]> sjero.net Git - wget/blob - src/ftp-ls.c
[svn] Applied Philipp Thomas's safe-ctype patch. Published in
[wget] / src / ftp-ls.c
1 /* Parsing FTP `ls' output.
2    Copyright (C) 1995, 1996, 1997, 2000, 2001 Free Software Foundation,
3    Inc. 
4
5 This file is part of Wget.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #ifdef HAVE_STRING_H
26 # include <string.h>
27 #else
28 # include <strings.h>
29 #endif
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <sys/types.h>
34 #include <errno.h>
35
36 #include "wget.h"
37 #include "utils.h"
38 #include "ftp.h"
39 #include "url.h"
40
41 /* Converts symbolic permissions to number-style ones, e.g. string
42    rwxr-xr-x to 755.  For now, it knows nothing of
43    setuid/setgid/sticky.  ACLs are ignored.  */
44 static int
45 symperms (const char *s)
46 {
47   int perms = 0, i;
48
49   if (strlen (s) < 9)
50     return 0;
51   for (i = 0; i < 3; i++, s += 3)
52     {
53       perms <<= 3;
54       perms += (((s[0] == 'r') << 2) + ((s[1] == 'w') << 1) +
55                 (s[2] == 'x' || s[2] == 's'));
56     }
57   return perms;
58 }
59
60
61 /* Cleans a line of text so that it can be consistently parsed. Destroys
62    <CR> and <LF> in case that thay occur at the end of the line and
63    replaces all <TAB> character with <SPACE>. Returns the length of the
64    modified line. */
65 static int
66 clean_line(char *line)
67 {
68   int len = strlen (line);
69   if (!len) return 0; 
70   if (line[len - 1] == '\n')
71     line[--len] = '\0';
72   if (line[len - 1] == '\r')
73     line[--len] = '\0';
74   for ( ; *line ; line++ ) if (*line == '\t') *line = ' '; 
75   return len;
76 }
77
78 /* Convert the Un*x-ish style directory listing stored in FILE to a
79    linked list of fileinfo (system-independent) entries.  The contents
80    of FILE are considered to be produced by the standard Unix `ls -la'
81    output (whatever that might be).  BSD (no group) and SYSV (with
82    group) listings are handled.
83
84    The time stamps are stored in a separate variable, time_t
85    compatible (I hope).  The timezones are ignored.  */
86 static struct fileinfo *
87 ftp_parse_unix_ls (const char *file, int ignore_perms)
88 {
89   FILE *fp;
90   static const char *months[] = {
91     "Jan", "Feb", "Mar", "Apr", "May", "Jun",
92     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
93   };
94   int next, len, i, error, ignore;
95   int year, month, day;         /* for time analysis */
96   int hour, min, sec;
97   struct tm timestruct, *tnow;
98   time_t timenow;
99
100   char *line, *tok;             /* tokenizer */
101   struct fileinfo *dir, *l, cur; /* list creation */
102
103   fp = fopen (file, "rb");
104   if (!fp)
105     {
106       logprintf (LOG_NOTQUIET, "%s: %s\n", file, strerror (errno));
107       return NULL;
108     }
109   dir = l = NULL;
110
111   /* Line loop to end of file: */
112   while ((line = read_whole_line (fp)))
113     {
114       len = clean_line (line);
115       /* Skip if total...  */
116       if (!strncasecmp (line, "total", 5))
117         {
118           xfree (line);
119           continue;
120         }
121       /* Get the first token (permissions).  */
122       tok = strtok (line, " ");
123       if (!tok)
124         {
125           xfree (line);
126           continue;
127         }
128
129       cur.name = NULL;
130       cur.linkto = NULL;
131
132       /* Decide whether we deal with a file or a directory.  */
133       switch (*tok)
134         {
135         case '-':
136           cur.type = FT_PLAINFILE;
137           DEBUGP (("PLAINFILE; "));
138           break;
139         case 'd':
140           cur.type = FT_DIRECTORY;
141           DEBUGP (("DIRECTORY; "));
142           break;
143         case 'l':
144           cur.type = FT_SYMLINK;
145           DEBUGP (("SYMLINK; "));
146           break;
147         default:
148           cur.type = FT_UNKNOWN;
149           DEBUGP (("UNKOWN; "));
150           break;
151         }
152
153       if (ignore_perms)
154         {
155           switch (cur.type)
156             {
157             case FT_PLAINFILE:
158               cur.perms = 420;
159               break;
160             case FT_DIRECTORY:
161               cur.perms = 493;
162               break;
163             default:
164               cur.perms = 1023;
165             }
166           DEBUGP (("implicite perms %0o; ", cur.perms));
167         }
168        else
169          {
170            cur.perms = symperms (tok + 1);
171            DEBUGP (("perms %0o; ", cur.perms));
172          }
173
174       error = ignore = 0;       /* Erroneous and ignoring entries are
175                                    treated equally for now.  */
176       year = hour = min = sec = 0; /* Silence the compiler.  */
177       month = day = 0;
178       next = -1;
179       /* While there are tokens on the line, parse them.  Next is the
180          number of tokens left until the filename.
181
182          Use the month-name token as the "anchor" (the place where the
183          position wrt the file name is "known").  When a month name is
184          encountered, `next' is set to 5.  Also, the preceding
185          characters are parsed to get the file size.
186
187          This tactic is quite dubious when it comes to
188          internationalization issues (non-English month names), but it
189          works for now.  */
190       while ((tok = strtok (NULL, " ")))
191         {
192           --next;
193           if (next < 0)         /* a month name was not encountered */
194             {
195               for (i = 0; i < 12; i++)
196                 if (!strcmp (tok, months[i]))
197                   break;
198               /* If we got a month, it means the token before it is the
199                  size, and the filename is three tokens away.  */
200               if (i != 12)
201                 {
202                   char *t = tok - 2;
203                   long mul = 1;
204
205                   for (cur.size = 0; t > line && ISDIGIT (*t); mul *= 10, t--)
206                     cur.size += mul * (*t - '0');
207                   if (t == line)
208                     {
209                       /* Something is seriously wrong.  */
210                       error = 1;
211                       break;
212                     }
213                   month = i;
214                   next = 5;
215                   DEBUGP (("month: %s; ", months[month]));
216                 }
217             }
218           else if (next == 4)   /* days */
219             {
220               if (tok[1])       /* two-digit... */
221                 day = 10 * (*tok - '0') + tok[1] - '0';
222               else              /* ...or one-digit */
223                 day = *tok - '0';
224               DEBUGP (("day: %d; ", day));
225             }
226           else if (next == 3)
227             {
228               /* This ought to be either the time, or the year.  Let's
229                  be flexible!
230
231                  If we have a number x, it's a year.  If we have x:y,
232                  it's hours and minutes.  If we have x:y:z, z are
233                  seconds.  */
234               year = 0;
235               min = hour = sec = 0;
236               /* We must deal with digits.  */
237               if (ISDIGIT (*tok))
238                 {
239                   /* Suppose it's year.  */
240                   for (; ISDIGIT (*tok); tok++)
241                     year = (*tok - '0') + 10 * year;
242                   if (*tok == ':')
243                     {
244                       /* This means these were hours!  */
245                       hour = year;
246                       year = 0;
247                       ++tok;
248                       /* Get the minutes...  */
249                       for (; ISDIGIT (*tok); tok++)
250                         min = (*tok - '0') + 10 * min;
251                       if (*tok == ':')
252                         {
253                           /* ...and the seconds.  */
254                           ++tok;
255                           for (; ISDIGIT (*tok); tok++)
256                             sec = (*tok - '0') + 10 * sec;
257                         }
258                     }
259                 }
260               if (year)
261                 DEBUGP (("year: %d (no tm); ", year));
262               else
263                 DEBUGP (("time: %02d:%02d:%02d (no yr); ", hour, min, sec));
264             }
265           else if (next == 2)    /* The file name */
266             {
267               int fnlen;
268               char *p;
269
270               /* Since the file name may contain a SPC, it is possible
271                  for strtok to handle it wrong.  */
272               fnlen = strlen (tok);
273               if (fnlen < len - (tok - line))
274                 {
275                   /* So we have a SPC in the file name.  Restore the
276                      original.  */
277                   tok[fnlen] = ' ';
278                   /* If the file is a symbolic link, it should have a
279                      ` -> ' somewhere.  */
280                   if (cur.type == FT_SYMLINK)
281                     {
282                       p = strstr (tok, " -> ");
283                       if (!p)
284                         {
285                           error = 1;
286                           break;
287                         }
288                       cur.linkto = xstrdup (p + 4);
289                       DEBUGP (("link to: %s\n", cur.linkto));
290                       /* And separate it from the file name.  */
291                       *p = '\0';
292                     }
293                 }
294               /* If we have the filename, add it to the list of files or
295                  directories.  */
296               /* "." and ".." are an exception!  */
297               if (!strcmp (tok, ".") || !strcmp (tok, ".."))
298                 {
299                   DEBUGP (("\nIgnoring `.' and `..'; "));
300                   ignore = 1;
301                   break;
302                 }
303               /* Some FTP sites choose to have ls -F as their default
304                  LIST output, which marks the symlinks with a trailing
305                  `@', directory names with a trailing `/' and
306                  executables with a trailing `*'.  This is no problem
307                  unless encountering a symbolic link ending with `@',
308                  or an executable ending with `*' on a server without
309                  default -F output.  I believe these cases are very
310                  rare.  */
311               fnlen = strlen (tok); /* re-calculate `fnlen' */
312               cur.name = (char *)xmalloc (fnlen + 1);
313               memcpy (cur.name, tok, fnlen + 1);
314               if (fnlen)
315                 {
316                   if (cur.type == FT_DIRECTORY && cur.name[fnlen - 1] == '/')
317                     {
318                       cur.name[fnlen - 1] = '\0';
319                       DEBUGP (("trailing `/' on dir.\n"));
320                     }
321                   else if (cur.type == FT_SYMLINK && cur.name[fnlen - 1] == '@')
322                     {
323                       cur.name[fnlen - 1] = '\0';
324                       DEBUGP (("trailing `@' on link.\n"));
325                     }
326                   else if (cur.type == FT_PLAINFILE
327                            && (cur.perms & 0111)
328                            && cur.name[fnlen - 1] == '*')
329                     {
330                       cur.name[fnlen - 1] = '\0';
331                       DEBUGP (("trailing `*' on exec.\n"));
332                     }
333                 } /* if (fnlen) */
334               else
335                 error = 1;
336               break;
337             }
338           else
339             abort ();
340         } /* while */
341
342       if (!cur.name || (cur.type == FT_SYMLINK && !cur.linkto))
343         error = 1;
344
345       DEBUGP (("\n"));
346
347       if (error || ignore)
348         {
349           DEBUGP (("Skipping.\n"));
350           FREE_MAYBE (cur.name);
351           FREE_MAYBE (cur.linkto);
352           xfree (line);
353           continue;
354         }
355
356       if (!dir)
357         {
358           l = dir = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
359           memcpy (l, &cur, sizeof (cur));
360           l->prev = l->next = NULL;
361         }
362       else
363         {
364           cur.prev = l;
365           l->next = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
366           l = l->next;
367           memcpy (l, &cur, sizeof (cur));
368           l->next = NULL;
369         }
370       /* Get the current time.  */
371       timenow = time (NULL);
372       tnow = localtime (&timenow);
373       /* Build the time-stamp (the idea by zaga@fly.cc.fer.hr).  */
374       timestruct.tm_sec   = sec;
375       timestruct.tm_min   = min;
376       timestruct.tm_hour  = hour;
377       timestruct.tm_mday  = day;
378       timestruct.tm_mon   = month;
379       if (year == 0)
380         {
381           /* Some listings will not specify the year if it is "obvious"
382              that the file was from the previous year.  E.g. if today
383              is 97-01-12, and you see a file of Dec 15th, its year is
384              1996, not 1997.  Thanks to Vladimir Volovich for
385              mentioning this!  */
386           if (month > tnow->tm_mon)
387             timestruct.tm_year = tnow->tm_year - 1;
388           else
389             timestruct.tm_year = tnow->tm_year;
390         }
391       else
392         timestruct.tm_year = year;
393       if (timestruct.tm_year >= 1900)
394         timestruct.tm_year -= 1900;
395       timestruct.tm_wday  = 0;
396       timestruct.tm_yday  = 0;
397       timestruct.tm_isdst = -1;
398       l->tstamp = mktime (&timestruct); /* store the time-stamp */
399
400       xfree (line);
401     }
402
403   fclose (fp);
404   return dir;
405 }
406
407 static struct fileinfo *
408 ftp_parse_winnt_ls (const char *file)
409 {
410   FILE *fp;
411   int len;
412   int year, month, day;         /* for time analysis */
413   int hour, min, sec;
414   struct tm timestruct;
415
416   char *line, *tok;             /* tokenizer */
417   struct fileinfo *dir, *l, cur; /* list creation */
418
419   fp = fopen (file, "rb");
420   if (!fp)
421     {
422       logprintf (LOG_NOTQUIET, "%s: %s\n", file, strerror (errno));
423       return NULL;
424     }
425   dir = l = NULL;
426
427   /* Line loop to end of file: */
428   while ((line = read_whole_line (fp)))
429     {
430       len = clean_line (line);
431
432       /* Extracting name is a bit of black magic and we have to do it
433          before `strtok' inserted extra \0 characters in the line
434          string. For the moment let us just suppose that the name starts at
435          column 39 of the listing. This way we could also recognize
436          filenames that begin with a series of space characters (but who
437          really wants to use such filenames anyway?). */
438       if (len < 40) continue;
439       tok = line + 39;
440       cur.name = xstrdup(tok);
441       DEBUGP(("Name: '%s'\n", cur.name));
442
443       /* First column: mm-dd-yy */
444       tok = strtok(line, "-");
445       month = atoi(tok);
446       tok = strtok(NULL, "-");
447       day = atoi(tok);
448       tok = strtok(NULL, " ");
449       year = atoi(tok);
450       /* Assuming the epoch starting at 1.1.1970 */
451       if (year <= 70) year += 100;
452
453       /* Second column: hh:mm[AP]M */
454       tok = strtok(NULL,  ":");
455       hour = atoi(tok);
456       tok = strtok(NULL,  "M");
457       min = atoi(tok);
458       /* Adjust hour from AM/PM */
459       tok+=2;
460       if (*tok == 'P') hour += 12;
461       /* Listing does not contain value for seconds */
462       sec = 0;
463
464       DEBUGP(("YYYY/MM/DD HH:MM - %d/%02d/%02d %02d:%02d\n", 
465               year+1900, month, day, hour, min));
466       
467       /* Build the time-stamp (copy & paste from above) */
468       timestruct.tm_sec   = sec;
469       timestruct.tm_min   = min;
470       timestruct.tm_hour  = hour;
471       timestruct.tm_mday  = day;
472       timestruct.tm_mon   = month;
473       timestruct.tm_year  = year;
474       timestruct.tm_wday  = 0;
475       timestruct.tm_yday  = 0;
476       timestruct.tm_isdst = -1;
477       cur.tstamp = mktime (&timestruct); /* store the time-stamp */
478
479       DEBUGP(("Timestamp: %ld\n", cur.tstamp));
480
481       /* Third column: Either file length, or <DIR>. We also set the
482          permissions (guessed as 0644 for plain files and 0755 for
483          directories as the listing does not give us a clue) and filetype
484          here. */
485       tok = strtok(NULL, " ");
486       while (*tok == '\0')  tok = strtok(NULL, " ");
487       if (*tok == '<')
488         {
489           cur.type  = FT_DIRECTORY;
490           cur.size  = 0;
491           cur.perms = 493; /* my gcc does not like 0755 ?? */
492           DEBUGP(("Directory\n"));
493         }
494       else
495         {
496           cur.type  = FT_PLAINFILE;
497           cur.size  = atoi(tok);
498           cur.perms = 420; /* 0664 octal */
499           DEBUGP(("File, size %ld bytes\n", cur.size));
500         }
501
502       cur.linkto = NULL;
503
504       /* And put everything into the linked list */
505       if (!dir)
506         {
507           l = dir = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
508           memcpy (l, &cur, sizeof (cur));
509           l->prev = l->next = NULL;
510         }
511       else
512         {
513           cur.prev = l;
514           l->next = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
515           l = l->next;
516           memcpy (l, &cur, sizeof (cur));
517           l->next = NULL;
518         }
519
520       xfree(line);
521     }
522
523   fclose(fp);
524   return dir;
525 }
526
527 /* Converts VMS symbolic permissions to number-style ones, e.g. string
528    RWED,RWE,RE to 755. "D" (delete) is taken to be equal to "W"
529    (write). Inspired by a patch of Stoyan Lekov <lekov@eda.bg>. */
530 static int
531 vmsperms (const char *s)
532 {
533   int perms = 0;
534
535   do
536     {
537       switch (*s) {
538         case ',': perms <<= 3; break;
539         case 'R': perms  |= 4; break;
540         case 'W': perms  |= 2; break;
541         case 'D': perms  |= 2; break;
542         case 'E': perms  |= 1; break;
543         default:  DEBUGP(("wrong VMS permissons!\n")); 
544       }
545     }
546   while (*++s);
547   return perms;
548 }
549
550
551 static struct fileinfo *
552 ftp_parse_vms_ls (const char *file)
553 {
554   FILE *fp;
555   /* #### A third copy of more-or-less the same array ? */
556   static const char *months[] = {
557     "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
558     "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
559   };
560   int i;
561   int year, month, day;          /* for time analysis */
562   int hour, min, sec;
563   struct tm timestruct;
564
565   char *line, *tok, *p;          /* tokenizer */
566   struct fileinfo *dir, *l, cur; /* list creation */
567
568   fp = fopen (file, "rb");
569   if (!fp)
570     {
571       logprintf (LOG_NOTQUIET, "%s: %s\n", file, strerror (errno));
572       return NULL;
573     }
574   dir = l = NULL;
575
576   /* Empty line */
577   read_whole_line (fp);
578   /* "Directory PUB$DEVICE[PUB]" */
579   read_whole_line (fp);
580   /* Empty line */
581   read_whole_line (fp);
582
583   /* Line loop to end of file: */
584   while ((line = read_whole_line (fp)))
585     {
586       i = clean_line (line);
587       if (!i) break;
588
589       /* First column: Name. A bit of black magic again. The name my be
590          either ABCD.EXT or ABCD.EXT;NUM and it might be on a separate
591          line. Therefore we will first try to get the complete name
592          until the first space character; if it fails, we assume that the name
593          occupies the whole line. After that we search for the version
594          separator ";", we remove it and check the extension of the file;
595          extension .DIR denotes directory. */
596
597       tok = strtok(line, " ");
598       if (tok == NULL) tok = line;
599       DEBUGP(("file name: '%s'\n", tok));
600       for (p = tok ; *p && *p != ';' ; p++);
601       if (*p == ';') *p = '\0';
602       p   = tok + strlen(tok) - 4;
603       if (!strcmp(p, ".DIR")) *p = '\0';
604       cur.name = xstrdup(tok);
605       DEBUGP(("Name: '%s'\n", cur.name));
606
607       /* If the name ends on .DIR or .DIR;#, it's a directory. We also set
608          the file size to zero as the listing does tell us only the size in
609          filesystem blocks - for an integrity check (when mirroring, for
610          example) we would need the size in bytes. */
611       
612       if (! *p)
613         {
614           cur.type  = FT_DIRECTORY;
615           cur.size  = 0;
616           DEBUGP(("Directory\n"));
617         }
618       else
619         {
620           cur.type  = FT_PLAINFILE;
621           DEBUGP(("File\n"));
622         }
623
624       cur.size  = 0;
625
626       /* Second column, if exists, or the first column of the next line
627          contain file size in blocks. We will skip it. */
628
629       tok = strtok(NULL, " ");
630       if (tok == NULL) 
631       {
632         DEBUGP(("Getting additional line\n"));
633         xfree (line);
634         line = read_whole_line (fp);
635         if (!line)
636         {
637           DEBUGP(("empty line read, leaving listing parser\n"));
638           break;
639         }
640         i = clean_line (line);
641         if (!i) 
642         {
643           DEBUGP(("confusing VMS listing item, leaving listing parser\n"));
644           break;
645         }
646         tok = strtok(line, " ");
647       }
648       DEBUGP(("second token: '%s'\n", tok));
649
650       /* Third/Second column: Date DD-MMM-YYYY. */
651
652       tok = strtok(NULL, "-");
653       DEBUGP(("day: '%s'\n",tok));
654       day = atoi(tok);
655       tok = strtok(NULL, "-");
656       if (!tok)
657       {
658         /* If the server produces garbage like
659            'EA95_0PS.GZ;1      No privilege for attempted operation'
660            the first strtok(NULL, "-") will return everything until the end
661            of the line and only the next strtok() call will return NULL. */
662         DEBUGP(("nonsense in VMS listing, skipping this line\n"));
663         break;
664       }
665       for (i=0; i<12; i++) if (!strcmp(tok,months[i])) break;
666       /* Uknown months are mapped to January */
667       month = (i%12)+1; 
668       tok = strtok(NULL, " ");
669       year = atoi(tok)-1900;
670       DEBUGP(("date parsed\n"));
671
672       /* Fourth/Third column: Time hh:mm:ss */
673       tok = strtok(NULL,  ":");
674       hour = atoi(tok);
675       tok = strtok(NULL,  ":");
676       min = atoi(tok);
677       tok = strtok(NULL,  " ");
678       sec = atoi(tok);
679
680       DEBUGP(("YYYY/MM/DD HH:MM:SS - %d/%02d/%02d %02d:%02d:%02d\n", 
681               year+1900, month, day, hour, min, sec));
682       
683       /* Build the time-stamp (copy & paste from above) */
684       timestruct.tm_sec   = sec;
685       timestruct.tm_min   = min;
686       timestruct.tm_hour  = hour;
687       timestruct.tm_mday  = day;
688       timestruct.tm_mon   = month;
689       timestruct.tm_year  = year;
690       timestruct.tm_wday  = 0;
691       timestruct.tm_yday  = 0;
692       timestruct.tm_isdst = -1;
693       cur.tstamp = mktime (&timestruct); /* store the time-stamp */
694
695       DEBUGP(("Timestamp: %ld\n", cur.tstamp));
696
697       /* Skip the fifth column */
698
699       tok = strtok(NULL, " ");
700
701       /* Sixth column: Permissions */
702
703       tok = strtok(NULL, ","); /* Skip the VMS-specific SYSTEM permissons */
704       tok = strtok(NULL, ")");
705       if (tok == NULL)
706         {
707           DEBUGP(("confusing VMS permissions, skipping line\n"));
708           continue;
709         }
710       /* Permissons have the format "RWED,RWED,RE" */
711       cur.perms = vmsperms(tok);
712       DEBUGP(("permissions: %s -> 0%o\n", tok, cur.perms));
713
714       cur.linkto = NULL;
715
716       /* And put everything into the linked list */
717       if (!dir)
718         {
719           l = dir = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
720           memcpy (l, &cur, sizeof (cur));
721           l->prev = l->next = NULL;
722         }
723       else
724         {
725           cur.prev = l;
726           l->next = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
727           l = l->next;
728           memcpy (l, &cur, sizeof (cur));
729           l->next = NULL;
730         }
731
732       xfree (line);
733     }
734
735   fclose (fp);
736   return dir;
737 }
738
739
740 /* This function switches between the correct parsing routine depending on
741    the SYSTEM_TYPE. The system type should be based on the result of the
742    "SYST" response of the FTP server. According to this repsonse we will
743    use on of the three different listing parsers that cover the most of FTP
744    servers used nowadays.  */
745
746 struct fileinfo *
747 ftp_parse_ls (const char *file, const enum stype system_type)
748 {
749   switch (system_type)
750     {
751     case ST_UNIX:
752       return ftp_parse_unix_ls (file, FALSE);
753     case ST_WINNT:
754       {
755         /* Detect whether the listing is simulating the UNIX format */
756         FILE *fp;
757         int   c;
758         fp = fopen (file, "rb");
759         if (!fp)
760         {
761           logprintf (LOG_NOTQUIET, "%s: %s\n", file, strerror (errno));
762           return NULL;
763         }
764         c = fgetc(fp);
765         fclose(fp);
766         /* If the first character of the file is '0'-'9', it's WINNT
767            format. */
768         if (c >= '0' && c <='9')
769           return ftp_parse_winnt_ls (file);
770         else
771           return ftp_parse_unix_ls (file, TRUE);
772       }
773     case ST_VMS:
774       return ftp_parse_vms_ls (file);
775     case ST_MACOS:
776       return ftp_parse_unix_ls (file, TRUE);
777     default:
778       logprintf (LOG_NOTQUIET, _("\
779 Usupported listing type, trying Unix listing parser.\n"));
780       return ftp_parse_unix_ls (file, FALSE);
781     }
782 }
783 \f
784 /* Stuff for creating FTP index. */
785
786 /* The function creates an HTML index containing references to given
787    directories and files on the appropriate host.  The references are
788    FTP.  */
789 uerr_t
790 ftp_index (const char *file, struct urlinfo *u, struct fileinfo *f)
791 {
792   FILE *fp;
793   char *upwd;
794   char *htclfile;               /* HTML-clean file name */
795
796   if (!opt.dfp)
797     {
798       fp = fopen (file, "wb");
799       if (!fp)
800         {
801           logprintf (LOG_NOTQUIET, "%s: %s\n", file, strerror (errno));
802           return FOPENERR;
803         }
804     }
805   else
806     fp = opt.dfp;
807   if (u->user)
808     {
809       char *tmpu, *tmpp;        /* temporary, clean user and passwd */
810
811       tmpu = CLEANDUP (u->user);
812       tmpp = u->passwd ? CLEANDUP (u->passwd) : NULL;
813       upwd = (char *)xmalloc (strlen (tmpu)
814                              + (tmpp ? (1 + strlen (tmpp)) : 0) + 2);
815       sprintf (upwd, "%s%s%s@", tmpu, tmpp ? ":" : "", tmpp ? tmpp : "");
816       xfree (tmpu);
817       FREE_MAYBE (tmpp);
818     }
819   else
820     upwd = xstrdup ("");
821   fprintf (fp, "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n");
822   fprintf (fp, "<html>\n<head>\n<title>");
823   fprintf (fp, _("Index of /%s on %s:%d"), u->dir, u->host, u->port);
824   fprintf (fp, "</title>\n</head>\n<body>\n<h1>");
825   fprintf (fp, _("Index of /%s on %s:%d"), u->dir, u->host, u->port);
826   fprintf (fp, "</h1>\n<hr>\n<pre>\n");
827   while (f)
828     {
829       fprintf (fp, "  ");
830       if (f->tstamp != -1)
831         {
832           /* #### Should we translate the months? */
833           static char *months[] = {
834             "Jan", "Feb", "Mar", "Apr", "May", "Jun",
835             "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
836           };
837           struct tm *ptm = localtime ((time_t *)&f->tstamp);
838
839           fprintf (fp, "%d %s %02d ", ptm->tm_year + 1900, months[ptm->tm_mon],
840                   ptm->tm_mday);
841           if (ptm->tm_hour)
842             fprintf (fp, "%02d:%02d  ", ptm->tm_hour, ptm->tm_min);
843           else
844             fprintf (fp, "       ");
845         }
846       else
847         fprintf (fp, _("time unknown       "));
848       switch (f->type)
849         {
850         case FT_PLAINFILE:
851           fprintf (fp, _("File        "));
852           break;
853         case FT_DIRECTORY:
854           fprintf (fp, _("Directory   "));
855           break;
856         case FT_SYMLINK:
857           fprintf (fp, _("Link        "));
858           break;
859         default:
860           fprintf (fp, _("Not sure    "));
861           break;
862         }
863       htclfile = html_quote_string (f->name);
864       fprintf (fp, "<a href=\"ftp://%s%s:%hu", upwd, u->host, u->port);
865       if (*u->dir != '/')
866         putc ('/', fp);
867       fprintf (fp, "%s", u->dir);
868       if (*u->dir)
869         putc ('/', fp);
870       fprintf (fp, "%s", htclfile);
871       if (f->type == FT_DIRECTORY)
872         putc ('/', fp);
873       fprintf (fp, "\">%s", htclfile);
874       if (f->type == FT_DIRECTORY)
875         putc ('/', fp);
876       fprintf (fp, "</a> ");
877       if (f->type == FT_PLAINFILE)
878         fprintf (fp, _(" (%s bytes)"), legible (f->size));
879       else if (f->type == FT_SYMLINK)
880         fprintf (fp, "-> %s", f->linkto ? f->linkto : "(nil)");
881       putc ('\n', fp);
882       xfree (htclfile);
883       f = f->next;
884     }
885   fprintf (fp, "</pre>\n</body>\n</html>\n");
886   xfree (upwd);
887   if (!opt.dfp)
888     fclose (fp);
889   else
890     fflush (fp);
891   return FTPOK;
892 }