]> sjero.net Git - wget/blob - src/ftp-basic.c
b2d21b1a1f086977d8d7c8e124c88f1d9b2d7139
[wget] / src / ftp-basic.c
1 /* Basic FTP routines.
2    Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3    2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
4
5 This file is part of GNU Wget.
6
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10  (at your option) any later version.
11
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Wget.  If not, see <http://www.gnu.org/licenses/>.
19
20 Additional permission under GNU GPL version 3 section 7
21
22 If you modify this program, or any covered work, by linking or
23 combining it with the OpenSSL project's OpenSSL library (or a
24 modified version of that library), containing parts covered by the
25 terms of the OpenSSL or SSLeay licenses, the Free Software Foundation
26 grants you additional permission to convey the resulting work.
27 Corresponding Source for a non-source form of such a combination
28 shall include the source code for the parts of OpenSSL used as well
29 as that of the covered work.  */
30
31 #include "wget.h"
32
33 #include <assert.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <errno.h>
37
38 #include <string.h>
39 #include <unistd.h>
40 #include "utils.h"
41 #include "connect.h"
42 #include "host.h"
43 #include "ftp.h"
44 #include "retr.h"
45
46 char ftp_last_respline[128];
47
48 \f
49 /* Get the response of FTP server and allocate enough room to handle
50    it.  <CR> and <LF> characters are stripped from the line, and the
51    line is 0-terminated.  All the response lines but the last one are
52    skipped.  The last line is determined as described in RFC959.
53
54    If the line is successfully read, FTPOK is returned, and *ret_line
55    is assigned a freshly allocated line.  Otherwise, FTPRERR is
56    returned, and the value of *ret_line should be ignored.  */
57
58 uerr_t
59 ftp_response (int fd, char **ret_line)
60 {
61   while (1)
62     {
63       char *p;
64       char *line = fd_read_line (fd);
65       if (!line)
66         return FTPRERR;
67
68       /* Strip trailing CRLF before printing the line, so that
69          quotting doesn't include bogus \012 and \015. */
70       p = strchr (line, '\0');
71       if (p > line && p[-1] == '\n')
72         *--p = '\0';
73       if (p > line && p[-1] == '\r')
74         *--p = '\0';
75
76       if (opt.server_response)
77         logprintf (LOG_NOTQUIET, "%s\n",
78                    quotearg_style (escape_quoting_style, line));
79       else
80         DEBUGP (("%s\n", quotearg_style (escape_quoting_style, line)));
81
82       /* The last line of output is the one that begins with "ddd ". */
83       if (c_isdigit (line[0]) && c_isdigit (line[1]) && c_isdigit (line[2])
84           && line[3] == ' ')
85         {
86           strncpy (ftp_last_respline, line, sizeof (ftp_last_respline));
87           ftp_last_respline[sizeof (ftp_last_respline) - 1] = '\0';
88           *ret_line = line;
89           return FTPOK;
90         }
91       xfree (line);
92     }
93 }
94
95 /* Returns the malloc-ed FTP request, ending with <CR><LF>, printing
96    it if printing is required.  If VALUE is NULL, just use
97    command<CR><LF>.  */
98 static char *
99 ftp_request (const char *command, const char *value)
100 {
101   char *res;
102   if (value)
103     {
104       /* Check for newlines in VALUE (possibly injected by the %0A URL
105          escape) making the callers inadvertently send multiple FTP
106          commands at once.  Without this check an attacker could
107          intentionally redirect to ftp://server/fakedir%0Acommand.../
108          and execute arbitrary FTP command on a remote FTP server.  */
109       if (strpbrk (value, "\r\n"))
110         {
111           /* Copy VALUE to the stack and modify CR/LF to space. */
112           char *defanged, *p;
113           STRDUP_ALLOCA (defanged, value);
114           for (p = defanged; *p; p++)
115             if (*p == '\r' || *p == '\n')
116               *p = ' ';
117           DEBUGP (("\nDetected newlines in %s \"%s\"; changing to %s \"%s\"\n",
118                    command, quotearg_style (escape_quoting_style, value),
119                    command, quotearg_style (escape_quoting_style, 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     size_t 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   /* Skip the useless stuff and get what's inside the parentheses */
758   start = strchr (respline, '(');
759   if (start == NULL)
760     {
761       xfree (respline);
762       return FTPINVPASV;
763     }
764
765   /* Skip the first two void fields */
766   s = start + 1;
767   delim = *s++;
768   if (delim < 33 || delim > 126)
769     {
770       xfree (respline);
771       return FTPINVPASV;
772     }
773
774   for (i = 0; i < 2; i++)
775     {
776       if (*s++ != delim)
777         {
778           xfree (respline);
779         return FTPINVPASV;
780         }
781     }
782
783   /* Finally, get the port number */
784   tport = 0;
785   for (i = 1; c_isdigit (*s); s++)
786     {
787       if (i > 5)
788         {
789           xfree (respline);
790           return FTPINVPASV;
791         }
792       tport = (*s - '0') + 10 * tport;
793     }
794
795   /* Make sure that the response terminates correcty */
796   if (*s++ != delim)
797     {
798       xfree (respline);
799       return FTPINVPASV;
800     }
801
802   if (*s != ')')
803     {
804       xfree (respline);
805       return FTPINVPASV;
806     }
807
808   *port = tport;
809
810   xfree (respline);
811   return FTPOK;
812 }
813 #endif
814
815 /* Sends the TYPE request to the server.  */
816 uerr_t
817 ftp_type (int csock, int type)
818 {
819   char *request, *respline;
820   int nwritten;
821   uerr_t err;
822   char stype[2];
823
824   /* Construct argument.  */
825   stype[0] = type;
826   stype[1] = 0;
827   /* Send TYPE request.  */
828   request = ftp_request ("TYPE", stype);
829   nwritten = fd_write (csock, request, strlen (request), -1);
830   if (nwritten < 0)
831     {
832       xfree (request);
833       return WRITEFAILED;
834     }
835   xfree (request);
836   /* Get appropriate response.  */
837   err = ftp_response (csock, &respline);
838   if (err != FTPOK)
839     return err;
840   if (*respline != '2')
841     {
842       xfree (respline);
843       return FTPUNKNOWNTYPE;
844     }
845   xfree (respline);
846   /* All OK.  */
847   return FTPOK;
848 }
849
850 /* Changes the working directory by issuing a CWD command to the
851    server.  */
852 uerr_t
853 ftp_cwd (int csock, const char *dir)
854 {
855   char *request, *respline;
856   int nwritten;
857   uerr_t err;
858
859   /* Send CWD request.  */
860   request = ftp_request ("CWD", dir);
861   nwritten = fd_write (csock, request, strlen (request), -1);
862   if (nwritten < 0)
863     {
864       xfree (request);
865       return WRITEFAILED;
866     }
867   xfree (request);
868   /* Get appropriate response.  */
869   err = ftp_response (csock, &respline);
870   if (err != FTPOK)
871     return err;
872   if (*respline == '5')
873     {
874       xfree (respline);
875       return FTPNSFOD;
876     }
877   if (*respline != '2')
878     {
879       xfree (respline);
880       return FTPRERR;
881     }
882   xfree (respline);
883   /* All OK.  */
884   return FTPOK;
885 }
886
887 /* Sends REST command to the FTP server.  */
888 uerr_t
889 ftp_rest (int csock, wgint offset)
890 {
891   char *request, *respline;
892   int nwritten;
893   uerr_t err;
894
895   request = ftp_request ("REST", number_to_static_string (offset));
896   nwritten = fd_write (csock, request, strlen (request), -1);
897   if (nwritten < 0)
898     {
899       xfree (request);
900       return WRITEFAILED;
901     }
902   xfree (request);
903   /* Get appropriate response.  */
904   err = ftp_response (csock, &respline);
905   if (err != FTPOK)
906     return err;
907   if (*respline != '3')
908     {
909       xfree (respline);
910       return FTPRESTFAIL;
911     }
912   xfree (respline);
913   /* All OK.  */
914   return FTPOK;
915 }
916
917 /* Sends RETR command to the FTP server.  */
918 uerr_t
919 ftp_retr (int csock, const char *file)
920 {
921   char *request, *respline;
922   int nwritten;
923   uerr_t err;
924
925   /* Send RETR request.  */
926   request = ftp_request ("RETR", file);
927   nwritten = fd_write (csock, request, strlen (request), -1);
928   if (nwritten < 0)
929     {
930       xfree (request);
931       return WRITEFAILED;
932     }
933   xfree (request);
934   /* Get appropriate response.  */
935   err = ftp_response (csock, &respline);
936   if (err != FTPOK)
937     return err;
938   if (*respline == '5')
939     {
940       xfree (respline);
941       return FTPNSFOD;
942     }
943   if (*respline != '1')
944     {
945       xfree (respline);
946       return FTPRERR;
947     }
948   xfree (respline);
949   /* All OK.  */
950   return FTPOK;
951 }
952
953 /* Sends the LIST command to the server.  If FILE is NULL, send just
954    `LIST' (no space).  */
955 uerr_t
956 ftp_list (int csock, const char *file, enum stype rs)
957 {
958   char *request, *respline;
959   int nwritten;
960   uerr_t err;
961   bool ok = false;
962   size_t i = 0;
963   /* Try `LIST -a' first and revert to `LIST' in case of failure.  */
964   const char *list_commands[] = { "LIST -a",
965                                   "LIST" };
966
967   /* 2008-01-29  SMS.  For a VMS FTP server, where "LIST -a" may not
968      fail, but will never do what is desired here, skip directly to the
969      simple "LIST" command (assumed to be the last one in the list).
970   */
971   if (rs == ST_VMS)
972     i = countof (list_commands)- 1;
973
974   do {
975     /* Send request.  */
976     request = ftp_request (list_commands[i], file);
977     nwritten = fd_write (csock, request, strlen (request), -1);
978     if (nwritten < 0)
979       {
980         xfree (request);
981         return WRITEFAILED;
982       }
983     xfree (request);
984     /* Get appropriate response.  */
985     err = ftp_response (csock, &respline);
986     if (err == FTPOK)
987       {
988         if (*respline == '5')
989           {
990             err = FTPNSFOD;
991           }
992         else if (*respline == '1')
993           {
994             err = FTPOK;
995             ok = true;
996           }
997         else
998           {
999             err = FTPRERR;
1000           }
1001         xfree (respline);
1002       }
1003     ++i;
1004   } while (i < countof (list_commands) && !ok);
1005
1006   return err;
1007 }
1008
1009 /* Sends the SYST command to the server. */
1010 uerr_t
1011 ftp_syst (int csock, enum stype *server_type)
1012 {
1013   char *request, *respline;
1014   int nwritten;
1015   uerr_t err;
1016
1017   /* Send SYST request.  */
1018   request = ftp_request ("SYST", NULL);
1019   nwritten = fd_write (csock, request, strlen (request), -1);
1020   if (nwritten < 0)
1021     {
1022       xfree (request);
1023       return WRITEFAILED;
1024     }
1025   xfree (request);
1026
1027   /* Get appropriate response.  */
1028   err = ftp_response (csock, &respline);
1029   if (err != FTPOK)
1030     return err;
1031   if (*respline == '5')
1032     {
1033       xfree (respline);
1034       return FTPSRVERR;
1035     }
1036
1037   /* Skip the number (215, but 200 (!!!) in case of VMS) */
1038   strtok (respline, " ");
1039
1040   /* Which system type has been reported (we are interested just in the
1041      first word of the server response)?  */
1042   request = strtok (NULL, " ");
1043
1044   if (request == NULL)
1045     *server_type = ST_OTHER;
1046   else if (!strcasecmp (request, "VMS"))
1047     *server_type = ST_VMS;
1048   else if (!strcasecmp (request, "UNIX"))
1049     *server_type = ST_UNIX;
1050   else if (!strcasecmp (request, "WINDOWS_NT")
1051            || !strcasecmp (request, "WINDOWS2000"))
1052     *server_type = ST_WINNT;
1053   else if (!strcasecmp (request, "MACOS"))
1054     *server_type = ST_MACOS;
1055   else if (!strcasecmp (request, "OS/400"))
1056     *server_type = ST_OS400;
1057   else
1058     *server_type = ST_OTHER;
1059
1060   xfree (respline);
1061   /* All OK.  */
1062   return FTPOK;
1063 }
1064
1065 /* Sends the PWD command to the server. */
1066 uerr_t
1067 ftp_pwd (int csock, char **pwd)
1068 {
1069   char *request, *respline;
1070   int nwritten;
1071   uerr_t err;
1072
1073   /* Send PWD request.  */
1074   request = ftp_request ("PWD", NULL);
1075   nwritten = fd_write (csock, request, strlen (request), -1);
1076   if (nwritten < 0)
1077     {
1078       xfree (request);
1079       return WRITEFAILED;
1080     }
1081   xfree (request);
1082   /* Get appropriate response.  */
1083   err = ftp_response (csock, &respline);
1084   if (err != FTPOK)
1085     return err;
1086   if (*respline == '5')
1087     {
1088     err:
1089       xfree (respline);
1090       return FTPSRVERR;
1091     }
1092
1093   /* Skip the number (257), leading citation mark, trailing citation mark
1094      and everything following it. */
1095   strtok (respline, "\"");
1096   request = strtok (NULL, "\"");
1097   if (!request)
1098     /* Treat the malformed response as an error, which the caller has
1099        to handle gracefully anyway.  */
1100     goto err;
1101
1102   /* Has the `pwd' been already allocated?  Free! */
1103   xfree_null (*pwd);
1104
1105   *pwd = xstrdup (request);
1106
1107   xfree (respline);
1108   /* All OK.  */
1109   return FTPOK;
1110 }
1111
1112 /* Sends the SIZE command to the server, and returns the value in 'size'.
1113  * If an error occurs, size is set to zero. */
1114 uerr_t
1115 ftp_size (int csock, const char *file, wgint *size)
1116 {
1117   char *request, *respline;
1118   int nwritten;
1119   uerr_t err;
1120
1121   /* Send PWD request.  */
1122   request = ftp_request ("SIZE", file);
1123   nwritten = fd_write (csock, request, strlen (request), -1);
1124   if (nwritten < 0)
1125     {
1126       xfree (request);
1127       *size = 0;
1128       return WRITEFAILED;
1129     }
1130   xfree (request);
1131   /* Get appropriate response.  */
1132   err = ftp_response (csock, &respline);
1133   if (err != FTPOK)
1134     {
1135       *size = 0;
1136       return err;
1137     }
1138   if (*respline == '5')
1139     {
1140       /*
1141        * Probably means SIZE isn't supported on this server.
1142        * Error is nonfatal since SIZE isn't in RFC 959
1143        */
1144       xfree (respline);
1145       *size = 0;
1146       return FTPOK;
1147     }
1148
1149   errno = 0;
1150   *size = str_to_wgint (respline + 4, NULL, 10);
1151   if (errno)
1152     {
1153       /*
1154        * Couldn't parse the response for some reason.  On the (few)
1155        * tests I've done, the response is 213 <SIZE> with nothing else -
1156        * maybe something a bit more resilient is necessary.  It's not a
1157        * fatal error, however.
1158        */
1159       xfree (respline);
1160       *size = 0;
1161       return FTPOK;
1162     }
1163
1164   xfree (respline);
1165   /* All OK.  */
1166   return FTPOK;
1167 }
1168
1169 /* If URL's params are of the form "type=X", return character X.
1170    Otherwise, return 'I' (the default type).  */
1171 char
1172 ftp_process_type (const char *params)
1173 {
1174   if (params
1175       && 0 == strncasecmp (params, "type=", 5)
1176       && params[5] != '\0')
1177     return c_toupper (params[5]);
1178   else
1179     return 'I';
1180 }