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