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