]> sjero.net Git - wget/blob - src/ftp-basic.c
Automated merge.
[wget] / src / ftp-basic.c
1 /* Basic FTP routines.
2    Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
3    2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4
5 This file is part of GNU Wget.
6
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10  (at your option) any later version.
11
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Wget.  If not, see <http://www.gnu.org/licenses/>.
19
20 Additional permission under GNU GPL version 3 section 7
21
22 If you modify this program, or any covered work, by linking or
23 combining it with the OpenSSL project's OpenSSL library (or a
24 modified version of that library), containing parts covered by the
25 terms of the OpenSSL or SSLeay licenses, the Free Software Foundation
26 grants you additional permission to convey the resulting work.
27 Corresponding Source for a non-source form of such a combination
28 shall include the source code for the parts of OpenSSL used as well
29 as that of the covered work.  */
30
31 #include "wget.h"
32
33 #include <assert.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <errno.h>
37
38 #include <string.h>
39 #ifdef HAVE_UNISTD_H
40 # include <unistd.h>
41 #endif
42 #include "utils.h"
43 #include "connect.h"
44 #include "host.h"
45 #include "ftp.h"
46 #include "retr.h"
47
48 char ftp_last_respline[128];
49
50 \f
51 /* Get the response of FTP server and allocate enough room to handle
52    it.  <CR> and <LF> characters are stripped from the line, and the
53    line is 0-terminated.  All the response lines but the last one are
54    skipped.  The last line is determined as described in RFC959.
55
56    If the line is successfully read, FTPOK is returned, and *ret_line
57    is assigned a freshly allocated line.  Otherwise, FTPRERR is
58    returned, and the value of *ret_line should be ignored.  */
59
60 uerr_t
61 ftp_response (int fd, char **ret_line)
62 {
63   while (1)
64     {
65       char *p;
66       char *line = fd_read_line (fd);
67       if (!line)
68         return FTPRERR;
69
70       /* Strip trailing CRLF before printing the line, so that
71          quotting doesn't include bogus \012 and \015. */
72       p = strchr (line, '\0');
73       if (p > line && p[-1] == '\n')
74         *--p = '\0';
75       if (p > line && p[-1] == '\r')
76         *--p = '\0';
77
78       if (opt.server_response)
79         logprintf (LOG_NOTQUIET, "%s\n", 
80                    quotearg_style (escape_quoting_style, line));
81       else
82         DEBUGP (("%s\n", quotearg_style (escape_quoting_style, line)));
83
84       /* The last line of output is the one that begins with "ddd ". */
85       if (c_isdigit (line[0]) && c_isdigit (line[1]) && c_isdigit (line[2])
86           && line[3] == ' ')
87         {
88           strncpy (ftp_last_respline, line, sizeof (ftp_last_respline));
89           ftp_last_respline[sizeof (ftp_last_respline) - 1] = '\0';
90           *ret_line = line;
91           return FTPOK;
92         }
93       xfree (line);
94     }
95 }
96
97 /* Returns the malloc-ed FTP request, ending with <CR><LF>, printing
98    it if printing is required.  If VALUE is NULL, just use
99    command<CR><LF>.  */
100 static char *
101 ftp_request (const char *command, const char *value)
102 {
103   char *res;
104   if (value)
105     {
106       /* Check for newlines in VALUE (possibly injected by the %0A URL
107          escape) making the callers inadvertently send multiple FTP
108          commands at once.  Without this check an attacker could
109          intentionally redirect to ftp://server/fakedir%0Acommand.../
110          and execute arbitrary FTP command on a remote FTP server.  */
111       if (strpbrk (value, "\r\n"))
112         {
113           /* Copy VALUE to the stack and modify CR/LF to space. */
114           char *defanged, *p;
115           STRDUP_ALLOCA (defanged, value);
116           for (p = defanged; *p; p++)
117             if (*p == '\r' || *p == '\n')
118               *p = ' ';
119           DEBUGP (("\nDetected newlines in %s \"%s\"; changing to %s \"%s\"\n",
120                    command, quotearg_style (escape_quoting_style, value), 
121                    command, quotearg_style (escape_quoting_style, defanged)));
122           /* Make VALUE point to the defanged copy of the string. */
123           value = defanged;
124         }
125       res = concat_strings (command, " ", value, "\r\n", (char *) 0);
126     }
127   else
128     res = concat_strings (command, "\r\n", (char *) 0);
129   if (opt.server_response)
130     {
131       /* Hack: don't print out password.  */
132       if (strncmp (res, "PASS", 4) != 0)
133         logprintf (LOG_ALWAYS, "--> %s\n", res);
134       else
135         logputs (LOG_ALWAYS, "--> PASS Turtle Power!\n\n");
136     }
137   else
138     DEBUGP (("\n--> %s\n", res));
139   return res;
140 }
141
142 /* Sends the USER and PASS commands to the server, to control
143    connection socket csock.  */
144 uerr_t
145 ftp_login (int csock, const char *acc, const char *pass)
146 {
147   uerr_t err;
148   char *request, *respline;
149   int nwritten;
150
151   /* Get greeting.  */
152   err = ftp_response (csock, &respline);
153   if (err != FTPOK)
154     return err;
155   if (*respline != '2')
156     {
157       xfree (respline);
158       return FTPSRVERR;
159     }
160   xfree (respline);
161   /* Send USER username.  */
162   request = ftp_request ("USER", acc);
163   nwritten = fd_write (csock, request, strlen (request), -1);
164   if (nwritten < 0)
165     {
166       xfree (request);
167       return WRITEFAILED;
168     }
169   xfree (request);
170   /* Get appropriate response.  */
171   err = ftp_response (csock, &respline);
172   if (err != FTPOK)
173     return err;
174   /* An unprobable possibility of logging without a password.  */
175   if (*respline == '2')
176     {
177       xfree (respline);
178       return FTPOK;
179     }
180   /* Else, only response 3 is appropriate.  */
181   if (*respline != '3')
182     {
183       xfree (respline);
184       return FTPLOGREFUSED;
185     }
186 #ifdef ENABLE_OPIE
187   {
188     static const char *skey_head[] = {
189       "331 s/key ",
190       "331 opiekey "
191     };
192     size_t i;
193     const char *seed = NULL;
194
195     for (i = 0; i < countof (skey_head); i++)
196       {
197         int l = strlen (skey_head[i]);
198         if (0 == strncasecmp (skey_head[i], respline, l))
199           {
200             seed = respline + l;
201             break;
202           }
203       }
204     if (seed)
205       {
206         int skey_sequence = 0;
207
208         /* Extract the sequence from SEED.  */
209         for (; c_isdigit (*seed); seed++)
210           skey_sequence = 10 * skey_sequence + *seed - '0';
211         if (*seed == ' ')
212           ++seed;
213         else
214           {
215             xfree (respline);
216             return FTPLOGREFUSED;
217           }
218         /* Replace the password with the SKEY response to the
219            challenge.  */
220         pass = skey_response (skey_sequence, seed, pass);
221       }
222   }
223 #endif /* ENABLE_OPIE */
224   xfree (respline);
225   /* Send PASS password.  */
226   request = ftp_request ("PASS", pass);
227   nwritten = fd_write (csock, request, strlen (request), -1);
228   if (nwritten < 0)
229     {
230       xfree (request);
231       return WRITEFAILED;
232     }
233   xfree (request);
234   /* Get appropriate response.  */
235   err = ftp_response (csock, &respline);
236   if (err != FTPOK)
237     return err;
238   if (*respline != '2')
239     {
240       xfree (respline);
241       return FTPLOGINC;
242     }
243   xfree (respline);
244   /* All OK.  */
245   return FTPOK;
246 }
247
248 static void
249 ip_address_to_port_repr (const ip_address *addr, int port, char *buf, 
250                          size_t buflen)
251 {
252   unsigned char *ptr;
253
254   assert (addr->family == AF_INET);
255   /* buf must contain the argument of PORT (of the form a,b,c,d,e,f). */
256   assert (buflen >= 6 * 4);
257
258   ptr = IP_INADDR_DATA (addr);
259   snprintf (buf, buflen, "%d,%d,%d,%d,%d,%d", ptr[0], ptr[1],
260             ptr[2], ptr[3], (port & 0xff00) >> 8, port & 0xff);
261   buf[buflen - 1] = '\0';
262 }
263
264 /* Bind a port and send the appropriate PORT command to the FTP
265    server.  Use acceptport after RETR, to get the socket of data
266    connection.  */
267 uerr_t
268 ftp_port (int csock, int *local_sock)
269 {
270   uerr_t err;
271   char *request, *respline;
272   ip_address addr;
273   int nwritten;
274   int port;
275   /* Must contain the argument of PORT (of the form a,b,c,d,e,f). */
276   char bytes[6 * 4 + 1];
277
278   /* Get the address of this side of the connection. */
279   if (!socket_ip_address (csock, &addr, ENDPOINT_LOCAL))
280     return FTPSYSERR;
281
282   assert (addr.family == AF_INET);
283
284   /* Setting port to 0 lets the system choose a free port.  */
285   port = 0;
286
287   /* Bind the port.  */
288   *local_sock = bind_local (&addr, &port);
289   if (*local_sock < 0)
290     return FTPSYSERR;
291
292   /* Construct the argument of PORT (of the form a,b,c,d,e,f). */
293   ip_address_to_port_repr (&addr, port, bytes, sizeof (bytes));
294
295   /* Send PORT request.  */
296   request = ftp_request ("PORT", bytes);
297   nwritten = fd_write (csock, request, strlen (request), -1);
298   if (nwritten < 0)
299     {
300       xfree (request);
301       fd_close (*local_sock);
302       return WRITEFAILED;
303     }
304   xfree (request);
305
306   /* Get appropriate response.  */
307   err = ftp_response (csock, &respline);
308   if (err != FTPOK)
309     {
310       fd_close (*local_sock);
311       return err;
312     }
313   if (*respline != '2')
314     {
315       xfree (respline);
316       fd_close (*local_sock);
317       return FTPPORTERR;
318     }
319   xfree (respline);
320   return FTPOK;
321 }
322
323 #ifdef ENABLE_IPV6
324 static void
325 ip_address_to_lprt_repr (const ip_address *addr, int port, char *buf, 
326                          size_t buflen)
327 {
328   unsigned char *ptr = IP_INADDR_DATA (addr);
329
330   /* buf must contain the argument of LPRT (of the form af,n,h1,h2,...,hn,p1,p2). */
331   assert (buflen >= 21 * 4);
332
333   /* Construct the argument of LPRT (of the form af,n,h1,h2,...,hn,p1,p2). */
334   switch (addr->family) 
335     {
336     case AF_INET: 
337       snprintf (buf, buflen, "%d,%d,%d,%d,%d,%d,%d,%d,%d", 4, 4, 
338                 ptr[0], ptr[1], ptr[2], ptr[3], 2,
339                 (port & 0xff00) >> 8, port & 0xff);
340       break;
341     case AF_INET6: 
342       snprintf (buf, buflen,
343                 "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
344                 6, 16,
345                 ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7], 
346                 ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15],
347                 2, (port & 0xff00) >> 8, port & 0xff);
348       break;
349     default:
350       abort ();
351     }
352 }
353
354 /* Bind a port and send the appropriate PORT command to the FTP
355    server.  Use acceptport after RETR, to get the socket of data
356    connection.  */
357 uerr_t
358 ftp_lprt (int csock, int *local_sock)
359 {
360   uerr_t err;
361   char *request, *respline;
362   ip_address addr;
363   int nwritten;
364   int port;
365   /* Must contain the argument of LPRT (of the form af,n,h1,h2,...,hn,p1,p2). */
366   char bytes[21 * 4 + 1];
367
368   /* Get the address of this side of the connection. */
369   if (!socket_ip_address (csock, &addr, ENDPOINT_LOCAL))
370     return FTPSYSERR;
371
372   assert (addr.family == AF_INET || addr.family == AF_INET6);
373
374   /* Setting port to 0 lets the system choose a free port.  */
375   port = 0;
376
377   /* Bind the port.  */
378   *local_sock = bind_local (&addr, &port);
379   if (*local_sock < 0)
380     return FTPSYSERR;
381
382   /* Construct the argument of LPRT (of the form af,n,h1,h2,...,hn,p1,p2). */
383   ip_address_to_lprt_repr (&addr, port, bytes, sizeof (bytes));
384
385   /* Send PORT request.  */
386   request = ftp_request ("LPRT", bytes);
387   nwritten = fd_write (csock, request, strlen (request), -1);
388   if (nwritten < 0)
389     {
390       xfree (request);
391       fd_close (*local_sock);
392       return WRITEFAILED;
393     }
394   xfree (request);
395   /* Get appropriate response.  */
396   err = ftp_response (csock, &respline);
397   if (err != FTPOK)
398     {
399       fd_close (*local_sock);
400       return err;
401     }
402   if (*respline != '2')
403     {
404       xfree (respline);
405       fd_close (*local_sock);
406       return FTPPORTERR;
407     }
408   xfree (respline);
409   return FTPOK;
410 }
411
412 static void
413 ip_address_to_eprt_repr (const ip_address *addr, int port, char *buf, 
414                          size_t buflen)
415 {
416   int afnum;
417
418   /* buf must contain the argument of EPRT (of the form |af|addr|port|). 
419    * 4 chars for the | separators, INET6_ADDRSTRLEN chars for addr  
420    * 1 char for af (1-2) and 5 chars for port (0-65535) */
421   assert (buflen >= 4 + INET6_ADDRSTRLEN + 1 + 5); 
422
423   /* Construct the argument of EPRT (of the form |af|addr|port|). */
424   afnum = (addr->family == AF_INET ? 1 : 2);
425   snprintf (buf, buflen, "|%d|%s|%d|", afnum, print_address (addr), port);
426   buf[buflen - 1] = '\0';
427 }
428
429 /* Bind a port and send the appropriate PORT command to the FTP
430    server.  Use acceptport after RETR, to get the socket of data
431    connection.  */
432 uerr_t
433 ftp_eprt (int csock, int *local_sock)
434 {
435   uerr_t err;
436   char *request, *respline;
437   ip_address addr;
438   int nwritten;
439   int port;
440   /* Must contain the argument of EPRT (of the form |af|addr|port|). 
441    * 4 chars for the | separators, INET6_ADDRSTRLEN chars for addr  
442    * 1 char for af (1-2) and 5 chars for port (0-65535) */
443   char bytes[4 + INET6_ADDRSTRLEN + 1 + 5 + 1];
444
445   /* Get the address of this side of the connection. */
446   if (!socket_ip_address (csock, &addr, ENDPOINT_LOCAL))
447     return FTPSYSERR;
448
449   /* Setting port to 0 lets the system choose a free port.  */
450   port = 0;
451
452   /* Bind the port.  */
453   *local_sock = bind_local (&addr, &port);
454   if (*local_sock < 0)
455     return FTPSYSERR;
456
457   /* Construct the argument of EPRT (of the form |af|addr|port|). */
458   ip_address_to_eprt_repr (&addr, port, bytes, sizeof (bytes));
459
460   /* Send PORT request.  */
461   request = ftp_request ("EPRT", bytes);
462   nwritten = fd_write (csock, request, strlen (request), -1);
463   if (nwritten < 0)
464     {
465       xfree (request);
466       fd_close (*local_sock);
467       return WRITEFAILED;
468     }
469   xfree (request);
470   /* Get appropriate response.  */
471   err = ftp_response (csock, &respline);
472   if (err != FTPOK)
473     {
474       fd_close (*local_sock);
475       return err;
476     }
477   if (*respline != '2')
478     {
479       xfree (respline);
480       fd_close (*local_sock);
481       return FTPPORTERR;
482     }
483   xfree (respline);
484   return FTPOK;
485 }
486 #endif
487
488 /* Similar to ftp_port, but uses `PASV' to initiate the passive FTP
489    transfer.  Reads the response from server and parses it.  Reads the
490    host and port addresses and returns them.  */
491 uerr_t
492 ftp_pasv (int csock, ip_address *addr, int *port)
493 {
494   char *request, *respline, *s;
495   int nwritten, i;
496   uerr_t err;
497   unsigned char tmp[6];
498
499   assert (addr != NULL);
500   assert (port != NULL);
501
502   xzero (*addr);
503
504   /* Form the request.  */
505   request = ftp_request ("PASV", NULL);
506   /* And send it.  */
507   nwritten = fd_write (csock, request, strlen (request), -1);
508   if (nwritten < 0)
509     {
510       xfree (request);
511       return WRITEFAILED;
512     }
513   xfree (request);
514   /* Get the server response.  */
515   err = ftp_response (csock, &respline);
516   if (err != FTPOK)
517     return err;
518   if (*respline != '2')
519     {
520       xfree (respline);
521       return FTPNOPASV;
522     }
523   /* Parse the request.  */
524   s = respline;
525   for (s += 4; *s && !c_isdigit (*s); s++)
526     ;
527   if (!*s)
528     return FTPINVPASV;
529   for (i = 0; i < 6; i++)
530     {
531       tmp[i] = 0;
532       for (; c_isdigit (*s); s++)
533         tmp[i] = (*s - '0') + 10 * tmp[i];
534       if (*s == ',')
535         s++;
536       else if (i < 5)
537         {
538           /* When on the last number, anything can be a terminator.  */
539           xfree (respline);
540           return FTPINVPASV;
541         }
542     }
543   xfree (respline);
544
545   addr->family = AF_INET;
546   memcpy (IP_INADDR_DATA (addr), tmp, 4);
547   *port = ((tmp[4] << 8) & 0xff00) + tmp[5];
548
549   return FTPOK;
550 }
551
552 #ifdef ENABLE_IPV6
553 /* Similar to ftp_lprt, but uses `LPSV' to initiate the passive FTP
554    transfer.  Reads the response from server and parses it.  Reads the
555    host and port addresses and returns them.  */
556 uerr_t
557 ftp_lpsv (int csock, ip_address *addr, int *port)
558 {
559   char *request, *respline, *s;
560   int nwritten, i, af, addrlen, portlen;
561   uerr_t err;
562   unsigned char tmp[16];
563   unsigned char tmpprt[2];
564
565   assert (addr != NULL);
566   assert (port != NULL);
567
568   xzero (*addr);
569
570   /* Form the request.  */
571   request = ftp_request ("LPSV", NULL);
572
573   /* And send it.  */
574   nwritten = fd_write (csock, request, strlen (request), -1);
575   if (nwritten < 0)
576     {
577       xfree (request);
578       return WRITEFAILED;
579     }
580   xfree (request);
581
582   /* Get the server response.  */
583   err = ftp_response (csock, &respline);
584   if (err != FTPOK)
585     return err;
586   if (*respline != '2')
587     {
588       xfree (respline);
589       return FTPNOPASV;
590     }  
591
592   /* Parse the response.  */
593   s = respline;
594   for (s += 4; *s && !c_isdigit (*s); s++)
595     ;
596   if (!*s)
597     return FTPINVPASV;
598
599   /* First, get the address family */
600   af = 0;
601   for (; c_isdigit (*s); s++)
602     af = (*s - '0') + 10 * af;
603
604   if (af != 4 && af != 6)
605     {
606       xfree (respline);
607       return FTPINVPASV;
608     }
609
610   if (!*s || *s++ != ',')
611     {
612       xfree (respline);
613       return FTPINVPASV;
614     }
615
616   /* Then, get the address length */
617   addrlen = 0;
618   for (; c_isdigit (*s); s++)
619     addrlen = (*s - '0') + 10 * addrlen;
620
621   if (!*s || *s++ != ',')
622     {
623       xfree (respline);
624       return FTPINVPASV;
625     }
626
627   if (addrlen > 16)
628     {
629       xfree (respline);
630       return FTPINVPASV;
631     }
632
633   if ((af == 4 && addrlen != 4)
634       || (af == 6 && addrlen != 16))
635     {
636       xfree (respline);
637       return FTPINVPASV;
638     }
639
640   /* Now, we get the actual address */
641   for (i = 0; i < addrlen; i++)
642     {
643       tmp[i] = 0;
644       for (; c_isdigit (*s); s++)
645         tmp[i] = (*s - '0') + 10 * tmp[i];
646       if (*s == ',')
647         s++;
648       else
649         {
650           xfree (respline);
651           return FTPINVPASV;
652         }
653     }
654
655   /* Now, get the port length */
656   portlen = 0;
657   for (; c_isdigit (*s); s++)
658     portlen = (*s - '0') + 10 * portlen;
659
660   if (!*s || *s++ != ',')
661     {
662       xfree (respline);
663       return FTPINVPASV;
664     }
665
666   if (portlen > 2)
667     {
668       xfree (respline);
669       return FTPINVPASV;
670     }
671
672   /* Finally, we get the port number */
673   tmpprt[0] = 0;
674   for (; c_isdigit (*s); s++)
675     tmpprt[0] = (*s - '0') + 10 * tmpprt[0];
676
677   if (!*s || *s++ != ',')
678     {
679       xfree (respline);
680       return FTPINVPASV;
681     }
682
683   tmpprt[1] = 0;
684   for (; c_isdigit (*s); s++)
685     tmpprt[1] = (*s - '0') + 10 * tmpprt[1];
686
687   assert (s != NULL);
688
689   if (af == 4)
690     {
691       addr->family = AF_INET;
692       memcpy (IP_INADDR_DATA (addr), tmp, 4);
693       *port = ((tmpprt[0] << 8) & 0xff00) + tmpprt[1];
694       DEBUGP (("lpsv addr is: %s\n", print_address(addr)));
695       DEBUGP (("tmpprt[0] is: %d\n", tmpprt[0]));
696       DEBUGP (("tmpprt[1] is: %d\n", tmpprt[1]));
697       DEBUGP (("*port is: %d\n", *port));
698     }
699   else
700     {
701       assert (af == 6);
702       addr->family = AF_INET6;
703       memcpy (IP_INADDR_DATA (addr), tmp, 16);
704       *port = ((tmpprt[0] << 8) & 0xff00) + tmpprt[1];
705       DEBUGP (("lpsv addr is: %s\n", print_address(addr)));
706       DEBUGP (("tmpprt[0] is: %d\n", tmpprt[0]));
707       DEBUGP (("tmpprt[1] is: %d\n", tmpprt[1]));
708       DEBUGP (("*port is: %d\n", *port));
709     }
710
711   xfree (respline);
712   return FTPOK;
713 }
714
715 /* Similar to ftp_eprt, but uses `EPSV' to initiate the passive FTP
716    transfer.  Reads the response from server and parses it.  Reads the
717    host and port addresses and returns them.  */
718 uerr_t
719 ftp_epsv (int csock, ip_address *ip, int *port)
720 {
721   char *request, *respline, *start, delim, *s;
722   int nwritten, i;
723   uerr_t err;
724   int tport;
725
726   assert (ip != NULL);
727   assert (port != NULL);
728
729   /* IP already contains the IP address of the control connection's
730      peer, so we don't need to call socket_ip_address here.  */
731
732   /* Form the request.  */
733   /* EPSV 1 means that we ask for IPv4 and EPSV 2 means that we ask for IPv6. */
734   request = ftp_request ("EPSV", (ip->family == AF_INET ? "1" : "2"));
735
736   /* And send it.  */
737   nwritten = fd_write (csock, request, strlen (request), -1);
738   if (nwritten < 0)
739     {
740       xfree (request);
741       return WRITEFAILED;
742     }
743   xfree (request);
744
745   /* Get the server response.  */
746   err = ftp_response (csock, &respline);
747   if (err != FTPOK)
748     return err;
749   if (*respline != '2')
750     {
751       xfree (respline);
752       return FTPNOPASV;
753     }  
754
755   assert (respline != NULL);
756
757   DEBUGP(("respline is %s\n", respline));
758
759   /* Parse the response.  */
760   s = respline;
761
762   /* Skip the useless stuff and get what's inside the parentheses */
763   start = strchr (respline, '(');
764   if (start == NULL)
765     {
766       xfree (respline);
767       return FTPINVPASV;
768     }  
769
770   /* Skip the first two void fields */
771   s = start + 1;
772   delim = *s++;
773   if (delim < 33 || delim > 126)
774     {
775       xfree (respline);
776       return FTPINVPASV;
777     }  
778
779   for (i = 0; i < 2; i++)
780     {
781       if (*s++ != delim) 
782         {
783           xfree (respline);
784         return FTPINVPASV;
785         }  
786     }
787
788   /* Finally, get the port number */
789   tport = 0; 
790   for (i = 1; c_isdigit (*s); s++) 
791     {
792       if (i > 5)
793         {
794           xfree (respline);
795           return FTPINVPASV;
796         }  
797       tport = (*s - '0') + 10 * tport;
798     }
799
800   /* Make sure that the response terminates correcty */
801   if (*s++ != delim)
802     {
803       xfree (respline);
804       return FTPINVPASV;
805     }  
806
807   if (*s++ != ')')
808     {
809       xfree (respline);
810       return FTPINVPASV;
811     }  
812
813   *port = tport;
814
815   xfree (respline);
816   return FTPOK;
817 }
818 #endif
819
820 /* Sends the TYPE request to the server.  */
821 uerr_t
822 ftp_type (int csock, int type)
823 {
824   char *request, *respline;
825   int nwritten;
826   uerr_t err;
827   char stype[2];
828
829   /* Construct argument.  */
830   stype[0] = type;
831   stype[1] = 0;
832   /* Send TYPE request.  */
833   request = ftp_request ("TYPE", stype);
834   nwritten = fd_write (csock, request, strlen (request), -1);
835   if (nwritten < 0)
836     {
837       xfree (request);
838       return WRITEFAILED;
839     }
840   xfree (request);
841   /* Get appropriate response.  */
842   err = ftp_response (csock, &respline);
843   if (err != FTPOK)
844     return err;
845   if (*respline != '2')
846     {
847       xfree (respline);
848       return FTPUNKNOWNTYPE;
849     }
850   xfree (respline);
851   /* All OK.  */
852   return FTPOK;
853 }
854
855 /* Changes the working directory by issuing a CWD command to the
856    server.  */
857 uerr_t
858 ftp_cwd (int csock, const char *dir)
859 {
860   char *request, *respline;
861   int nwritten;
862   uerr_t err;
863
864   /* Send CWD request.  */
865   request = ftp_request ("CWD", dir);
866   nwritten = fd_write (csock, request, strlen (request), -1);
867   if (nwritten < 0)
868     {
869       xfree (request);
870       return WRITEFAILED;
871     }
872   xfree (request);
873   /* Get appropriate response.  */
874   err = ftp_response (csock, &respline);
875   if (err != FTPOK)
876     return err;
877   if (*respline == '5')
878     {
879       xfree (respline);
880       return FTPNSFOD;
881     }
882   if (*respline != '2')
883     {
884       xfree (respline);
885       return FTPRERR;
886     }
887   xfree (respline);
888   /* All OK.  */
889   return FTPOK;
890 }
891
892 /* Sends DELE command to the FTP server.  */
893 uerr_t
894 ftp_dele (int csock, const char *file)
895 {
896   char *request, *respline;
897   int nwritten;
898   uerr_t err;
899
900   /* Send DELE request.  */
901   request = ftp_request ("DELE", file);
902   nwritten = fd_write (csock, request, strlen (request), -1.0);
903   if (nwritten < 0)
904     {
905       xfree (request);
906       return WRITEFAILED;
907     }
908   xfree (request);
909   /* Get appropriate response.  */
910   err = ftp_response (csock, &respline);
911   if (err != FTPOK)
912     return err;                 /* Return with early bad status. */
913
914   /* All OK, so far.  */
915   if (*respline == '5')
916     {
917       err = FTPNSFOD;           /* Permanent Negative Completion. */
918     }
919   else if (*respline != '2')    /* Success might be 226 or 250 (or ???). */
920     {
921       err = FTPRERR;            /* Not Positive Completion. */
922     }
923
924   xfree (respline);             /* Free "respline" storage. */
925   return err;                   /* Return response-based status code. */
926 }
927
928 /* Sends REST command to the FTP server.  */
929 uerr_t
930 ftp_rest (int csock, wgint offset)
931 {
932   char *request, *respline;
933   int nwritten;
934   uerr_t err;
935
936   request = ftp_request ("REST", number_to_static_string (offset));
937   nwritten = fd_write (csock, request, strlen (request), -1);
938   if (nwritten < 0)
939     {
940       xfree (request);
941       return WRITEFAILED;
942     }
943   xfree (request);
944   /* Get appropriate response.  */
945   err = ftp_response (csock, &respline);
946   if (err != FTPOK)
947     return err;
948   if (*respline != '3')
949     {
950       xfree (respline);
951       return FTPRESTFAIL;
952     }
953   xfree (respline);
954   /* All OK.  */
955   return FTPOK;
956 }
957
958 /* Sends RETR command to the FTP server.  */
959 uerr_t
960 ftp_retr (int csock, const char *file)
961 {
962   char *request, *respline;
963   int nwritten;
964   uerr_t err;
965
966   /* Send RETR request.  */
967   request = ftp_request ("RETR", file);
968   nwritten = fd_write (csock, request, strlen (request), -1);
969   if (nwritten < 0)
970     {
971       xfree (request);
972       return WRITEFAILED;
973     }
974   xfree (request);
975   /* Get appropriate response.  */
976   err = ftp_response (csock, &respline);
977   if (err != FTPOK)
978     return err;
979   if (*respline == '5')
980     {
981       xfree (respline);
982       return FTPNSFOD;
983     }
984   if (*respline != '1')
985     {
986       xfree (respline);
987       return FTPRERR;
988     }
989   xfree (respline);
990   /* All OK.  */
991   return FTPOK;
992 }
993
994 /* Sends the LIST command to the server.  If FILE is NULL, send just
995    `LIST' (no space).  */
996 uerr_t
997 ftp_list (int csock, const char *file, enum stype rs)
998 {
999   char *request, *respline;
1000   int nwritten;
1001   uerr_t err;
1002   bool ok = false;
1003   size_t i = 0;
1004   /* Try `LIST -a' first and revert to `LIST' in case of failure.  */
1005   const char *list_commands[] = { "LIST -a", 
1006                                   "LIST" };
1007
1008   /* 2008-01-29  SMS.  For a VMS FTP server, where "LIST -a" may not
1009      fail, but will never do what is desired here, skip directly to the
1010      simple "LIST" command (assumed to be the last one in the list).
1011   */
1012   if (rs == ST_VMS)
1013     i = countof (list_commands)- 1;
1014
1015   do {
1016     /* Send request.  */
1017     request = ftp_request (list_commands[i], file);
1018     nwritten = fd_write (csock, request, strlen (request), -1);
1019     if (nwritten < 0)
1020       {
1021         xfree (request);
1022         return WRITEFAILED;
1023       }
1024     xfree (request);
1025     /* Get appropriate response.  */
1026     err = ftp_response (csock, &respline);
1027     if (err == FTPOK)
1028       {
1029         if (*respline == '5')
1030           {
1031             err = FTPNSFOD;
1032           }
1033         else if (*respline == '1')
1034           {
1035             err = FTPOK;
1036             ok = true;
1037           }
1038         else 
1039           {
1040             err = FTPRERR;
1041           }
1042         xfree (respline);
1043       }
1044     ++i;
1045   } while (i < countof (list_commands) && !ok);
1046   
1047   return err;
1048 }
1049
1050 /* Sends the SYST command to the server. */
1051 uerr_t
1052 ftp_syst (int csock, enum stype *server_type)
1053 {
1054   char *request, *respline;
1055   int nwritten;
1056   uerr_t err;
1057
1058   /* Send SYST request.  */
1059   request = ftp_request ("SYST", NULL);
1060   nwritten = fd_write (csock, request, strlen (request), -1);
1061   if (nwritten < 0)
1062     {
1063       xfree (request);
1064       return WRITEFAILED;
1065     }
1066   xfree (request);
1067
1068   /* Get appropriate response.  */
1069   err = ftp_response (csock, &respline);
1070   if (err != FTPOK)
1071     return err;
1072   if (*respline == '5')
1073     {
1074       xfree (respline);
1075       return FTPSRVERR;
1076     }
1077
1078   /* Skip the number (215, but 200 (!!!) in case of VMS) */
1079   strtok (respline, " ");
1080
1081   /* Which system type has been reported (we are interested just in the
1082      first word of the server response)?  */
1083   request = strtok (NULL, " ");
1084
1085   if (request == NULL)
1086     *server_type = ST_OTHER;
1087   else if (!strcasecmp (request, "VMS"))
1088     *server_type = ST_VMS;
1089   else if (!strcasecmp (request, "UNIX"))
1090     *server_type = ST_UNIX;
1091   else if (!strcasecmp (request, "WINDOWS_NT")
1092            || !strcasecmp (request, "WINDOWS2000"))
1093     *server_type = ST_WINNT;
1094   else if (!strcasecmp (request, "MACOS"))
1095     *server_type = ST_MACOS;
1096   else if (!strcasecmp (request, "OS/400"))
1097     *server_type = ST_OS400;
1098   else
1099     *server_type = ST_OTHER;
1100
1101   xfree (respline);
1102   /* All OK.  */
1103   return FTPOK;
1104 }
1105
1106 /* Sends the PWD command to the server. */
1107 uerr_t
1108 ftp_pwd (int csock, char **pwd)
1109 {
1110   char *request, *respline;
1111   int nwritten;
1112   uerr_t err;
1113
1114   /* Send PWD request.  */
1115   request = ftp_request ("PWD", NULL);
1116   nwritten = fd_write (csock, request, strlen (request), -1);
1117   if (nwritten < 0)
1118     {
1119       xfree (request);
1120       return WRITEFAILED;
1121     }
1122   xfree (request);
1123   /* Get appropriate response.  */
1124   err = ftp_response (csock, &respline);
1125   if (err != FTPOK)
1126     return err;
1127   if (*respline == '5')
1128     {
1129     err:
1130       xfree (respline);
1131       return FTPSRVERR;
1132     }
1133
1134   /* Skip the number (257), leading citation mark, trailing citation mark
1135      and everything following it. */
1136   strtok (respline, "\"");
1137   request = strtok (NULL, "\"");
1138   if (!request)
1139     /* Treat the malformed response as an error, which the caller has
1140        to handle gracefully anyway.  */
1141     goto err;
1142
1143   /* Has the `pwd' been already allocated?  Free! */
1144   xfree_null (*pwd);
1145
1146   *pwd = xstrdup (request);
1147
1148   xfree (respline);
1149   /* All OK.  */
1150   return FTPOK;
1151 }
1152
1153 /* Sends the SIZE command to the server, and returns the value in 'size'.
1154  * If an error occurs, size is set to zero. */
1155 uerr_t
1156 ftp_size (int csock, const char *file, wgint *size)
1157 {
1158   char *request, *respline;
1159   int nwritten;
1160   uerr_t err;
1161
1162   /* Send PWD request.  */
1163   request = ftp_request ("SIZE", file);
1164   nwritten = fd_write (csock, request, strlen (request), -1);
1165   if (nwritten < 0)
1166     {
1167       xfree (request);
1168       *size = 0;
1169       return WRITEFAILED;
1170     }
1171   xfree (request);
1172   /* Get appropriate response.  */
1173   err = ftp_response (csock, &respline);
1174   if (err != FTPOK)
1175     {
1176       *size = 0;
1177       return err;
1178     }
1179   if (*respline == '5')
1180     {
1181       /* 
1182        * Probably means SIZE isn't supported on this server.
1183        * Error is nonfatal since SIZE isn't in RFC 959 
1184        */
1185       xfree (respline);
1186       *size = 0;
1187       return FTPOK;
1188     }
1189
1190   errno = 0;
1191   *size = str_to_wgint (respline + 4, NULL, 10);
1192   if (errno)
1193     {
1194       /* 
1195        * Couldn't parse the response for some reason.  On the (few)
1196        * tests I've done, the response is 213 <SIZE> with nothing else -
1197        * maybe something a bit more resilient is necessary.  It's not a
1198        * fatal error, however.
1199        */
1200       xfree (respline);
1201       *size = 0;
1202       return FTPOK;
1203     }
1204
1205   xfree (respline);
1206   /* All OK.  */
1207   return FTPOK;
1208 }
1209
1210 /* If URL's params are of the form "type=X", return character X.
1211    Otherwise, return 'I' (the default type).  */
1212 char
1213 ftp_process_type (const char *params)
1214 {
1215   if (params
1216       && 0 == strncasecmp (params, "type=", 5)
1217       && params[5] != '\0')
1218     return c_toupper (params[5]);
1219   else
1220     return 'I';
1221 }