]> sjero.net Git - wget/blob - src/ftp-basic.c
Undo the USE_GNULIB_ALLOC defines.
[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 REST command to the FTP server.  */
891 uerr_t
892 ftp_rest (int csock, wgint offset)
893 {
894   char *request, *respline;
895   int nwritten;
896   uerr_t err;
897
898   request = ftp_request ("REST", number_to_static_string (offset));
899   nwritten = fd_write (csock, request, strlen (request), -1);
900   if (nwritten < 0)
901     {
902       xfree (request);
903       return WRITEFAILED;
904     }
905   xfree (request);
906   /* Get appropriate response.  */
907   err = ftp_response (csock, &respline);
908   if (err != FTPOK)
909     return err;
910   if (*respline != '3')
911     {
912       xfree (respline);
913       return FTPRESTFAIL;
914     }
915   xfree (respline);
916   /* All OK.  */
917   return FTPOK;
918 }
919
920 /* Sends RETR command to the FTP server.  */
921 uerr_t
922 ftp_retr (int csock, const char *file)
923 {
924   char *request, *respline;
925   int nwritten;
926   uerr_t err;
927
928   /* Send RETR request.  */
929   request = ftp_request ("RETR", file);
930   nwritten = fd_write (csock, request, strlen (request), -1);
931   if (nwritten < 0)
932     {
933       xfree (request);
934       return WRITEFAILED;
935     }
936   xfree (request);
937   /* Get appropriate response.  */
938   err = ftp_response (csock, &respline);
939   if (err != FTPOK)
940     return err;
941   if (*respline == '5')
942     {
943       xfree (respline);
944       return FTPNSFOD;
945     }
946   if (*respline != '1')
947     {
948       xfree (respline);
949       return FTPRERR;
950     }
951   xfree (respline);
952   /* All OK.  */
953   return FTPOK;
954 }
955
956 /* Sends the LIST command to the server.  If FILE is NULL, send just
957    `LIST' (no space).  */
958 uerr_t
959 ftp_list (int csock, const char *file)
960 {
961   char *request, *respline;
962   int nwritten;
963   uerr_t err;
964   bool ok = false;
965   int i = 0;
966   /* Try `LIST -a' first and revert to `LIST' in case of failure.  */
967   const char *list_commands[] = { "LIST -a", 
968                                   "LIST" };
969
970   do {
971     /* Send request.  */
972     request = ftp_request (list_commands[i], file);
973     nwritten = fd_write (csock, request, strlen (request), -1);
974     if (nwritten < 0)
975       {
976         xfree (request);
977         return WRITEFAILED;
978       }
979     xfree (request);
980     /* Get appropriate response.  */
981     err = ftp_response (csock, &respline);
982     if (err == FTPOK)
983       {
984         if (*respline == '5')
985           {
986             err = FTPNSFOD;
987           }
988         else if (*respline == '1')
989           {
990             err = FTPOK;
991             ok = true;
992           }
993         else 
994           {
995             err = FTPRERR;
996           }
997         xfree (respline);
998       }
999     ++i;
1000   } while (i < countof (list_commands) && !ok);
1001   
1002   return err;
1003 }
1004
1005 /* Sends the SYST command to the server. */
1006 uerr_t
1007 ftp_syst (int csock, enum stype *server_type)
1008 {
1009   char *request, *respline;
1010   int nwritten;
1011   uerr_t err;
1012
1013   /* Send SYST request.  */
1014   request = ftp_request ("SYST", NULL);
1015   nwritten = fd_write (csock, request, strlen (request), -1);
1016   if (nwritten < 0)
1017     {
1018       xfree (request);
1019       return WRITEFAILED;
1020     }
1021   xfree (request);
1022
1023   /* Get appropriate response.  */
1024   err = ftp_response (csock, &respline);
1025   if (err != FTPOK)
1026     return err;
1027   if (*respline == '5')
1028     {
1029       xfree (respline);
1030       return FTPSRVERR;
1031     }
1032
1033   /* Skip the number (215, but 200 (!!!) in case of VMS) */
1034   strtok (respline, " ");
1035
1036   /* Which system type has been reported (we are interested just in the
1037      first word of the server response)?  */
1038   request = strtok (NULL, " ");
1039
1040   if (request == NULL)
1041     *server_type = ST_OTHER;
1042   else if (!strcasecmp (request, "VMS"))
1043     *server_type = ST_VMS;
1044   else if (!strcasecmp (request, "UNIX"))
1045     *server_type = ST_UNIX;
1046   else if (!strcasecmp (request, "WINDOWS_NT")
1047            || !strcasecmp (request, "WINDOWS2000"))
1048     *server_type = ST_WINNT;
1049   else if (!strcasecmp (request, "MACOS"))
1050     *server_type = ST_MACOS;
1051   else if (!strcasecmp (request, "OS/400"))
1052     *server_type = ST_OS400;
1053   else
1054     *server_type = ST_OTHER;
1055
1056   xfree (respline);
1057   /* All OK.  */
1058   return FTPOK;
1059 }
1060
1061 /* Sends the PWD command to the server. */
1062 uerr_t
1063 ftp_pwd (int csock, char **pwd)
1064 {
1065   char *request, *respline;
1066   int nwritten;
1067   uerr_t err;
1068
1069   /* Send PWD request.  */
1070   request = ftp_request ("PWD", NULL);
1071   nwritten = fd_write (csock, request, strlen (request), -1);
1072   if (nwritten < 0)
1073     {
1074       xfree (request);
1075       return WRITEFAILED;
1076     }
1077   xfree (request);
1078   /* Get appropriate response.  */
1079   err = ftp_response (csock, &respline);
1080   if (err != FTPOK)
1081     return err;
1082   if (*respline == '5')
1083     {
1084     err:
1085       xfree (respline);
1086       return FTPSRVERR;
1087     }
1088
1089   /* Skip the number (257), leading citation mark, trailing citation mark
1090      and everything following it. */
1091   strtok (respline, "\"");
1092   request = strtok (NULL, "\"");
1093   if (!request)
1094     /* Treat the malformed response as an error, which the caller has
1095        to handle gracefully anyway.  */
1096     goto err;
1097
1098   /* Has the `pwd' been already allocated?  Free! */
1099   xfree_null (*pwd);
1100
1101   *pwd = xstrdup (request);
1102
1103   xfree (respline);
1104   /* All OK.  */
1105   return FTPOK;
1106 }
1107
1108 /* Sends the SIZE command to the server, and returns the value in 'size'.
1109  * If an error occurs, size is set to zero. */
1110 uerr_t
1111 ftp_size (int csock, const char *file, wgint *size)
1112 {
1113   char *request, *respline;
1114   int nwritten;
1115   uerr_t err;
1116
1117   /* Send PWD request.  */
1118   request = ftp_request ("SIZE", file);
1119   nwritten = fd_write (csock, request, strlen (request), -1);
1120   if (nwritten < 0)
1121     {
1122       xfree (request);
1123       *size = 0;
1124       return WRITEFAILED;
1125     }
1126   xfree (request);
1127   /* Get appropriate response.  */
1128   err = ftp_response (csock, &respline);
1129   if (err != FTPOK)
1130     {
1131       *size = 0;
1132       return err;
1133     }
1134   if (*respline == '5')
1135     {
1136       /* 
1137        * Probably means SIZE isn't supported on this server.
1138        * Error is nonfatal since SIZE isn't in RFC 959 
1139        */
1140       xfree (respline);
1141       *size = 0;
1142       return FTPOK;
1143     }
1144
1145   errno = 0;
1146   *size = str_to_wgint (respline + 4, NULL, 10);
1147   if (errno)
1148     {
1149       /* 
1150        * Couldn't parse the response for some reason.  On the (few)
1151        * tests I've done, the response is 213 <SIZE> with nothing else -
1152        * maybe something a bit more resilient is necessary.  It's not a
1153        * fatal error, however.
1154        */
1155       xfree (respline);
1156       *size = 0;
1157       return FTPOK;
1158     }
1159
1160   xfree (respline);
1161   /* All OK.  */
1162   return FTPOK;
1163 }
1164
1165 /* If URL's params are of the form "type=X", return character X.
1166    Otherwise, return 'I' (the default type).  */
1167 char
1168 ftp_process_type (const char *params)
1169 {
1170   if (params
1171       && 0 == strncasecmp (params, "type=", 5)
1172       && params[5] != '\0')
1173     return c_toupper (params[5]);
1174   else
1175     return 'I';
1176 }