]> sjero.net Git - wget/blob - src/ftp.c
aa283cf8fbbc554799f39185b164a54c38b6d327
[wget] / src / ftp.c
1 /* File Transfer Protocol support.
2    Copyright (C) 1995, 1996, 1997, 1998, 2000 Free Software Foundation, Inc.
3
4 This file is part of Wget.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
19
20 #include <config.h>
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #ifdef HAVE_STRING_H
25 # include <string.h>
26 #else
27 # include <strings.h>
28 #endif
29 #include <ctype.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <sys/types.h>
34 #include <assert.h>
35 #include <errno.h>
36
37 #include "wget.h"
38 #include "utils.h"
39 #include "url.h"
40 #include "rbuf.h"
41 #include "retr.h"
42 #include "ftp.h"
43 #include "connect.h"
44 #include "host.h"
45 #include "fnmatch.h"
46 #include "netrc.h"
47
48 #ifndef errno
49 extern int errno;
50 #endif
51 #ifndef h_errno
52 extern int h_errno;
53 #endif
54
55 /* File where the "ls -al" listing will be saved.  */
56 #define LIST_FILENAME ".listing"
57
58 extern char ftp_last_respline[];
59
60 /* Look for regexp "( *[0-9]+ *byte" (literal parenthesis) anywhere in
61    the string S, and return the number converted to long, if found, 0
62    otherwise.  */
63 static long
64 ftp_expected_bytes (const char *s)
65 {
66   long res;
67
68   while (1)
69     {
70       while (*s && *s != '(')
71         ++s;
72       if (!*s)
73         return 0;
74       for (++s; *s && ISSPACE (*s); s++);
75       if (!*s)
76         return 0;
77       if (!ISDIGIT (*s))
78         continue;
79       res = 0;
80       do
81         {
82           res = (*s - '0') + 10 * res;
83           ++s;
84         }
85       while (*s && ISDIGIT (*s));
86       if (!*s)
87         return 0;
88       while (*s && ISSPACE (*s))
89         ++s;
90       if (!*s)
91         return 0;
92       if (TOLOWER (*s) != 'b')
93         continue;
94       if (strncasecmp (s, "byte", 4))
95         continue;
96       else
97         break;
98     }
99   return res;
100 }
101
102 /* Retrieves a file with denoted parameters through opening an FTP
103    connection to the server.  It always closes the data connection,
104    and closes the control connection in case of error.  */
105 static uerr_t
106 getftp (const struct urlinfo *u, long *len, long restval, ccon *con)
107 {
108   int csock, dtsock, res;
109   uerr_t err;
110   FILE *fp;
111   char *user, *passwd, *respline;
112   char *tms, *tmrate;
113   unsigned char pasv_addr[6];
114   int cmd = con->cmd;
115   int passive_mode_open = 0;
116   long expected_bytes = 0L;
117
118   assert (con != NULL);
119   assert (u->local != NULL);
120   /* Debug-check of the sanity of the request by making sure that LIST
121      and RETR are never both requested (since we can handle only one
122      at a time.  */
123   assert (!((cmd & DO_LIST) && (cmd & DO_RETR)));
124   /* Make sure that at least *something* is requested.  */
125   assert ((cmd & (DO_LIST | DO_CWD | DO_RETR | DO_LOGIN)) != 0);
126
127   user = u->user;
128   passwd = u->passwd;
129   search_netrc (u->host, (const char **)&user, (const char **)&passwd, 1);
130   user = user ? user : opt.ftp_acc;
131   if (!opt.ftp_pass)
132     opt.ftp_pass = xstrdup (ftp_getaddress ());
133   passwd = passwd ? passwd : opt.ftp_pass;
134   assert (user && passwd);
135
136   dtsock = -1;
137   con->dltime = 0;
138
139   if (!(cmd & DO_LOGIN))
140     csock = RBUF_FD (&con->rbuf);
141   else                          /* cmd & DO_LOGIN */
142     {
143       /* Login to the server: */
144
145       /* First: Establish the control connection.  */
146       logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
147       err = make_connection (&csock, u->host, u->port);
148       if (cmd & LEAVE_PENDING)
149         rbuf_initialize (&con->rbuf, csock);
150       else
151         rbuf_uninitialize (&con->rbuf);
152       switch (err)
153         {
154           /* Do not close the socket in first several cases, since it
155              wasn't created at all.  */
156         case HOSTERR:
157           logputs (LOG_VERBOSE, "\n");
158           logprintf (LOG_NOTQUIET, "%s: %s\n", u->host, herrmsg (h_errno));
159           return HOSTERR;
160           break;
161         case CONSOCKERR:
162           logputs (LOG_VERBOSE, "\n");
163           logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
164           return CONSOCKERR;
165           break;
166         case CONREFUSED:
167           logputs (LOG_VERBOSE, "\n");
168           logprintf (LOG_NOTQUIET, _("Connection to %s:%hu refused.\n"),
169                      u->host, u->port);
170           CLOSE (csock);
171           rbuf_uninitialize (&con->rbuf);
172           return CONREFUSED;
173         case CONERROR:
174           logputs (LOG_VERBOSE, "\n");
175           logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
176           CLOSE (csock);
177           rbuf_uninitialize (&con->rbuf);
178           return CONERROR;
179           break;
180         default:
181           DO_NOTHING;
182           /* #### Hmm?  */
183         }
184       /* Since this is a new connection, we may safely discard
185          anything left in the buffer.  */
186       rbuf_discard (&con->rbuf);
187
188       /* Second: Login with proper USER/PASS sequence.  */
189       logputs (LOG_VERBOSE, _("connected!\n"));
190       logprintf (LOG_VERBOSE, _("Logging in as %s ... "), user);
191       if (opt.server_response)
192         logputs (LOG_ALWAYS, "\n");
193       err = ftp_login (&con->rbuf, user, passwd);
194       /* FTPRERR, FTPSRVERR, WRITEFAILED, FTPLOGREFUSED, FTPLOGINC */
195       switch (err)
196         {
197         case FTPRERR:
198           logputs (LOG_VERBOSE, "\n");
199           logputs (LOG_NOTQUIET, _("\
200 Error in server response, closing control connection.\n"));
201           CLOSE (csock);
202           rbuf_uninitialize (&con->rbuf);
203           return err;
204           break;
205         case FTPSRVERR:
206           logputs (LOG_VERBOSE, "\n");
207           logputs (LOG_NOTQUIET, _("Error in server greeting.\n"));
208           CLOSE (csock);
209           rbuf_uninitialize (&con->rbuf);
210           return err;
211           break;
212         case WRITEFAILED:
213           logputs (LOG_VERBOSE, "\n");
214           logputs (LOG_NOTQUIET,
215                    _("Write failed, closing control connection.\n"));
216           CLOSE (csock);
217           rbuf_uninitialize (&con->rbuf);
218           return err;
219           break;
220         case FTPLOGREFUSED:
221           logputs (LOG_VERBOSE, "\n");
222           logputs (LOG_NOTQUIET, _("The server refuses login.\n"));
223           CLOSE (csock);
224           rbuf_uninitialize (&con->rbuf);
225           return FTPLOGREFUSED;
226           break;
227         case FTPLOGINC:
228           logputs (LOG_VERBOSE, "\n");
229           logputs (LOG_NOTQUIET, _("Login incorrect.\n"));
230           CLOSE (csock);
231           rbuf_uninitialize (&con->rbuf);
232           return FTPLOGINC;
233           break;
234         case FTPOK:
235           if (!opt.server_response)
236             logputs (LOG_VERBOSE, _("Logged in!\n"));
237           break;
238         default:
239           abort ();
240           exit (1);
241           break;
242         }
243       /* Third: Set type to Image (binary).  */
244       if (!opt.server_response)
245         logprintf (LOG_VERBOSE, "==> TYPE %c ... ", TOUPPER (u->ftp_type));
246       err = ftp_type (&con->rbuf, TOUPPER (u->ftp_type));
247       /* FTPRERR, WRITEFAILED, FTPUNKNOWNTYPE */
248       switch (err)
249         {
250         case FTPRERR:
251           logputs (LOG_VERBOSE, "\n");
252           logputs (LOG_NOTQUIET, _("\
253 Error in server response, closing control connection.\n"));
254           CLOSE (csock);
255           rbuf_uninitialize (&con->rbuf);
256           return err;
257           break;
258         case WRITEFAILED:
259           logputs (LOG_VERBOSE, "\n");
260           logputs (LOG_NOTQUIET,
261                    _("Write failed, closing control connection.\n"));
262           CLOSE (csock);
263           rbuf_uninitialize (&con->rbuf);
264           return err;
265           break;
266         case FTPUNKNOWNTYPE:
267           logputs (LOG_VERBOSE, "\n");
268           logprintf (LOG_NOTQUIET,
269                      _("Unknown type `%c', closing control connection.\n"),
270                      TOUPPER (u->ftp_type));
271           CLOSE (csock);
272           rbuf_uninitialize (&con->rbuf);
273           return err;
274         case FTPOK:
275           /* Everything is OK.  */
276           break;
277         default:
278           abort ();
279           break;
280         }
281       if (!opt.server_response)
282         logputs (LOG_VERBOSE, _("done.  "));
283     } /* do login */
284
285   if (cmd & DO_CWD)
286     {
287       if (!*u->dir)
288         logputs (LOG_VERBOSE, _("==> CWD not needed.\n"));
289       else
290         {
291           /* Change working directory.  */
292           if (!opt.server_response)
293             logprintf (LOG_VERBOSE, "==> CWD %s ... ", u->dir);
294           err = ftp_cwd (&con->rbuf, u->dir);
295           /* FTPRERR, WRITEFAILED, FTPNSFOD */
296           switch (err)
297             {
298             case FTPRERR:
299               logputs (LOG_VERBOSE, "\n");
300               logputs (LOG_NOTQUIET, _("\
301 Error in server response, closing control connection.\n"));
302               CLOSE (csock);
303               rbuf_uninitialize (&con->rbuf);
304               return err;
305               break;
306             case WRITEFAILED:
307               logputs (LOG_VERBOSE, "\n");
308               logputs (LOG_NOTQUIET,
309                        _("Write failed, closing control connection.\n"));
310               CLOSE (csock);
311               rbuf_uninitialize (&con->rbuf);
312               return err;
313               break;
314             case FTPNSFOD:
315               logputs (LOG_VERBOSE, "\n");
316               logprintf (LOG_NOTQUIET, _("No such directory `%s'.\n\n"),
317                          u->dir);
318               CLOSE (csock);
319               rbuf_uninitialize (&con->rbuf);
320               return err;
321               break;
322             case FTPOK:
323               /* fine and dandy */
324               break;
325             default:
326               abort ();
327               break;
328             }
329           if (!opt.server_response)
330             logputs (LOG_VERBOSE, _("done.\n"));
331         }
332     }
333   else /* do not CWD */
334     logputs (LOG_VERBOSE, _("==> CWD not required.\n"));
335
336   /* If anything is to be retrieved, PORT (or PASV) must be sent.  */
337   if (cmd & (DO_LIST | DO_RETR))
338     {
339       if (opt.ftp_pasv > 0)
340         {
341           char thost[256];
342           unsigned short tport;
343
344           if (!opt.server_response)
345             logputs (LOG_VERBOSE, "==> PASV ... ");
346           err = ftp_pasv (&con->rbuf, pasv_addr);
347           /* FTPRERR, WRITEFAILED, FTPNOPASV, FTPINVPASV */
348           switch (err)
349             {
350             case FTPRERR:
351               logputs (LOG_VERBOSE, "\n");
352               logputs (LOG_NOTQUIET, _("\
353 Error in server response, closing control connection.\n"));
354               CLOSE (csock);
355               rbuf_uninitialize (&con->rbuf);
356               return err;
357               break;
358             case WRITEFAILED:
359               logputs (LOG_VERBOSE, "\n");
360               logputs (LOG_NOTQUIET,
361                        _("Write failed, closing control connection.\n"));
362               CLOSE (csock);
363               rbuf_uninitialize (&con->rbuf);
364               return err;
365               break;
366             case FTPNOPASV:
367               logputs (LOG_VERBOSE, "\n");
368               logputs (LOG_NOTQUIET, _("Cannot initiate PASV transfer.\n"));
369               break;
370             case FTPINVPASV:
371               logputs (LOG_VERBOSE, "\n");
372               logputs (LOG_NOTQUIET, _("Cannot parse PASV response.\n"));
373               break;
374             case FTPOK:
375               /* fine and dandy */
376               break;
377             default:
378               abort ();
379               break;
380             }
381           if (err==FTPOK)
382             {
383               sprintf (thost, "%d.%d.%d.%d",
384                        pasv_addr[0], pasv_addr[1], pasv_addr[2], pasv_addr[3]);
385               tport = (pasv_addr[4] << 8) + pasv_addr[5];
386               DEBUGP ((_("Will try connecting to %s:%hu.\n"), thost, tport));
387               err = make_connection (&dtsock, thost, tport);
388               switch (err)
389                 {
390                   /* Do not close the socket in first several cases,
391                      since it wasn't created at all.  */
392                 case HOSTERR:
393                   logputs (LOG_VERBOSE, "\n");
394                   logprintf (LOG_NOTQUIET, "%s: %s\n", thost,
395                              herrmsg (h_errno));
396                   CLOSE (csock);
397                   rbuf_uninitialize (&con->rbuf);
398                   return HOSTERR;
399                   break;
400                 case CONSOCKERR:
401                   logputs (LOG_VERBOSE, "\n");
402                   logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
403                   CLOSE (csock);
404                   rbuf_uninitialize (&con->rbuf);
405                   return CONSOCKERR;
406                   break;
407                 case CONREFUSED:
408                   logputs (LOG_VERBOSE, "\n");
409                   logprintf (LOG_NOTQUIET,
410                              _("Connection to %s:%hu refused.\n"),
411                              thost, tport);
412                   CLOSE (csock);
413                   rbuf_uninitialize (&con->rbuf);
414                   closeport (dtsock);
415                   return CONREFUSED;
416                 case CONERROR:
417                   logputs (LOG_VERBOSE, "\n");
418                   logprintf (LOG_NOTQUIET, "connect: %s\n",
419                              strerror (errno));
420                   CLOSE (csock);
421                   rbuf_uninitialize (&con->rbuf);
422                   closeport (dtsock);
423                   return CONERROR;
424                   break;
425                 default:
426                   /* #### What?!  */
427                   DO_NOTHING;
428                 }
429               passive_mode_open= 1;  /* Flag to avoid accept port */
430               if (!opt.server_response)
431                 logputs (LOG_VERBOSE, _("done.    "));
432             } /* err==FTP_OK */
433         }
434
435       if (!passive_mode_open)   /* Try to use a port command if PASV failed */
436         {
437           if (!opt.server_response)
438             logputs (LOG_VERBOSE, "==> PORT ... ");
439           err = ftp_port (&con->rbuf);
440           /* FTPRERR, WRITEFAILED, bindport (CONSOCKERR, CONPORTERR, BINDERR,
441              LISTENERR), HOSTERR, FTPPORTERR */
442           switch (err)
443             {
444             case FTPRERR:
445               logputs (LOG_VERBOSE, "\n");
446               logputs (LOG_NOTQUIET, _("\
447 Error in server response, closing control connection.\n"));
448               CLOSE (csock);
449               closeport (dtsock);
450               rbuf_uninitialize (&con->rbuf);
451               return err;
452               break;
453             case WRITEFAILED:
454               logputs (LOG_VERBOSE, "\n");
455               logputs (LOG_NOTQUIET,
456                        _("Write failed, closing control connection.\n"));
457               CLOSE (csock);
458               closeport (dtsock);
459               rbuf_uninitialize (&con->rbuf);
460               return err;
461               break;
462             case CONSOCKERR:
463               logputs (LOG_VERBOSE, "\n");
464               logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
465               CLOSE (csock);
466               closeport (dtsock);
467               rbuf_uninitialize (&con->rbuf);
468               return err;
469               break;
470             case CONPORTERR: case BINDERR: case LISTENERR:
471               /* What now?  These problems are local...  */
472               logputs (LOG_VERBOSE, "\n");
473               logprintf (LOG_NOTQUIET, _("Bind error (%s).\n"),
474                          strerror (errno));
475               closeport (dtsock);
476               return err;
477               break;
478             case HOSTERR:
479               logputs (LOG_VERBOSE, "\n");
480               logprintf (LOG_NOTQUIET, "%s: %s\n", u->host,
481                          herrmsg (h_errno));
482               CLOSE (csock);
483               closeport (dtsock);
484               rbuf_uninitialize (&con->rbuf);
485               return HOSTERR;
486               break;
487             case FTPPORTERR:
488               logputs (LOG_VERBOSE, "\n");
489               logputs (LOG_NOTQUIET, _("Invalid PORT.\n"));
490               CLOSE (csock);
491               closeport (dtsock);
492               rbuf_uninitialize (&con->rbuf);
493               return err;
494               break;
495             case FTPOK:
496               /* fine and dandy */
497               break;
498             default:
499               abort ();
500               break;
501             } /* port switch */
502           if (!opt.server_response)
503             logputs (LOG_VERBOSE, _("done.    "));
504         } /* dtsock == -1 */
505     } /* cmd & (DO_LIST | DO_RETR) */
506
507   /* Restart if needed.  */
508   if (restval && (cmd & DO_RETR))
509     {
510       if (!opt.server_response)
511         logprintf (LOG_VERBOSE, "==> REST %ld ... ", restval);
512       err = ftp_rest (&con->rbuf, restval);
513
514       /* FTPRERR, WRITEFAILED, FTPRESTFAIL */
515       switch (err)
516         {
517         case FTPRERR:
518           logputs (LOG_VERBOSE, "\n");
519           logputs (LOG_NOTQUIET, _("\
520 Error in server response, closing control connection.\n"));
521           CLOSE (csock);
522           closeport (dtsock);
523           rbuf_uninitialize (&con->rbuf);
524           return err;
525           break;
526         case WRITEFAILED:
527           logputs (LOG_VERBOSE, "\n");
528           logputs (LOG_NOTQUIET,
529                    _("Write failed, closing control connection.\n"));
530           CLOSE (csock);
531           closeport (dtsock);
532           rbuf_uninitialize (&con->rbuf);
533           return err;
534           break;
535         case FTPRESTFAIL:
536           logputs (LOG_VERBOSE, _("\nREST failed, starting from scratch.\n"));
537           restval = 0L;
538           break;
539         case FTPOK:
540           /* fine and dandy */
541           break;
542         default:
543           abort ();
544           break;
545         }
546       if (err != FTPRESTFAIL && !opt.server_response)
547         logputs (LOG_VERBOSE, _("done.    "));
548     } /* restval && cmd & DO_RETR */
549
550   if (cmd & DO_RETR)
551     {
552       if (opt.verbose)
553         {
554           if (!opt.server_response)
555             {
556               if (restval)
557                 logputs (LOG_VERBOSE, "\n");
558               logprintf (LOG_VERBOSE, "==> RETR %s ... ", u->file);
559             }
560         }
561       err = ftp_retr (&con->rbuf, u->file);
562       /* FTPRERR, WRITEFAILED, FTPNSFOD */
563       switch (err)
564         {
565         case FTPRERR:
566           logputs (LOG_VERBOSE, "\n");
567           logputs (LOG_NOTQUIET, _("\
568 Error in server response, closing control connection.\n"));
569           CLOSE (csock);
570           closeport (dtsock);
571           rbuf_uninitialize (&con->rbuf);
572           return err;
573           break;
574         case WRITEFAILED:
575           logputs (LOG_VERBOSE, "\n");
576           logputs (LOG_NOTQUIET,
577                    _("Write failed, closing control connection.\n"));
578           CLOSE (csock);
579           closeport (dtsock);
580           rbuf_uninitialize (&con->rbuf);
581           return err;
582           break;
583         case FTPNSFOD:
584           logputs (LOG_VERBOSE, "\n");
585           logprintf (LOG_NOTQUIET, _("No such file `%s'.\n\n"), u->file);
586           closeport (dtsock);
587           return err;
588           break;
589         case FTPOK:
590           /* fine and dandy */
591           break;
592         default:
593           abort ();
594           break;
595         }
596
597       if (!opt.server_response)
598         logputs (LOG_VERBOSE, _("done.\n"));
599       expected_bytes = ftp_expected_bytes (ftp_last_respline);
600     } /* do retrieve */
601
602   if (cmd & DO_LIST)
603     {
604       if (!opt.server_response)
605         logputs (LOG_VERBOSE, "==> LIST ... ");
606       /* As Maciej W. Rozycki (macro@ds2.pg.gda.pl) says, `LIST'
607          without arguments is better than `LIST .'; confirmed by
608          RFC959.  */
609       err = ftp_list (&con->rbuf, NULL);
610       /* FTPRERR, WRITEFAILED */
611       switch (err)
612         {
613         case FTPRERR:
614           logputs (LOG_VERBOSE, "\n");
615           logputs (LOG_NOTQUIET, _("\
616 Error in server response, closing control connection.\n"));
617           CLOSE (csock);
618           closeport (dtsock);
619           rbuf_uninitialize (&con->rbuf);
620           return err;
621           break;
622         case WRITEFAILED:
623           logputs (LOG_VERBOSE, "\n");
624           logputs (LOG_NOTQUIET,
625                    _("Write failed, closing control connection.\n"));
626           CLOSE (csock);
627           closeport (dtsock);
628           rbuf_uninitialize (&con->rbuf);
629           return err;
630           break;
631         case FTPNSFOD:
632           logputs (LOG_VERBOSE, "\n");
633           logprintf (LOG_NOTQUIET, _("No such file or directory `%s'.\n\n"),
634                      ".");
635           closeport (dtsock);
636           return err;
637           break;
638         case FTPOK:
639           /* fine and dandy */
640           break;
641         default:
642           abort ();
643           break;
644         }
645       if (!opt.server_response)
646         logputs (LOG_VERBOSE, _("done.\n"));
647       expected_bytes = ftp_expected_bytes (ftp_last_respline);
648     } /* cmd & DO_LIST */
649
650   /* Some FTP servers return the total length of file after REST
651      command, others just return the remaining size. */
652   if (*len && restval && expected_bytes
653       && (expected_bytes == *len - restval))
654     {
655       DEBUGP (("Lying FTP server found, adjusting.\n"));
656       expected_bytes = *len;
657     }
658
659   /* If no transmission was required, then everything is OK.  */
660   if (!(cmd & (DO_LIST | DO_RETR)))
661     return RETRFINISHED;
662
663   if (!passive_mode_open)  /* we are not using pasive mode so we need
664                               to accept */
665     {
666       /* Open the data transmission socket by calling acceptport().  */
667       err = acceptport (&dtsock);
668       /* Possible errors: ACCEPTERR.  */
669       if (err == ACCEPTERR)
670         {
671           logprintf (LOG_NOTQUIET, "accept: %s\n", strerror (errno));
672           return err;
673         }
674     }
675
676   /* Open the file -- if opt.dfp is set, use it instead.  */
677   if (!opt.dfp || con->cmd & DO_LIST)
678     {
679       mkalldirs (u->local);
680       if (opt.backups)
681         rotate_backups (u->local);
682       /* #### Is this correct? */
683       chmod (u->local, 0600);
684
685       fp = fopen (u->local, restval ? "ab" : "wb");
686       if (!fp)
687         {
688           logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
689           CLOSE (csock);
690           rbuf_uninitialize (&con->rbuf);
691           closeport (dtsock);
692           return FOPENERR;
693         }
694     }
695   else
696     {
697       fp = opt.dfp;
698       if (!restval)
699         {
700           /* This will silently fail for streams that don't correspond
701              to regular files, but that's OK.  */
702           rewind (fp);
703           clearerr (fp);
704         }
705     }
706
707   if (*len)
708     {
709       logprintf (LOG_VERBOSE, _("Length: %s"), legible (*len));
710       if (restval)
711         logprintf (LOG_VERBOSE, _(" [%s to go]"), legible (*len - restval));
712       logputs (LOG_VERBOSE, "\n");
713     }
714   else if (expected_bytes)
715     {
716       logprintf (LOG_VERBOSE, _("Length: %s"), legible (expected_bytes));
717       if (restval)
718         logprintf (LOG_VERBOSE, _(" [%s to go]"),
719                    legible (expected_bytes - restval));
720       logputs (LOG_VERBOSE, _(" (unauthoritative)\n"));
721     }
722   reset_timer ();
723   /* Get the contents of the document.  */
724   res = get_contents (dtsock, fp, len, restval, expected_bytes, &con->rbuf, 0);
725   con->dltime = elapsed_time ();
726   tms = time_str (NULL);
727   tmrate = rate (*len - restval, con->dltime);
728   /* Close data connection socket.  */
729   closeport (dtsock);
730   /* Close the local file.  */
731   {
732     /* Close or flush the file.  We have to be careful to check for
733        error here.  Checking the result of fwrite() is not enough --
734        errors could go unnoticed!  */
735     int flush_res;
736     if (!opt.dfp || con->cmd & DO_LIST)
737       flush_res = fclose (fp);
738     else
739       flush_res = fflush (fp);
740     if (flush_res == EOF)
741       res = -2;
742   }
743   /* If get_contents couldn't write to fp, bail out.  */
744   if (res == -2)
745     {
746       logprintf (LOG_NOTQUIET, _("%s: %s, closing control connection.\n"),
747                  u->local, strerror (errno));
748       CLOSE (csock);
749       rbuf_uninitialize (&con->rbuf);
750       return FWRITEERR;
751     }
752   else if (res == -1)
753     {
754       logprintf (LOG_NOTQUIET, _("%s (%s) - Data connection: %s; "),
755                  tms, tmrate, strerror (errno));
756       if (opt.server_response)
757         logputs (LOG_ALWAYS, "\n");
758     }
759
760   /* Get the server to tell us if everything is retrieved.  */
761   err = ftp_response (&con->rbuf, &respline);
762   /* ...and empty the buffer.  */
763   rbuf_discard (&con->rbuf);
764   if (err != FTPOK)
765     {
766       free (respline);
767       /* The control connection is decidedly closed.  Print the time
768          only if it hasn't already been printed.  */
769       if (res != -1)
770         logprintf (LOG_NOTQUIET, "%s (%s) - ", tms, tmrate);
771       logputs (LOG_NOTQUIET, _("Control connection closed.\n"));
772       /* If there is an error on the control connection, close it, but
773          return FTPRETRINT, since there is a possibility that the
774          whole file was retrieved nevertheless (but that is for
775          ftp_loop_internal to decide).  */
776       CLOSE (csock);
777       rbuf_uninitialize (&con->rbuf);
778       return FTPRETRINT;
779     } /* err != FTPOK */
780   /* If retrieval failed for any reason, return FTPRETRINT, but do not
781      close socket, since the control connection is still alive.  If
782      there is something wrong with the control connection, it will
783      become apparent later.  */
784   if (*respline != '2')
785     {
786       free (respline);
787       if (res != -1)
788         logprintf (LOG_NOTQUIET, "%s (%s) - ", tms, tmrate);
789       logputs (LOG_NOTQUIET, _("Data transfer aborted.\n"));
790       return FTPRETRINT;
791     }
792   free (respline);
793
794   if (res == -1)
795     {
796       /* What now?  The data connection was erroneous, whereas the
797          response says everything is OK.  We shall play it safe.  */
798       return FTPRETRINT;
799     }
800
801   if (!(cmd & LEAVE_PENDING))
802     {
803       /* I should probably send 'QUIT' and check for a reply, but this
804          is faster.  #### Is it OK, though?  */
805       CLOSE (csock);
806       rbuf_uninitialize (&con->rbuf);
807     }
808   /* If it was a listing, and opt.server_response is true,
809      print it out.  */
810   if (opt.server_response && (con->cmd & DO_LIST))
811     {
812       mkalldirs (u->local);
813       fp = fopen (u->local, "r");
814       if (!fp)
815         logprintf (LOG_ALWAYS, "%s: %s\n", u->local, strerror (errno));
816       else
817         {
818           char *line;
819           /* The lines are being read with read_whole_line because of
820              no-buffering on opt.lfile.  */
821           while ((line = read_whole_line (fp)))
822             {
823               logprintf (LOG_ALWAYS, "%s\n", line);
824               free (line);
825             }
826           fclose (fp);
827         }
828     } /* con->cmd & DO_LIST && server_response */
829
830   return RETRFINISHED;
831 }
832
833 /* A one-file FTP loop.  This is the part where FTP retrieval is
834    retried, and retried, and retried, and...
835
836    This loop either gets commands from con, or (if ON_YOUR_OWN is
837    set), makes them up to retrieve the file given by the URL.  */
838 static uerr_t
839 ftp_loop_internal (struct urlinfo *u, struct fileinfo *f, ccon *con)
840 {
841   static int first_retrieval = 1;
842
843   int count, orig_lp;
844   long restval, len;
845   char *tms, *tmrate, *locf;
846   uerr_t err;
847   struct stat st;
848
849   if (!u->local)
850     u->local = url_filename (u);
851
852   if (opt.noclobber && file_exists_p (u->local))
853     {
854       logprintf (LOG_VERBOSE,
855                  _("File `%s' already there, not retrieving.\n"), u->local);
856       /* If the file is there, we suppose it's retrieved OK.  */
857       return RETROK;
858     }
859
860   /* Remove it if it's a link.  */
861   remove_link (u->local);
862   if (!opt.output_document)
863     locf = u->local;
864   else
865     locf = opt.output_document;
866
867   count = 0;
868
869   if (con->st & ON_YOUR_OWN)
870     con->st = ON_YOUR_OWN;
871
872   orig_lp = con->cmd & LEAVE_PENDING ? 1 : 0;
873
874   /* THE loop.  */
875   do
876     {
877       /* Increment the pass counter.  */
878       ++count;
879       /* Wait before the retrieval (unless this is the very first
880          retrieval).
881          Check if we are retrying or not, wait accordingly - HEH */
882       if (!first_retrieval && (opt.wait || (count && opt.waitretry)))
883         {
884           if (count)
885             {
886               if (count<opt.waitretry)
887                 sleep(count);
888               else
889                 sleep(opt.waitretry);
890             }
891           else
892             sleep (opt.wait);
893         }
894       if (first_retrieval)
895         first_retrieval = 0;
896       if (con->st & ON_YOUR_OWN)
897         {
898           con->cmd = 0;
899           con->cmd |= (DO_RETR | LEAVE_PENDING);
900           if (rbuf_initialized_p (&con->rbuf))
901             con->cmd &= ~ (DO_LOGIN | DO_CWD);
902           else
903             con->cmd |= (DO_LOGIN | DO_CWD);
904         }
905       else /* not on your own */
906         {
907           if (rbuf_initialized_p (&con->rbuf))
908             con->cmd &= ~DO_LOGIN;
909           else
910             con->cmd |= DO_LOGIN;
911           if (con->st & DONE_CWD)
912             con->cmd &= ~DO_CWD;
913           else
914             con->cmd |= DO_CWD;
915         }
916       /* Assume no restarting.  */
917       restval = 0L;
918       if ((count > 1 || opt.always_rest)
919           && !(con->cmd & DO_LIST)
920           && file_exists_p (u->local))
921         if (stat (u->local, &st) == 0)
922           restval = st.st_size;
923       /* Get the current time string.  */
924       tms = time_str (NULL);
925       /* Print fetch message, if opt.verbose.  */
926       if (opt.verbose)
927         {
928           char *hurl = str_url (u->proxy ? u->proxy : u, 1);
929           char tmp[15];
930           strcpy (tmp, "        ");
931           if (count > 1)
932             sprintf (tmp, _("(try:%2d)"), count);
933           logprintf (LOG_VERBOSE, "--%s--  %s\n  %s => `%s'\n",
934                      tms, hurl, tmp, locf);
935 #ifdef WINDOWS
936           ws_changetitle (hurl, 1);
937 #endif
938           free (hurl);
939         }
940       /* Send getftp the proper length, if fileinfo was provided.  */
941       if (f)
942         len = f->size;
943       else
944         len = 0;
945       err = getftp (u, &len, restval, con);
946       /* Time?  */
947       tms = time_str (NULL);
948       tmrate = rate (len - restval, con->dltime);
949
950       if (!rbuf_initialized_p (&con->rbuf))
951         con->st &= ~DONE_CWD;
952       else
953         con->st |= DONE_CWD;
954
955       switch (err)
956         {
957         case HOSTERR: case CONREFUSED: case FWRITEERR: case FOPENERR:
958         case FTPNSFOD: case FTPLOGINC: case FTPNOPASV:
959           /* Fatal errors, give up.  */
960           return err;
961           break;
962         case CONSOCKERR: case CONERROR: case FTPSRVERR: case FTPRERR:
963         case WRITEFAILED: case FTPUNKNOWNTYPE: case CONPORTERR:
964         case BINDERR: case LISTENERR: case ACCEPTERR:
965         case FTPPORTERR: case FTPLOGREFUSED: case FTPINVPASV:
966           printwhat (count, opt.ntry);
967           /* non-fatal errors */
968           continue;
969           break;
970         case FTPRETRINT:
971           /* If the control connection was closed, the retrieval
972              will be considered OK if f->size == len.  */
973           if (!f || len != f->size)
974             {
975               printwhat (count, opt.ntry);
976               continue;
977             }
978           break;
979         case RETRFINISHED:
980           /* Great!  */
981           break;
982         default:
983           /* Not as great.  */
984           abort ();
985         }
986
987       /* If we get out of the switch above without continue'ing, we've
988          successfully downloaded a file.  Remember this fact. */
989       downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
990
991       if (con->st & ON_YOUR_OWN)
992         {
993           CLOSE (RBUF_FD (&con->rbuf));
994           rbuf_uninitialize (&con->rbuf);
995         }
996       logprintf (LOG_VERBOSE, _("%s (%s) - `%s' saved [%ld]\n\n"),
997                  tms, tmrate, locf, len);
998       if (!opt.verbose && !opt.quiet)
999         {
1000           /* Need to hide the password from the URL.  The `if' is here
1001              so that we don't do the needless allocation every
1002              time. */
1003           char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1004           logprintf (LOG_NONVERBOSE, "%s URL: %s [%ld] -> \"%s\" [%d]\n",
1005                      tms, hurl, len, locf, count);
1006           free (hurl);
1007         }
1008
1009       if ((con->cmd & DO_LIST))
1010         /* This is a directory listing file. */
1011         {
1012           if (!opt.remove_listing)
1013             /* --dont-remove-listing was specified, so do count this towards the
1014                number of bytes and files downloaded. */
1015             {
1016               downloaded_increase (len);
1017               opt.numurls++;
1018             }
1019
1020           /* Deletion of listing files is not controlled by --delete-after, but
1021              by the more specific option --dont-remove-listing, and the code
1022              to do this deletion is in another function. */
1023         }
1024       else
1025         /* This is not a directory listing file. */
1026         {
1027           /* Unlike directory listing files, don't pretend normal files weren't
1028              downloaded if they're going to be deleted.  People seeding proxies,
1029              for instance, may want to know how many bytes and files they've
1030              downloaded through it. */
1031           downloaded_increase (len);
1032           opt.numurls++;
1033
1034           if (opt.delete_after)
1035             {
1036               DEBUGP (("Removing file due to --delete-after in"
1037                        " ftp_loop_internal():\n"));
1038               logprintf (LOG_VERBOSE, _("Removing %s.\n"), locf);
1039               if (unlink (locf))
1040                 logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
1041             }
1042         }
1043       
1044       /* Restore the original leave-pendingness.  */
1045       if (orig_lp)
1046         con->cmd |= LEAVE_PENDING;
1047       else
1048         con->cmd &= ~LEAVE_PENDING;
1049       return RETROK;
1050     } while (!opt.ntry || (count < opt.ntry));
1051
1052   if (rbuf_initialized_p (&con->rbuf) && (con->st & ON_YOUR_OWN))
1053     {
1054       CLOSE (RBUF_FD (&con->rbuf));
1055       rbuf_uninitialize (&con->rbuf);
1056     }
1057   return TRYLIMEXC;
1058 }
1059
1060 /* Return the directory listing in a reusable format.  The directory
1061    is specifed in u->dir.  */
1062 static struct fileinfo *
1063 ftp_get_listing (struct urlinfo *u, ccon *con)
1064 {
1065   struct fileinfo *f;
1066   uerr_t err;
1067   char *olocal = u->local;
1068   char *list_filename, *ofile;
1069
1070   con->st &= ~ON_YOUR_OWN;
1071   con->cmd |= (DO_LIST | LEAVE_PENDING);
1072   con->cmd &= ~DO_RETR;
1073   /* Get the listing filename.  */
1074   ofile = u->file;
1075   u->file = LIST_FILENAME;
1076   list_filename = url_filename (u);
1077   u->file = ofile;
1078   u->local = list_filename;
1079   DEBUGP ((_("Using `%s' as listing tmp file.\n"), list_filename));
1080   err = ftp_loop_internal (u, NULL, con);
1081   u->local = olocal;
1082   if (err == RETROK)
1083     f = ftp_parse_ls (list_filename);
1084   else
1085     f = NULL;
1086   if (opt.remove_listing)
1087     {
1088       if (unlink (list_filename))
1089         logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
1090       else
1091         logprintf (LOG_VERBOSE, _("Removed `%s'.\n"), list_filename);
1092     }
1093   free (list_filename);
1094   con->cmd &= ~DO_LIST;
1095   return f;
1096 }
1097
1098 static uerr_t ftp_retrieve_dirs PARAMS ((struct urlinfo *, struct fileinfo *,
1099                                          ccon *));
1100 static uerr_t ftp_retrieve_glob PARAMS ((struct urlinfo *, ccon *, int));
1101 static struct fileinfo *delelement PARAMS ((struct fileinfo *,
1102                                             struct fileinfo **));
1103 static void freefileinfo PARAMS ((struct fileinfo *f));
1104
1105 /* Retrieve a list of files given in struct fileinfo linked list.  If
1106    a file is a symbolic link, do not retrieve it, but rather try to
1107    set up a similar link on the local disk, if the symlinks are
1108    supported.
1109
1110    If opt.recursive is set, after all files have been retrieved,
1111    ftp_retrieve_dirs will be called to retrieve the directories.  */
1112 static uerr_t
1113 ftp_retrieve_list (struct urlinfo *u, struct fileinfo *f, ccon *con)
1114 {
1115   static int depth = 0;
1116   uerr_t err;
1117   char *olocal, *ofile;
1118   struct fileinfo *orig;
1119   long local_size;
1120   time_t tml;
1121   int dlthis;
1122
1123   /* Increase the depth.  */
1124   ++depth;
1125   if (opt.reclevel != INFINITE_RECURSION && depth > opt.reclevel)
1126     {
1127       DEBUGP ((_("Recursion depth %d exceeded max. depth %d.\n"),
1128                depth, opt.reclevel));
1129       --depth;
1130       return RECLEVELEXC;
1131     }
1132
1133   assert (f != NULL);
1134   orig = f;
1135
1136   con->st &= ~ON_YOUR_OWN;
1137   if (!(con->st & DONE_CWD))
1138     con->cmd |= DO_CWD;
1139   else
1140     con->cmd &= ~DO_CWD;
1141   con->cmd |= (DO_RETR | LEAVE_PENDING);
1142
1143   if (!rbuf_initialized_p (&con->rbuf))
1144     con->cmd |= DO_LOGIN;
1145   else
1146     con->cmd &= ~DO_LOGIN;
1147
1148   err = RETROK;                 /* in case it's not used */
1149
1150   while (f)
1151     {
1152       if (downloaded_exceeds_quota ())
1153         {
1154           --depth;
1155           return QUOTEXC;
1156         }
1157       olocal = u->local;
1158       ofile = u->file;
1159       u->file = f->name;
1160       u->local = url_filename (u);
1161       err = RETROK;
1162
1163       dlthis = 1;
1164       if (opt.timestamping && f->type == FT_PLAINFILE)
1165         {
1166           struct stat st;
1167           /* If conversion of HTML files retrieved via FTP is ever implemented,
1168              we'll need to stat() <file>.orig here when -K has been specified.
1169              I'm not implementing it now since files on an FTP server are much
1170              more likely than files on an HTTP server to legitimately have a
1171              .orig suffix. */
1172           if (!stat (u->local, &st))
1173             {
1174               /* Else, get it from the file.  */
1175               local_size = st.st_size;
1176               tml = st.st_mtime;
1177               if (local_size == f->size && tml >= f->tstamp)
1178                 {
1179                   logprintf (LOG_VERBOSE, _("\
1180 Server file no newer than local file `%s' -- not retrieving.\n\n"), u->local);
1181                   dlthis = 0;
1182                 }
1183               else if (local_size != f->size)
1184                 {
1185                   logprintf (LOG_VERBOSE, _("\
1186 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1187                 }
1188             }
1189         }       /* opt.timestamping && f->type == FT_PLAINFILE */
1190       switch (f->type)
1191         {
1192         case FT_SYMLINK:
1193           /* If opt.retr_symlinks is defined, we treat symlinks as
1194              if they were normal files.  There is currently no way
1195              to distinguish whether they might be directories, and
1196              follow them.  */
1197           if (!opt.retr_symlinks)
1198             {
1199 #ifdef HAVE_SYMLINK
1200               if (!f->linkto)
1201                 logputs (LOG_NOTQUIET,
1202                          _("Invalid name of the symlink, skipping.\n"));
1203               else
1204                 {
1205                   struct stat st;
1206                   /* Check whether we already have the correct
1207                      symbolic link.  */
1208                   int rc = lstat (u->local, &st);
1209                   if (rc == 0)
1210                     {
1211                       size_t len = strlen (f->linkto) + 1;
1212                       if (S_ISLNK (st.st_mode))
1213                         {
1214                           char *link_target = (char *)alloca (len);
1215                           size_t n = readlink (u->local, link_target, len);
1216                           if ((n == len - 1)
1217                               && (memcmp (link_target, f->linkto, n) == 0))
1218                             {
1219                               logprintf (LOG_VERBOSE, _("\
1220 Already have correct symlink %s -> %s\n\n"),
1221                                          u->local, f->linkto);
1222                               dlthis = 0;
1223                               break;
1224                             }
1225                         }
1226                     }
1227                   logprintf (LOG_VERBOSE, _("Creating symlink %s -> %s\n"),
1228                              u->local, f->linkto);
1229                   /* Unlink before creating symlink!  */
1230                   unlink (u->local);
1231                   if (symlink (f->linkto, u->local) == -1)
1232                     logprintf (LOG_NOTQUIET, "symlink: %s\n",
1233                                strerror (errno));
1234                   logputs (LOG_VERBOSE, "\n");
1235                 } /* have f->linkto */
1236 #else  /* not HAVE_SYMLINK */
1237               logprintf (LOG_NOTQUIET,
1238                          _("Symlinks not supported, skipping symlink `%s'.\n"),
1239                          u->local);
1240 #endif /* not HAVE_SYMLINK */
1241             }
1242           else                /* opt.retr_symlinks */
1243             {
1244               if (dlthis)
1245                 err = ftp_loop_internal (u, f, con);
1246             } /* opt.retr_symlinks */
1247           break;
1248         case FT_DIRECTORY:
1249           if (!opt.recursive)
1250             logprintf (LOG_NOTQUIET, _("Skipping directory `%s'.\n"),
1251                        f->name);
1252           break;
1253         case FT_PLAINFILE:
1254           /* Call the retrieve loop.  */
1255           if (dlthis)
1256             err = ftp_loop_internal (u, f, con);
1257           break;
1258         case FT_UNKNOWN:
1259           logprintf (LOG_NOTQUIET, _("%s: unknown/unsupported file type.\n"),
1260                      f->name);
1261           break;
1262         }       /* switch */
1263
1264       /* Set the time-stamp information to the local file.  Symlinks
1265          are not to be stamped because it sets the stamp on the
1266          original.  :( */
1267       if (!opt.dfp
1268           && !(f->type == FT_SYMLINK && !opt.retr_symlinks)
1269           && f->tstamp != -1
1270           && dlthis
1271           && file_exists_p (u->local))
1272         {
1273           touch (u->local, f->tstamp);
1274         }
1275       else if (f->tstamp == -1)
1276         logprintf (LOG_NOTQUIET, _("%s: corrupt time-stamp.\n"), u->local);
1277
1278       if (f->perms && f->type == FT_PLAINFILE && dlthis)
1279         chmod (u->local, f->perms);
1280       else
1281         DEBUGP (("Unrecognized permissions for %s.\n", u->local));
1282
1283       free (u->local);
1284       u->local = olocal;
1285       u->file = ofile;
1286       /* Break on fatals.  */
1287       if (err == QUOTEXC || err == HOSTERR || err == FWRITEERR)
1288         break;
1289       con->cmd &= ~ (DO_CWD | DO_LOGIN);
1290       f = f->next;
1291     } /* while */
1292   /* We do not want to call ftp_retrieve_dirs here */
1293   if (opt.recursive &&
1294       !(opt.reclevel != INFINITE_RECURSION && depth >= opt.reclevel))
1295     err = ftp_retrieve_dirs (u, orig, con);
1296   else if (opt.recursive)
1297     DEBUGP ((_("Will not retrieve dirs since depth is %d (max %d).\n"),
1298              depth, opt.reclevel));
1299   --depth;
1300   return err;
1301 }
1302
1303 /* Retrieve the directories given in a file list.  This function works
1304    by simply going through the linked list and calling
1305    ftp_retrieve_glob on each directory entry.  The function knows
1306    about excluded directories.  */
1307 static uerr_t
1308 ftp_retrieve_dirs (struct urlinfo *u, struct fileinfo *f, ccon *con)
1309 {
1310   char *odir;
1311   char *current_container = NULL;
1312   int current_length = 0;
1313
1314   for (; f; f = f->next)
1315     {
1316       int len;
1317
1318       if (downloaded_exceeds_quota ())
1319         break;
1320       if (f->type != FT_DIRECTORY)
1321         continue;
1322       odir = u->dir;
1323       len = 1 + strlen (u->dir) + 1 + strlen (f->name) + 1;
1324       /* Allocate u->dir off stack, but reallocate only if a larger
1325          string is needed.  */
1326       if (len > current_length)
1327         current_container = (char *)alloca (len);
1328       u->dir = current_container;
1329       /* When retrieving recursively, all directories must be
1330          absolute.  This restriction will (hopefully!) be lifted in
1331          the future.  */
1332       sprintf (u->dir, "/%s%s%s", odir + (*odir == '/'),
1333               (!*odir || (*odir == '/' && !* (odir + 1))) ? "" : "/", f->name);
1334       if (!accdir (u->dir, ALLABS))
1335         {
1336           logprintf (LOG_VERBOSE, _("\
1337 Not descending to `%s' as it is excluded/not-included.\n"), u->dir);
1338           u->dir = odir;
1339           continue;
1340         }
1341       con->st &= ~DONE_CWD;
1342       ftp_retrieve_glob (u, con, GETALL);
1343       /* Set the time-stamp?  */
1344       u->dir = odir;
1345     }
1346   if (opt.quota && opt.downloaded > opt.quota)
1347     return QUOTEXC;
1348   else
1349     return RETROK;
1350 }
1351
1352
1353 /* A near-top-level function to retrieve the files in a directory.
1354    The function calls ftp_get_listing, to get a linked list of files.
1355    Then it weeds out the file names that do not match the pattern.
1356    ftp_retrieve_list is called with this updated list as an argument.
1357
1358    If the argument ACTION is GETONE, just download the file (but first
1359    get the listing, so that the time-stamp is heeded); if it's GLOBALL,
1360    use globbing; if it's GETALL, download the whole directory.  */
1361 static uerr_t
1362 ftp_retrieve_glob (struct urlinfo *u, ccon *con, int action)
1363 {
1364   struct fileinfo *orig, *start;
1365   uerr_t res;
1366
1367   con->cmd |= LEAVE_PENDING;
1368
1369   orig = ftp_get_listing (u, con);
1370   start = orig;
1371   /* First: weed out that do not conform the global rules given in
1372      opt.accepts and opt.rejects.  */
1373   if (opt.accepts || opt.rejects)
1374     {
1375       struct fileinfo *f = orig;
1376
1377       while (f)
1378         {
1379           if (f->type != FT_DIRECTORY && !acceptable (f->name))
1380             {
1381               logprintf (LOG_VERBOSE, _("Rejecting `%s'.\n"), f->name);
1382               f = delelement (f, &start);
1383             }
1384           else
1385             f = f->next;
1386         }
1387     }
1388   /* Now weed out the files that do not match our globbing pattern.
1389      If we are dealing with a globbing pattern, that is.  */
1390   if (*u->file && (action == GLOBALL || action == GETONE))
1391     {
1392       int matchres = 0;
1393       struct fileinfo *f = start;
1394
1395       while (f)
1396         {
1397           matchres = fnmatch (u->file, f->name, 0);
1398           if (matchres == -1)
1399             {
1400               logprintf (LOG_NOTQUIET, "%s: %s\n", u->local,
1401                          strerror (errno));
1402               break;
1403             }
1404           if (matchres == FNM_NOMATCH)
1405             f = delelement (f, &start); /* delete the element from the list */
1406           else
1407             f = f->next;        /* leave the element in the list */
1408         }
1409       if (matchres == -1)
1410         {
1411           freefileinfo (start);
1412           return RETRBADPATTERN;
1413         }
1414     }
1415   res = RETROK;
1416   if (start)
1417     {
1418       /* Just get everything.  */
1419       ftp_retrieve_list (u, start, con);
1420     }
1421   else if (!start)
1422     {
1423       if (action == GLOBALL)
1424         {
1425           /* No luck.  */
1426           /* #### This message SUCKS.  We should see what was the
1427              reason that nothing was retrieved.  */
1428           logprintf (LOG_VERBOSE, _("No matches on pattern `%s'.\n"), u->file);
1429         }
1430       else /* GETONE or GETALL */
1431         {
1432           /* Let's try retrieving it anyway.  */
1433           con->st |= ON_YOUR_OWN;
1434           res = ftp_loop_internal (u, NULL, con);
1435           return res;
1436         }
1437     }
1438   freefileinfo (start);
1439   if (downloaded_exceeds_quota ())
1440     return QUOTEXC;
1441   else
1442     /* #### Should we return `res' here?  */
1443     return RETROK;
1444 }
1445
1446 /* The wrapper that calls an appropriate routine according to contents
1447    of URL.  Inherently, its capabilities are limited on what can be
1448    encoded into a URL.  */
1449 uerr_t
1450 ftp_loop (struct urlinfo *u, int *dt)
1451 {
1452   ccon con;                     /* FTP connection */
1453   uerr_t res;
1454
1455   *dt = 0;
1456
1457   rbuf_uninitialize (&con.rbuf);
1458   con.st = ON_YOUR_OWN;
1459   res = RETROK;                 /* in case it's not used */
1460
1461   /* If the file name is empty, the user probably wants a directory
1462      index.  We'll provide one, properly HTML-ized.  Unless
1463      opt.htmlify is 0, of course.  :-) */
1464   if (!*u->file && !opt.recursive)
1465     {
1466       struct fileinfo *f = ftp_get_listing (u, &con);
1467
1468       if (f)
1469         {
1470           if (opt.htmlify)
1471             {
1472               char *filename = (opt.output_document
1473                                 ? xstrdup (opt.output_document)
1474                                 : (u->local ? xstrdup (u->local)
1475                                    : url_filename (u)));
1476               res = ftp_index (filename, u, f);
1477               if (res == FTPOK && opt.verbose)
1478                 {
1479                   if (!opt.output_document)
1480                     {
1481                       struct stat st;
1482                       long sz;
1483                       if (stat (filename, &st) == 0)
1484                         sz = st.st_size;
1485                       else
1486                         sz = -1;
1487                       logprintf (LOG_NOTQUIET,
1488                                  _("Wrote HTML-ized index to `%s' [%ld].\n"),
1489                                  filename, sz);
1490                     }
1491                   else
1492                     logprintf (LOG_NOTQUIET,
1493                                _("Wrote HTML-ized index to `%s'.\n"),
1494                                filename);
1495                 }
1496               free (filename);
1497             }
1498           freefileinfo (f);
1499         }
1500     }
1501   else
1502     {
1503       int wild = has_wildcards_p (u->file);
1504       if ((opt.ftp_glob && wild) || opt.recursive || opt.timestamping)
1505         {
1506           /* ftp_retrieve_glob is a catch-all function that gets called
1507              if we need globbing, time-stamping or recursion.  Its
1508              third argument is just what we really need.  */
1509           ftp_retrieve_glob (u, &con,
1510                              (opt.ftp_glob && wild) ? GLOBALL : GETONE);
1511         }
1512       else
1513         res = ftp_loop_internal (u, NULL, &con);
1514     }
1515   if (res == FTPOK)
1516     res = RETROK;
1517   if (res == RETROK)
1518     *dt |= RETROKF;
1519   /* If a connection was left, quench it.  */
1520   if (rbuf_initialized_p (&con.rbuf))
1521     CLOSE (RBUF_FD (&con.rbuf));
1522   return res;
1523 }
1524
1525 /* Delete an element from the fileinfo linked list.  Returns the
1526    address of the next element, or NULL if the list is exhausted.  It
1527    can modify the start of the list.  */
1528 static struct fileinfo *
1529 delelement (struct fileinfo *f, struct fileinfo **start)
1530 {
1531   struct fileinfo *prev = f->prev;
1532   struct fileinfo *next = f->next;
1533
1534   free (f->name);
1535   FREE_MAYBE (f->linkto);
1536   free (f);
1537
1538   if (next)
1539     next->prev = prev;
1540   if (prev)
1541     prev->next = next;
1542   else
1543     *start = next;
1544   return next;
1545 }
1546
1547 /* Free the fileinfo linked list of files.  */
1548 static void
1549 freefileinfo (struct fileinfo *f)
1550 {
1551   while (f)
1552     {
1553       struct fileinfo *next = f->next;
1554       free (f->name);
1555       if (f->linkto)
1556         free (f->linkto);
1557       free (f);
1558       f = next;
1559     }
1560 }