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