]> sjero.net Git - wget/blob - src/ftp-basic.c
Silent warnings reported by clang.
[wget] / src / ftp-basic.c
1 /* Basic FTP routines.
2    Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3    2005, 2006, 2007, 2008, 2009, 2010 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   /* Skip the useless stuff and get what's inside the parentheses */
760   start = strchr (respline, '(');
761   if (start == NULL)
762     {
763       xfree (respline);
764       return FTPINVPASV;
765     }
766
767   /* Skip the first two void fields */
768   s = start + 1;
769   delim = *s++;
770   if (delim < 33 || delim > 126)
771     {
772       xfree (respline);
773       return FTPINVPASV;
774     }
775
776   for (i = 0; i < 2; i++)
777     {
778       if (*s++ != delim)
779         {
780           xfree (respline);
781         return FTPINVPASV;
782         }
783     }
784
785   /* Finally, get the port number */
786   tport = 0;
787   for (i = 1; c_isdigit (*s); s++)
788     {
789       if (i > 5)
790         {
791           xfree (respline);
792           return FTPINVPASV;
793         }
794       tport = (*s - '0') + 10 * tport;
795     }
796
797   /* Make sure that the response terminates correcty */
798   if (*s++ != delim)
799     {
800       xfree (respline);
801       return FTPINVPASV;
802     }
803
804   if (*s != ')')
805     {
806       xfree (respline);
807       return FTPINVPASV;
808     }
809
810   *port = tport;
811
812   xfree (respline);
813   return FTPOK;
814 }
815 #endif
816
817 /* Sends the TYPE request to the server.  */
818 uerr_t
819 ftp_type (int csock, int type)
820 {
821   char *request, *respline;
822   int nwritten;
823   uerr_t err;
824   char stype[2];
825
826   /* Construct argument.  */
827   stype[0] = type;
828   stype[1] = 0;
829   /* Send TYPE request.  */
830   request = ftp_request ("TYPE", stype);
831   nwritten = fd_write (csock, request, strlen (request), -1);
832   if (nwritten < 0)
833     {
834       xfree (request);
835       return WRITEFAILED;
836     }
837   xfree (request);
838   /* Get appropriate response.  */
839   err = ftp_response (csock, &respline);
840   if (err != FTPOK)
841     return err;
842   if (*respline != '2')
843     {
844       xfree (respline);
845       return FTPUNKNOWNTYPE;
846     }
847   xfree (respline);
848   /* All OK.  */
849   return FTPOK;
850 }
851
852 /* Changes the working directory by issuing a CWD command to the
853    server.  */
854 uerr_t
855 ftp_cwd (int csock, const char *dir)
856 {
857   char *request, *respline;
858   int nwritten;
859   uerr_t err;
860
861   /* Send CWD request.  */
862   request = ftp_request ("CWD", dir);
863   nwritten = fd_write (csock, request, strlen (request), -1);
864   if (nwritten < 0)
865     {
866       xfree (request);
867       return WRITEFAILED;
868     }
869   xfree (request);
870   /* Get appropriate response.  */
871   err = ftp_response (csock, &respline);
872   if (err != FTPOK)
873     return err;
874   if (*respline == '5')
875     {
876       xfree (respline);
877       return FTPNSFOD;
878     }
879   if (*respline != '2')
880     {
881       xfree (respline);
882       return FTPRERR;
883     }
884   xfree (respline);
885   /* All OK.  */
886   return FTPOK;
887 }
888
889 /* Sends REST command to the FTP server.  */
890 uerr_t
891 ftp_rest (int csock, wgint offset)
892 {
893   char *request, *respline;
894   int nwritten;
895   uerr_t err;
896
897   request = ftp_request ("REST", number_to_static_string (offset));
898   nwritten = fd_write (csock, request, strlen (request), -1);
899   if (nwritten < 0)
900     {
901       xfree (request);
902       return WRITEFAILED;
903     }
904   xfree (request);
905   /* Get appropriate response.  */
906   err = ftp_response (csock, &respline);
907   if (err != FTPOK)
908     return err;
909   if (*respline != '3')
910     {
911       xfree (respline);
912       return FTPRESTFAIL;
913     }
914   xfree (respline);
915   /* All OK.  */
916   return FTPOK;
917 }
918
919 /* Sends RETR command to the FTP server.  */
920 uerr_t
921 ftp_retr (int csock, const char *file)
922 {
923   char *request, *respline;
924   int nwritten;
925   uerr_t err;
926
927   /* Send RETR request.  */
928   request = ftp_request ("RETR", file);
929   nwritten = fd_write (csock, request, strlen (request), -1);
930   if (nwritten < 0)
931     {
932       xfree (request);
933       return WRITEFAILED;
934     }
935   xfree (request);
936   /* Get appropriate response.  */
937   err = ftp_response (csock, &respline);
938   if (err != FTPOK)
939     return err;
940   if (*respline == '5')
941     {
942       xfree (respline);
943       return FTPNSFOD;
944     }
945   if (*respline != '1')
946     {
947       xfree (respline);
948       return FTPRERR;
949     }
950   xfree (respline);
951   /* All OK.  */
952   return FTPOK;
953 }
954
955 /* Sends the LIST command to the server.  If FILE is NULL, send just
956    `LIST' (no space).  */
957 uerr_t
958 ftp_list (int csock, const char *file, enum stype rs)
959 {
960   char *request, *respline;
961   int nwritten;
962   uerr_t err;
963   bool ok = false;
964   size_t i = 0;
965   /* Try `LIST -a' first and revert to `LIST' in case of failure.  */
966   const char *list_commands[] = { "LIST -a",
967                                   "LIST" };
968
969   /* 2008-01-29  SMS.  For a VMS FTP server, where "LIST -a" may not
970      fail, but will never do what is desired here, skip directly to the
971      simple "LIST" command (assumed to be the last one in the list).
972   */
973   if (rs == ST_VMS)
974     i = countof (list_commands)- 1;
975
976   do {
977     /* Send request.  */
978     request = ftp_request (list_commands[i], file);
979     nwritten = fd_write (csock, request, strlen (request), -1);
980     if (nwritten < 0)
981       {
982         xfree (request);
983         return WRITEFAILED;
984       }
985     xfree (request);
986     /* Get appropriate response.  */
987     err = ftp_response (csock, &respline);
988     if (err == FTPOK)
989       {
990         if (*respline == '5')
991           {
992             err = FTPNSFOD;
993           }
994         else if (*respline == '1')
995           {
996             err = FTPOK;
997             ok = true;
998           }
999         else
1000           {
1001             err = FTPRERR;
1002           }
1003         xfree (respline);
1004       }
1005     ++i;
1006   } while (i < countof (list_commands) && !ok);
1007
1008   return err;
1009 }
1010
1011 /* Sends the SYST command to the server. */
1012 uerr_t
1013 ftp_syst (int csock, enum stype *server_type)
1014 {
1015   char *request, *respline;
1016   int nwritten;
1017   uerr_t err;
1018
1019   /* Send SYST request.  */
1020   request = ftp_request ("SYST", NULL);
1021   nwritten = fd_write (csock, request, strlen (request), -1);
1022   if (nwritten < 0)
1023     {
1024       xfree (request);
1025       return WRITEFAILED;
1026     }
1027   xfree (request);
1028
1029   /* Get appropriate response.  */
1030   err = ftp_response (csock, &respline);
1031   if (err != FTPOK)
1032     return err;
1033   if (*respline == '5')
1034     {
1035       xfree (respline);
1036       return FTPSRVERR;
1037     }
1038
1039   /* Skip the number (215, but 200 (!!!) in case of VMS) */
1040   strtok (respline, " ");
1041
1042   /* Which system type has been reported (we are interested just in the
1043      first word of the server response)?  */
1044   request = strtok (NULL, " ");
1045
1046   if (request == NULL)
1047     *server_type = ST_OTHER;
1048   else if (!strcasecmp (request, "VMS"))
1049     *server_type = ST_VMS;
1050   else if (!strcasecmp (request, "UNIX"))
1051     *server_type = ST_UNIX;
1052   else if (!strcasecmp (request, "WINDOWS_NT")
1053            || !strcasecmp (request, "WINDOWS2000"))
1054     *server_type = ST_WINNT;
1055   else if (!strcasecmp (request, "MACOS"))
1056     *server_type = ST_MACOS;
1057   else if (!strcasecmp (request, "OS/400"))
1058     *server_type = ST_OS400;
1059   else
1060     *server_type = ST_OTHER;
1061
1062   xfree (respline);
1063   /* All OK.  */
1064   return FTPOK;
1065 }
1066
1067 /* Sends the PWD command to the server. */
1068 uerr_t
1069 ftp_pwd (int csock, char **pwd)
1070 {
1071   char *request, *respline;
1072   int nwritten;
1073   uerr_t err;
1074
1075   /* Send PWD request.  */
1076   request = ftp_request ("PWD", NULL);
1077   nwritten = fd_write (csock, request, strlen (request), -1);
1078   if (nwritten < 0)
1079     {
1080       xfree (request);
1081       return WRITEFAILED;
1082     }
1083   xfree (request);
1084   /* Get appropriate response.  */
1085   err = ftp_response (csock, &respline);
1086   if (err != FTPOK)
1087     return err;
1088   if (*respline == '5')
1089     {
1090     err:
1091       xfree (respline);
1092       return FTPSRVERR;
1093     }
1094
1095   /* Skip the number (257), leading citation mark, trailing citation mark
1096      and everything following it. */
1097   strtok (respline, "\"");
1098   request = strtok (NULL, "\"");
1099   if (!request)
1100     /* Treat the malformed response as an error, which the caller has
1101        to handle gracefully anyway.  */
1102     goto err;
1103
1104   /* Has the `pwd' been already allocated?  Free! */
1105   xfree_null (*pwd);
1106
1107   *pwd = xstrdup (request);
1108
1109   xfree (respline);
1110   /* All OK.  */
1111   return FTPOK;
1112 }
1113
1114 /* Sends the SIZE command to the server, and returns the value in 'size'.
1115  * If an error occurs, size is set to zero. */
1116 uerr_t
1117 ftp_size (int csock, const char *file, wgint *size)
1118 {
1119   char *request, *respline;
1120   int nwritten;
1121   uerr_t err;
1122
1123   /* Send PWD request.  */
1124   request = ftp_request ("SIZE", file);
1125   nwritten = fd_write (csock, request, strlen (request), -1);
1126   if (nwritten < 0)
1127     {
1128       xfree (request);
1129       *size = 0;
1130       return WRITEFAILED;
1131     }
1132   xfree (request);
1133   /* Get appropriate response.  */
1134   err = ftp_response (csock, &respline);
1135   if (err != FTPOK)
1136     {
1137       *size = 0;
1138       return err;
1139     }
1140   if (*respline == '5')
1141     {
1142       /*
1143        * Probably means SIZE isn't supported on this server.
1144        * Error is nonfatal since SIZE isn't in RFC 959
1145        */
1146       xfree (respline);
1147       *size = 0;
1148       return FTPOK;
1149     }
1150
1151   errno = 0;
1152   *size = str_to_wgint (respline + 4, NULL, 10);
1153   if (errno)
1154     {
1155       /*
1156        * Couldn't parse the response for some reason.  On the (few)
1157        * tests I've done, the response is 213 <SIZE> with nothing else -
1158        * maybe something a bit more resilient is necessary.  It's not a
1159        * fatal error, however.
1160        */
1161       xfree (respline);
1162       *size = 0;
1163       return FTPOK;
1164     }
1165
1166   xfree (respline);
1167   /* All OK.  */
1168   return FTPOK;
1169 }
1170
1171 /* If URL's params are of the form "type=X", return character X.
1172    Otherwise, return 'I' (the default type).  */
1173 char
1174 ftp_process_type (const char *params)
1175 {
1176   if (params
1177       && 0 == strncasecmp (params, "type=", 5)
1178       && params[5] != '\0')
1179     return c_toupper (params[5]);
1180   else
1181     return 'I';
1182 }