Synthesize a st_ino field for fts(3) use across FTP.
[platform/upstream/rpm.git] / rpmio / rpmrpc.c
1 /*@-type@*/ /* LCL: function typedefs */
2 /** \ingroup rpmio
3  * \file rpmio/rpmrpc.c
4  */
5
6 #include "system.h"
7 #include <pthread.h>
8 #include <rpmio_internal.h>
9 #include <popt.h>
10 #include "ugid.h"
11 #include "debug.h"
12
13 /*@access FD_t@*/
14 /*@access urlinfo@*/
15
16 /*@-redecl@*/
17 extern int _ftp_debug;
18 /*@=redecl@*/
19
20 /*@-redecl@*/
21 extern int _rpmio_debug;
22 /*@=redecl@*/
23
24 /* =============================================================== */
25 static int ftpMkdir(const char * path, /*@unused@*/ mode_t mode)
26         /*@globals fileSystem @*/
27         /*@modifies fileSystem @*/
28 {
29     int rc;
30     if ((rc = ftpCmd("MKD", path, NULL)) != 0)
31         return rc;
32 #if NOTYET
33     {   char buf[20];
34         sprintf(buf, " 0%o", mode);
35         (void) ftpCmd("SITE CHMOD", path, buf);
36     }
37 #endif
38     return rc;
39 }
40
41 static int ftpChdir(const char * path)
42         /*@globals fileSystem @*/
43         /*@modifies fileSystem @*/
44 {
45     return ftpCmd("CWD", path, NULL);
46 }
47
48 static int ftpRmdir(const char * path)
49         /*@globals fileSystem @*/
50         /*@modifies fileSystem @*/
51 {
52     return ftpCmd("RMD", path, NULL);
53 }
54
55 static int ftpRename(const char * oldpath, const char * newpath)
56         /*@globals fileSystem @*/
57         /*@modifies fileSystem @*/
58 {
59     int rc;
60     if ((rc = ftpCmd("RNFR", oldpath, NULL)) != 0)
61         return rc;
62     return ftpCmd("RNTO", newpath, NULL);
63 }
64
65 static int ftpUnlink(const char * path)
66         /*@globals fileSystem @*/
67         /*@modifies fileSystem @*/
68 {
69     return ftpCmd("DELE", path, NULL);
70 }
71
72 /* =============================================================== */
73 /* XXX rebuilddb.c: analogues to mkdir(2)/rmdir(2). */
74 int Mkdir (const char * path, mode_t mode)
75 {
76     const char * lpath;
77     int ut = urlPath(path, &lpath);
78
79     switch (ut) {
80     case URL_IS_FTP:
81         return ftpMkdir(path, mode);
82         /*@notreached@*/ break;
83     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
84     case URL_IS_PATH:
85         path = lpath;
86         /*@fallthrough@*/
87     case URL_IS_UNKNOWN:
88         break;
89     case URL_IS_DASH:
90     default:
91         return -2;
92         /*@notreached@*/ break;
93     }
94     return mkdir(path, mode);
95 }
96
97 int Chdir (const char * path)
98 {
99     const char * lpath;
100     int ut = urlPath(path, &lpath);
101
102     switch (ut) {
103     case URL_IS_FTP:
104         return ftpChdir(path);
105         /*@notreached@*/ break;
106     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
107     case URL_IS_PATH:
108         path = lpath;
109         /*@fallthrough@*/
110     case URL_IS_UNKNOWN:
111         break;
112     case URL_IS_DASH:
113     default:
114         return -2;
115         /*@notreached@*/ break;
116     }
117     return chdir(path);
118 }
119
120 int Rmdir (const char * path)
121 {
122     const char * lpath;
123     int ut = urlPath(path, &lpath);
124
125     switch (ut) {
126     case URL_IS_FTP:
127         return ftpRmdir(path);
128         /*@notreached@*/ break;
129     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
130     case URL_IS_PATH:
131         path = lpath;
132         /*@fallthrough@*/
133     case URL_IS_UNKNOWN:
134         break;
135     case URL_IS_DASH:
136     default:
137         return -2;
138         /*@notreached@*/ break;
139     }
140     return rmdir(path);
141 }
142
143 /* XXX rpmdb.c: analogue to rename(2). */
144
145 int Rename (const char * oldpath, const char * newpath)
146 {
147     const char *oe = NULL;
148     const char *ne = NULL;
149     int oldut, newut;
150
151     /* XXX lib/install.c used to rely on this behavior. */
152     if (!strcmp(oldpath, newpath)) return 0;
153
154     oldut = urlPath(oldpath, &oe);
155     switch (oldut) {
156     case URL_IS_FTP:            /* XXX WRONG WRONG WRONG */
157     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
158     case URL_IS_PATH:
159     case URL_IS_UNKNOWN:
160         break;
161     case URL_IS_DASH:
162     default:
163         return -2;
164         /*@notreached@*/ break;
165     }
166
167     newut = urlPath(newpath, &ne);
168     switch (newut) {
169     case URL_IS_FTP:
170 if (_rpmio_debug)
171 fprintf(stderr, "*** rename old %*s new %*s\n", (int)(oe - oldpath), oldpath, (int)(ne - newpath), newpath);
172         if (!(oldut == newut && oe && ne && (oe - oldpath) == (ne - newpath) &&
173             !xstrncasecmp(oldpath, newpath, (oe - oldpath))))
174             return -2;
175         return ftpRename(oldpath, newpath);
176         /*@notreached@*/ break;
177     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
178     case URL_IS_PATH:
179         oldpath = oe;
180         newpath = ne;
181         break;
182     case URL_IS_UNKNOWN:
183         break;
184     case URL_IS_DASH:
185     default:
186         return -2;
187         /*@notreached@*/ break;
188     }
189     return rename(oldpath, newpath);
190 }
191
192 int Link (const char * oldpath, const char * newpath)
193 {
194     const char *oe = NULL;
195     const char *ne = NULL;
196     int oldut, newut;
197
198     oldut = urlPath(oldpath, &oe);
199     switch (oldut) {
200     case URL_IS_FTP:            /* XXX WRONG WRONG WRONG */
201     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
202     case URL_IS_PATH:
203     case URL_IS_UNKNOWN:
204         break;
205     case URL_IS_DASH:
206     default:
207         return -2;
208         /*@notreached@*/ break;
209     }
210
211     newut = urlPath(newpath, &ne);
212     switch (newut) {
213     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
214     case URL_IS_FTP:            /* XXX WRONG WRONG WRONG */
215     case URL_IS_PATH:
216 if (_rpmio_debug)
217 fprintf(stderr, "*** link old %*s new %*s\n", (int)(oe - oldpath), oldpath, (int)(ne - newpath), newpath);
218         if (!(oldut == newut && oe && ne && (oe - oldpath) == (ne - newpath) &&
219             !xstrncasecmp(oldpath, newpath, (oe - oldpath))))
220             return -2;
221         oldpath = oe;
222         newpath = ne;
223         break;
224     case URL_IS_UNKNOWN:
225         break;
226     case URL_IS_DASH:
227     default:
228         return -2;
229         /*@notreached@*/ break;
230     }
231     return link(oldpath, newpath);
232 }
233
234 /* XXX build/build.c: analogue to unlink(2). */
235
236 int Unlink(const char * path) {
237     const char * lpath;
238     int ut = urlPath(path, &lpath);
239
240     switch (ut) {
241     case URL_IS_FTP:
242         return ftpUnlink(path);
243         /*@notreached@*/ break;
244     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
245     case URL_IS_PATH:
246         path = lpath;
247         /*@fallthrough@*/
248     case URL_IS_UNKNOWN:
249         break;
250     case URL_IS_DASH:
251     default:
252         return -2;
253         /*@notreached@*/ break;
254     }
255     return unlink(path);
256 }
257
258 /* XXX swiped from mc-4.5.39-pre9 vfs/ftpfs.c */
259
260 #define g_strdup        xstrdup
261 #define g_free          free
262
263 /*
264  * FIXME: this is broken. It depends on mc not crossing border on month!
265  */
266 /*@unchecked@*/
267 static int current_mday;
268 /*@unchecked@*/
269 static int current_mon;
270 /*@unchecked@*/
271 static int current_year;
272
273 /* Following stuff (parse_ls_lga) is used by ftpfs and extfs */
274 #define MAXCOLS         30
275
276 /*@unchecked@*/
277 static char *columns [MAXCOLS]; /* Points to the string in column n */
278 /*@unchecked@*/
279 static int   column_ptr [MAXCOLS]; /* Index from 0 to the starting positions of the columns */
280
281 static int
282 vfs_split_text (char *p)
283         /*@globals columns, column_ptr @*/
284         /*@modifies *p, columns, column_ptr @*/
285 {
286     char *original = p;
287     int  numcols;
288
289
290     for (numcols = 0; *p && numcols < MAXCOLS; numcols++){
291         while (*p == ' ' || *p == '\r' || *p == '\n'){
292             *p = 0;
293             p++;
294         }
295         columns [numcols] = p;
296         column_ptr [numcols] = p - original;
297         while (*p && *p != ' ' && *p != '\r' && *p != '\n')
298             p++;
299     }
300     return numcols;
301 }
302
303 static int
304 is_num (int idx)
305         /*@*/
306 {
307     if (!columns [idx] || columns [idx][0] < '0' || columns [idx][0] > '9')
308         return 0;
309     return 1;
310 }
311
312 static int
313 is_dos_date(/*@null@*/ const char *str)
314         /*@*/
315 {
316     if (str != NULL && strlen(str) == 8 &&
317                 str[2] == str[5] && strchr("\\-/", (int)str[2]) != NULL)
318         return 1;
319     return 0;
320 }
321
322 static int
323 is_week (/*@null@*/ const char * str, /*@out@*/ struct tm * tim)
324         /*@modifies *tim @*/
325 {
326 /*@observer@*/ static const char * week = "SunMonTueWedThuFriSat";
327     const char * pos;
328
329     /*@-observertrans -mayaliasunique@*/
330     if (str != NULL && (pos=strstr(week, str)) != NULL) {
331     /*@=observertrans =mayaliasunique@*/
332         if (tim != NULL)
333             tim->tm_wday = (pos - week)/3;
334         return 1;
335     }
336     return 0;    
337 }
338
339 static int
340 is_month (/*@null@*/ const char * str, /*@out@*/ struct tm * tim)
341         /*@modifies *tim @*/
342 {
343 /*@observer@*/ static const char * month = "JanFebMarAprMayJunJulAugSepOctNovDec";
344     const char * pos;
345     
346     /*@-observertrans -mayaliasunique@*/
347     if (str != NULL && (pos = strstr(month, str)) != NULL) {
348     /*@=observertrans -mayaliasunique@*/
349         if (tim != NULL)
350             tim->tm_mon = (pos - month)/3;
351         return 1;
352     }
353     return 0;
354 }
355
356 static int
357 is_time (/*@null@*/ const char * str, /*@out@*/ struct tm * tim)
358         /*@modifies *tim @*/
359 {
360     const char * p, * p2;
361
362     if (str != NULL && (p = strchr(str, ':')) && (p2 = strrchr(str, ':'))) {
363         if (p != p2) {
364             if (sscanf (str, "%2d:%2d:%2d", &tim->tm_hour, &tim->tm_min, &tim->tm_sec) != 3)
365                 return 0;
366         } else {
367             if (sscanf (str, "%2d:%2d", &tim->tm_hour, &tim->tm_min) != 2)
368                 return 0;
369         }
370     } else 
371         return 0;
372     
373     return 1;
374 }
375
376 static int is_year(/*@null@*/ const char * str, /*@out@*/ struct tm * tim)
377         /*@modifies *tim @*/
378 {
379     long year;
380
381     if (str == NULL)
382         return 0;
383
384     if (strchr(str,':'))
385         return 0;
386
387     if (strlen(str) != 4)
388         return 0;
389
390     if (sscanf(str, "%ld", &year) != 1)
391         return 0;
392
393     if (year < 1900 || year > 3000)
394         return 0;
395
396     tim->tm_year = (int) (year - 1900);
397
398     return 1;
399 }
400
401 /*
402  * FIXME: this is broken. Consider following entry:
403  * -rwx------   1 root     root            1 Aug 31 10:04 2904 1234
404  * where "2904 1234" is filename. Well, this code decodes it as year :-(.
405  */
406
407 static int
408 vfs_parse_filetype (char c)
409         /*@*/
410 {
411     switch (c) {
412         case 'd': return S_IFDIR; 
413         case 'b': return S_IFBLK;
414         case 'c': return S_IFCHR;
415         case 'l': return S_IFLNK;
416         case 's':
417 #ifdef IS_IFSOCK /* And if not, we fall through to IFIFO, which is pretty close */
418                   return S_IFSOCK;
419 #endif
420         case 'p': return S_IFIFO;
421         case 'm': case 'n':             /* Don't know what these are :-) */
422         case '-': case '?': return S_IFREG;
423         default: return -1;
424     }
425 }
426
427 static int vfs_parse_filemode (const char *p)
428         /*@*/
429 {       /* converts rw-rw-rw- into 0666 */
430     int res = 0;
431     switch (*(p++)) {
432         case 'r': res |= 0400; break;
433         case '-': break;
434         default: return -1;
435     }
436     switch (*(p++)) {
437         case 'w': res |= 0200; break;
438         case '-': break;
439         default: return -1;
440     }
441     switch (*(p++)) {
442         case 'x': res |= 0100; break;
443         case 's': res |= 0100 | S_ISUID; break;
444         case 'S': res |= S_ISUID; break;
445         case '-': break;
446         default: return -1;
447     }
448     switch (*(p++)) {
449         case 'r': res |= 0040; break;
450         case '-': break;
451         default: return -1;
452     }
453     switch (*(p++)) {
454         case 'w': res |= 0020; break;
455         case '-': break;
456         default: return -1;
457     }
458     switch (*(p++)) {
459         case 'x': res |= 0010; break;
460         case 's': res |= 0010 | S_ISGID; break;
461         case 'l': /* Solaris produces these */
462         case 'S': res |= S_ISGID; break;
463         case '-': break;
464         default: return -1;
465     }
466     switch (*(p++)) {
467         case 'r': res |= 0004; break;
468         case '-': break;
469         default: return -1;
470     }
471     switch (*(p++)) {
472         case 'w': res |= 0002; break;
473         case '-': break;
474         default: return -1;
475     }
476     switch (*(p++)) {
477         case 'x': res |= 0001; break;
478         case 't': res |= 0001 | S_ISVTX; break;
479         case 'T': res |= S_ISVTX; break;
480         case '-': break;
481         default: return -1;
482     }
483     return res;
484 }
485
486 static int vfs_parse_filedate(int idx, /*@out@*/ time_t *t)
487         /*@modifies *t @*/
488 {       /* This thing parses from idx in columns[] array */
489
490     char *p;
491     struct tm tim;
492     int d[3];
493     int got_year = 0;
494
495     /* Let's setup default time values */
496     tim.tm_year = current_year;
497     tim.tm_mon  = current_mon;
498     tim.tm_mday = current_mday;
499     tim.tm_hour = 0;
500     tim.tm_min  = 0;
501     tim.tm_sec  = 0;
502     tim.tm_isdst = -1; /* Let mktime() try to guess correct dst offset */
503     
504     p = columns [idx++];
505     
506     /* We eat weekday name in case of extfs */
507     if(is_week(p, &tim))
508         p = columns [idx++];
509
510     /* Month name */
511     if(is_month(p, &tim)){
512         /* And we expect, it followed by day number */
513         if (is_num (idx))
514             tim.tm_mday = (int)atol (columns [idx++]);
515         else
516             return 0; /* No day */
517
518     } else {
519         /* We usually expect:
520            Mon DD hh:mm
521            Mon DD  YYYY
522            But in case of extfs we allow these date formats:
523            Mon DD YYYY hh:mm
524            Mon DD hh:mm YYYY
525            Wek Mon DD hh:mm:ss YYYY
526            MM-DD-YY hh:mm
527            where Mon is Jan-Dec, DD, MM, YY two digit day, month, year,
528            YYYY four digit year, hh, mm, ss two digit hour, minute or second. */
529
530         /* Here just this special case with MM-DD-YY */
531         if (is_dos_date(p)){
532             /*@-mods@*/
533             p[2] = p[5] = '-';
534             /*@=mods@*/
535             
536             memset(d, 0, sizeof(d));
537             if (sscanf(p, "%2d-%2d-%2d", &d[0], &d[1], &d[2]) == 3){
538             /*  We expect to get:
539                 1. MM-DD-YY
540                 2. DD-MM-YY
541                 3. YY-MM-DD
542                 4. YY-DD-MM  */
543                 
544                 /* Hmm... maybe, next time :)*/
545                 
546                 /* At last, MM-DD-YY */
547                 d[0]--; /* Months are zerobased */
548                 /* Y2K madness */
549                 if(d[2] < 70)
550                     d[2] += 100;
551
552                 tim.tm_mon  = d[0];
553                 tim.tm_mday = d[1];
554                 tim.tm_year = d[2];
555                 got_year = 1;
556             } else
557                 return 0; /* sscanf failed */
558         } else
559             return 0; /* unsupported format */
560     }
561
562     /* Here we expect to find time and/or year */
563     
564     if (is_num (idx)) {
565         if(is_time(columns[idx], &tim) || (got_year = is_year(columns[idx], &tim))) {
566         idx++;
567
568         /* This is a special case for ctime() or Mon DD YYYY hh:mm */
569         if(is_num (idx) && 
570             ((got_year = is_year(columns[idx], &tim)) || is_time(columns[idx], &tim)))
571                 idx++; /* time & year or reverse */
572         } /* only time or date */
573     }
574     else 
575         return 0; /* Nor time or date */
576
577     /*
578      * If the date is less than 6 months in the past, it is shown without year
579      * other dates in the past or future are shown with year but without time
580      * This does not check for years before 1900 ... I don't know, how
581      * to represent them at all
582      */
583     if (!got_year &&
584         current_mon < 6 && current_mon < tim.tm_mon && 
585         tim.tm_mon - current_mon >= 6)
586
587         tim.tm_year--;
588
589     if ((*t = mktime(&tim)) < 0)
590         *t = 0;
591     return idx;
592 }
593
594 static int
595 vfs_parse_ls_lga (char * p, /*@out@*/ struct stat * st,
596                 /*@out@*/ const char ** filename,
597                 /*@out@*/ const char ** linkname)
598         /*@modifies *p, *st, *filename, *linkname @*/
599 {
600     int idx, idx2, num_cols;
601     int i;
602     char *p_copy;
603     
604     if (strncmp (p, "total", 5) == 0)
605         return 0;
606
607     p_copy = g_strdup(p);
608 /* XXX FIXME: parse out inode number from "NLST -lai ." */
609 /* XXX FIXME: parse out sizein blocks from "NLST -lais ." */
610
611     if ((i = vfs_parse_filetype(*(p++))) == -1)
612         goto error;
613
614     st->st_mode = i;
615     if (*p == ' ')      /* Notwell 4 */
616         p++;
617     if (*p == '['){
618         if (strlen (p) <= 8 || p [8] != ']')
619             goto error;
620         /* Should parse here the Notwell permissions :) */
621         /*@-unrecog@*/
622         if (S_ISDIR (st->st_mode))
623             st->st_mode |= (S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR | S_IXUSR | S_IXGRP | S_IXOTH);
624         else
625             st->st_mode |= (S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR);
626         p += 9;
627         /*@=unrecog@*/
628     } else {
629         if ((i = vfs_parse_filemode(p)) == -1)
630             goto error;
631         st->st_mode |= i;
632         p += 9;
633
634         /* This is for an extra ACL attribute (HP-UX) */
635         if (*p == '+')
636             p++;
637     }
638
639     g_free(p_copy);
640     p_copy = g_strdup(p);
641     num_cols = vfs_split_text (p);
642
643     st->st_nlink = atol (columns [0]);
644     if (st->st_nlink < 0)
645         goto error;
646
647     if (!is_num (1))
648 #ifdef  HACK
649         st->st_uid = finduid (columns [1]);
650 #else
651         (void) unameToUid (columns [1], &st->st_uid);
652 #endif
653     else
654         st->st_uid = (uid_t) atol (columns [1]);
655
656     /* Mhm, the ls -lg did not produce a group field */
657     for (idx = 3; idx <= 5; idx++) 
658         if (is_month(columns [idx], NULL) || is_week(columns [idx], NULL) || is_dos_date(columns[idx]))
659             break;
660
661     if (idx == 6 || (idx == 5 && !S_ISCHR (st->st_mode) && !S_ISBLK (st->st_mode)))
662         goto error;
663
664     /* We don't have gid */     
665     if (idx == 3 || (idx == 4 && (S_ISCHR(st->st_mode) || S_ISBLK (st->st_mode))))
666         idx2 = 2;
667     else { 
668         /* We have gid field */
669         if (is_num (2))
670             st->st_gid = (gid_t) atol (columns [2]);
671         else
672 #ifdef  HACK
673             st->st_gid = findgid (columns [2]);
674 #else
675             (void) gnameToGid (columns [1], &st->st_gid);
676 #endif
677         idx2 = 3;
678     }
679
680     /* This is device */
681     if (S_ISCHR (st->st_mode) || S_ISBLK (st->st_mode)){
682         int maj, min;
683         
684         if (!is_num (idx2) || sscanf(columns [idx2], " %d,", &maj) != 1)
685             goto error;
686         
687         if (!is_num (++idx2) || sscanf(columns [idx2], " %d", &min) != 1)
688             goto error;
689         
690 #ifdef HAVE_ST_RDEV
691         st->st_rdev = ((maj & 0xff) << 8) | (min & 0xffff00ff);
692 #endif
693         st->st_size = 0;
694         
695     } else {
696         /* Common file size */
697         if (!is_num (idx2))
698             goto error;
699         
700         st->st_size = (size_t) atol (columns [idx2]);
701 #ifdef HAVE_ST_RDEV
702         st->st_rdev = 0;
703 #endif
704     }
705
706     idx = vfs_parse_filedate(idx, &st->st_mtime);
707     if (!idx)
708         goto error;
709     /* Use resulting time value */
710     st->st_atime = st->st_ctime = st->st_mtime;
711     st->st_dev = 0;
712     st->st_ino = 0;
713 #ifdef HAVE_ST_BLKSIZE
714     st->st_blksize = 512;
715 #endif
716 #ifdef HAVE_ST_BLOCKS
717     st->st_blocks = (st->st_size + 511) / 512;
718 #endif
719
720     for (i = idx + 1, idx2 = 0; i < num_cols; i++ ) 
721         if (strcmp (columns [i], "->") == 0){
722             idx2 = i;
723             break;
724         }
725     
726     if (((S_ISLNK (st->st_mode) || 
727         (num_cols == idx + 3 && st->st_nlink > 1))) /* Maybe a hardlink? (in extfs) */
728         && idx2){
729         int tlen;
730         char *t;
731             
732         if (filename){
733 #ifdef HACK
734             t = g_strndup (p_copy + column_ptr [idx], column_ptr [idx2] - column_ptr [idx] - 1);
735 #else
736             int nb = column_ptr [idx2] - column_ptr [idx] - 1;
737             t = xmalloc(nb+1);
738             strncpy(t, p_copy + column_ptr [idx], nb);
739 #endif
740             *filename = t;
741         }
742         if (linkname){
743             t = g_strdup (p_copy + column_ptr [idx2+1]);
744             tlen = strlen (t);
745             if (t [tlen-1] == '\r' || t [tlen-1] == '\n')
746                 t [tlen-1] = 0;
747             if (t [tlen-2] == '\r' || t [tlen-2] == '\n')
748                 t [tlen-2] = 0;
749                 
750             *linkname = t;
751         }
752     } else {
753         /* Extract the filename from the string copy, not from the columns
754          * this way we have a chance of entering hidden directories like ". ."
755          */
756         if (filename){
757             /* 
758             *filename = g_strdup (columns [idx++]);
759             */
760             int tlen;
761             char *t;
762             
763             t = g_strdup (p_copy + column_ptr [idx]); idx++;
764             tlen = strlen (t);
765             /* g_strchomp(); */
766             if (t [tlen-1] == '\r' || t [tlen-1] == '\n')
767                 t [tlen-1] = 0;
768             if (t [tlen-2] == '\r' || t [tlen-2] == '\n')
769                 t [tlen-2] = 0;
770             
771             *filename = t;
772         }
773         if (linkname)
774             *linkname = NULL;
775     }
776     g_free (p_copy);
777     return 1;
778
779 error:
780 #ifdef  HACK
781     {
782       static int errorcount = 0;
783
784       if (++errorcount < 5) {
785         message_1s (1, "Could not parse:", p_copy);
786       } else if (errorcount == 5)
787         message_1s (1, "More parsing errors will be ignored.", "(sorry)" );
788     }
789 #endif
790
791     /*@-usereleased@*/
792     if (p_copy != p)            /* Carefull! */
793     /*@=usereleased@*/
794         g_free (p_copy);
795     return 0;
796 }
797
798 typedef enum {
799         DO_FTP_STAT     = 1,
800         DO_FTP_LSTAT    = 2,
801         DO_FTP_READLINK = 3,
802         DO_FTP_ACCESS   = 4,
803         DO_FTP_GLOB     = 5
804 } ftpSysCall_t;
805
806 /**
807  */
808 /*@unchecked@*/
809 static size_t ftpBufAlloced = 0;
810
811 /**
812  */
813 /*@unchecked@*/
814 static /*@only@*/ char * ftpBuf = NULL;
815         
816 #define alloca_strdup(_s)       strcpy(alloca(strlen(_s)+1), (_s))
817
818 /*@-mods@*/
819 static int ftpNLST(const char * url, ftpSysCall_t ftpSysCall,
820                 /*@out@*/ /*@null@*/ struct stat * st,
821                 /*@out@*/ /*@null@*/ char * rlbuf, size_t rlbufsiz)
822         /*@globals fileSystem @*/
823         /*@modifies *st, *rlbuf, fileSystem @*/
824 {
825     FD_t fd;
826     const char * path;
827     int bufLength, moretodo;
828     const char *n, *ne, *o, *oe;
829     char * s;
830     char * se;
831     const char * urldn;
832     char * bn = NULL;
833     int nbn = 0;
834     urlinfo u;
835     int rc;
836
837     n = ne = o = oe = NULL;
838     (void) urlPath(url, &path);
839     if (*path == '\0')
840         return -2;
841
842     switch (ftpSysCall) {
843     case DO_FTP_GLOB:
844         fd = ftpOpen(url, 0, 0, &u);
845         if (fd == NULL || u == NULL)
846             return -1;
847
848         u->openError = ftpReq(fd, "LIST", path);
849         break;
850     default:
851         urldn = alloca_strdup(url);
852         /*@-branchstate@*/
853         if ((bn = strrchr(urldn, '/')) == NULL)
854             return -2;
855         else if (bn == path)
856             bn = ".";
857         else
858             *bn++ = '\0';
859         /*@=branchstate@*/
860         nbn = strlen(bn);
861
862         rc = ftpChdir(urldn);           /* XXX don't care about CWD */
863         if (rc < 0)
864             return rc;
865
866         fd = ftpOpen(url, 0, 0, &u);
867         if (fd == NULL || u == NULL)
868             return -1;
869
870         /* XXX possibly should do "NLST -lais" to get st_ino/st_blocks also */
871         u->openError = ftpReq(fd, "NLST", "-la");
872
873         if (bn == NULL || nbn <= 0) {
874             rc = -2;
875             goto exit;
876         }
877         break;
878     }
879
880     if (u->openError < 0) {
881         fd = fdLink(fd, "error data (ftpStat)");
882         rc = -2;
883         goto exit;
884     }
885
886     if (ftpBufAlloced == 0 || ftpBuf == NULL) {
887         ftpBufAlloced = _url_iobuf_size;
888         ftpBuf = xcalloc(ftpBufAlloced, sizeof(ftpBuf[0]));
889     }
890     *ftpBuf = '\0';
891
892     bufLength = 0;
893     moretodo = 1;
894
895     do {
896
897         /* XXX FIXME: realloc ftpBuf if < ~128 chars remain */
898         if ((ftpBufAlloced - bufLength) < (1024+80)) {
899             ftpBufAlloced <<= 2;
900             ftpBuf = xrealloc(ftpBuf, ftpBufAlloced);
901         }
902         s = se = ftpBuf + bufLength;
903         *se = '\0';
904
905         rc = fdFgets(fd, se, (ftpBufAlloced - bufLength));
906         if (rc <= 0) {
907             moretodo = 0;
908             break;
909         }
910         if (ftpSysCall == DO_FTP_GLOB) {        /* XXX HACK */
911             bufLength += strlen(se);
912             continue;
913         }
914
915         for (s = se; *s != '\0'; s = se) {
916             int bingo;
917
918             while (*se && *se != '\n') se++;
919             if (se > s && se[-1] == '\r') se[-1] = '\0';
920             if (*se == '\0') 
921                 /*@innerbreak@*/ break;
922             *se++ = '\0';
923
924             if (!strncmp(s, "total ", sizeof("total ")-1))
925                 /*@innercontinue@*/ continue;
926
927             o = NULL;
928             for (bingo = 0, n = se; n >= s; n--) {
929                 switch (*n) {
930                 case '\0':
931                     oe = ne = n;
932                     /*@switchbreak@*/ break;
933                 case ' ':
934                     if (o || !(n[-3] == ' ' && n[-2] == '-' && n[-1] == '>')) {
935                         while (*(++n) == ' ')
936                             {};
937                         bingo++;
938                         /*@switchbreak@*/ break;
939                     }
940                     for (o = n + 1; *o == ' '; o++)
941                         {};
942                     n -= 3;
943                     ne = n;
944                     /*@switchbreak@*/ break;
945                 default:
946                     /*@switchbreak@*/ break;
947                 }
948                 if (bingo)
949                     /*@innerbreak@*/ break;
950             }
951
952             if (nbn != (ne - n))        /* Same name length? */
953                 /*@innercontinue@*/ continue;
954             if (strncmp(n, bn, nbn))    /* Same name? */
955                 /*@innercontinue@*/ continue;
956
957             moretodo = 0;
958             /*@innerbreak@*/ break;
959         }
960
961         if (moretodo && se > s) {
962             bufLength = se - s - 1;
963             if (s != ftpBuf)
964                 memmove(ftpBuf, s, bufLength);
965         } else {
966             bufLength = 0;
967         }
968     } while (moretodo);
969
970     switch (ftpSysCall) {
971     case DO_FTP_STAT:
972         if (o && oe) {
973             /* XXX FIXME: symlink, replace urldn/bn from [o,oe) and restart */
974         }
975         /*@fallthrough@*/
976     case DO_FTP_LSTAT:
977         if (st == NULL || !(n && ne)) {
978             rc = -1;
979         } else {
980             rc = ((vfs_parse_ls_lga(s, st, NULL, NULL) > 0) ? 0 : -1);
981         }
982         break;
983     case DO_FTP_READLINK:
984         if (rlbuf == NULL || !(o && oe)) {
985             rc = -1;
986         } else {
987             rc = oe - o;
988             if (rc > rlbufsiz)
989                 rc = rlbufsiz;
990             memcpy(rlbuf, o, rc);
991             if (rc < rlbufsiz)
992                 rlbuf[rc] = '\0';
993         }
994         break;
995     case DO_FTP_ACCESS:
996         rc = 0;         /* XXX WRONG WRONG WRONG */
997         break;
998     case DO_FTP_GLOB:
999         rc = 0;         /* XXX WRONG WRONG WRONG */
1000         break;
1001     }
1002
1003 exit:
1004     (void) ufdClose(fd);
1005     return rc;
1006 }
1007 /*@=mods@*/
1008
1009 static const char * statstr(struct stat * st)
1010 {
1011     static char buf[1024];
1012 sprintf(buf, "*** dev %x ino %x mode %0o nlink %d uid %d gid %d rdev %x size %x\n",
1013 (unsigned)st->st_dev,
1014 (unsigned)st->st_ino,
1015 st->st_mode,
1016 st->st_nlink,
1017 st->st_uid,
1018 st->st_gid,
1019 (unsigned)st->st_rdev,
1020 (unsigned)st->st_size);
1021     return buf;
1022 }
1023
1024 static int ftp_st_ino = 0x1000;
1025
1026 static int ftpStat(const char * path, /*@out@*/ struct stat *st)
1027         /*@globals fileSystem @*/
1028         /*@modifies *st, fileSystem @*/
1029 {
1030     int rc;
1031     rc = ftpNLST(path, DO_FTP_STAT, st, NULL, 0);
1032 if (_ftp_debug)
1033 fprintf(stderr, "*** ftpStat(%s) rc %d\n%s", path, rc, statstr(st));
1034     /* XXX fts(3) needs/uses st_ino, make something up for now. */
1035     if (st->st_ino == 0)
1036         st->st_ino = ftp_st_ino++;
1037     return rc;
1038 }
1039
1040 static int ftpLstat(const char * path, /*@out@*/ struct stat *st)
1041         /*@globals fileSystem @*/
1042         /*@modifies *st, fileSystem @*/
1043 {
1044     int rc;
1045     rc = ftpNLST(path, DO_FTP_LSTAT, st, NULL, 0);
1046 if (_ftp_debug)
1047 fprintf(stderr, "*** ftpLstat(%s) rc %d\n%s\n", path, rc, statstr(st));
1048 st->st_ino = ftp_st_ino++;
1049     /* XXX fts(3) needs/uses st_ino, make something up for now. */
1050     if (st->st_ino == 0)
1051         st->st_ino = ftp_st_ino++;
1052     return rc;
1053 }
1054
1055 static int ftpReadlink(const char * path, /*@out@*/ char * buf, size_t bufsiz)
1056         /*@globals fileSystem @*/
1057         /*@modifies *buf, fileSystem @*/
1058 {
1059     int rc;
1060     rc = ftpNLST(path, DO_FTP_READLINK, NULL, buf, bufsiz);
1061 if (_ftp_debug)
1062 fprintf(stderr, "*** ftpReadlink(%s) rc %d\n", path, rc);
1063     return rc;
1064 }
1065
1066 struct __dirstream {
1067     int fd;                     /* File descriptor.  */
1068     char * data;                /* Directory block.  */
1069     size_t allocation;          /* Space allocated for the block.  */
1070     size_t size;                /* Total valid data in the block.  */
1071     size_t offset;              /* Current offset into the block.  */
1072     off_t filepos;              /* Position of next entry to read.  */
1073     pthread_mutex_t lock;       /* Mutex lock for this structure.  */
1074 };
1075
1076 static int ftpmagicdir = 0x8440291;
1077 #define ISFTPMAGIC(_dir) (!memcmp((_dir), &ftpmagicdir, sizeof(ftpmagicdir)))
1078
1079 static DIR * ftpOpendir(const char * path)
1080 {
1081     DIR * dir;
1082     struct dirent * dp;
1083     size_t nb;
1084     const char * s, * sb, * se;
1085     const char ** av;
1086     unsigned char * dt;
1087     char * t;
1088     int ac;
1089     int c;
1090     int rc;
1091
1092 if (_ftp_debug)
1093 fprintf(stderr, "*** ftpOpendir(%s)\n", path);
1094     rc = ftpNLST(path, DO_FTP_GLOB, NULL, NULL, 0);
1095     if (rc)
1096         return NULL;
1097
1098     /*
1099      * ftpBuf now contains absolute paths, newline terminated.
1100      * Calculate the number of bytes to hold the directory info.
1101      */
1102     nb = sizeof(".") + sizeof("..");
1103     ac = 2;
1104     sb = NULL;
1105     s = se = ftpBuf;
1106     while ((c = *se) != '\0') {
1107         se++;
1108         switch (c) {
1109         case '/':
1110             sb = se;
1111             break;
1112         case '\r':
1113             if (sb == NULL) {
1114                 for (sb = se; sb > s && sb[-1] != ' '; sb--)
1115                     ;
1116             }
1117             ac++;
1118             nb += (se - sb);
1119
1120             if (*se == '\n') se++;
1121             sb = NULL;
1122             s = se;
1123             break;
1124         default:
1125             break;
1126         }
1127     }
1128
1129     nb += sizeof(*dir) + sizeof(*dp) + ((ac + 1) * sizeof(*av)) + (ac + 1);
1130     dir = xcalloc(1, nb);
1131     dp = (struct dirent *) (dir + 1);
1132     av = (const char **) (dp + 1);
1133     dt = (char *) (av + (ac + 1));
1134     t = (char *) (dt + ac + 1);
1135
1136     dir->fd = ftpmagicdir;
1137     dir->data = (char *) dp;
1138     dir->allocation = nb;
1139     dir->size = ac;
1140     dir->offset = -1;
1141     dir->filepos = 0;
1142
1143     ac = 0;
1144     dt[ac] = DT_DIR;    av[ac++] = t;   t = stpcpy(t, ".");     t++;
1145     dt[ac] = DT_DIR;    av[ac++] = t;   t = stpcpy(t, "..");    t++;
1146     sb = NULL;
1147     s = se = ftpBuf;
1148     while ((c = *se) != '\0') {
1149         se++;
1150         switch (c) {
1151         case '/':
1152             sb = se;
1153             break;
1154         case '\r':
1155             av[ac] = t;
1156             if (sb == NULL) {
1157                 switch(*s) {
1158                 case 'p':       dt[ac] = DT_FIFO;       break;
1159                 case 'c':       dt[ac] = DT_CHR;        break;
1160                 case 'd':       dt[ac] = DT_DIR;        break;
1161                 case 'b':       dt[ac] = DT_BLK;        break;
1162                 case '-':       dt[ac] = DT_REG;        break;
1163                 case 'l':       dt[ac] = DT_LNK;        break;
1164                 case 's':       dt[ac] = DT_SOCK;       break;
1165                 default:        dt[ac] = DT_UNKNOWN;    break;
1166                 }
1167                 for (sb = se; sb > s && sb[-1] != ' '; sb--)
1168                     ;
1169             }
1170             ac++;
1171             t = stpncpy(t, sb, (se - sb));
1172             t[-1] = '\0';
1173             if (*se == '\n') se++;
1174             sb = NULL;
1175             s = se;
1176             break;
1177         default:
1178             break;
1179         }
1180     }
1181     av[ac] = NULL;
1182
1183     return dir;
1184 }
1185
1186 static struct dirent * ftpReaddir(DIR * dir)
1187 {
1188     struct dirent * dp;
1189     const char ** av;
1190     unsigned char * dt;
1191     int ac;
1192     int i;
1193
1194     if (dir == NULL || !ISFTPMAGIC(dir) || dir->data == NULL) {
1195         /* XXX TODO: EBADF errno. */
1196         return NULL;
1197     }
1198
1199     dp = (struct dirent *) dir->data;
1200     av = (const char **) (dp + 1);
1201     ac = dir->size;
1202     dt = (char *) (av + (ac + 1));
1203     i = dir->offset + 1;
1204
1205     if (i < 0 || i >= ac || av[i] == NULL)
1206         return NULL;
1207
1208     dir->offset = i;
1209
1210     /* XXX glob(3) uses REAL_DIR_ENTRY(dp) test on d_ino */
1211     dp->d_ino = i + 1;          /* W2DO? */
1212     dp->d_off = 0;              /* W2DO? */
1213     dp->d_reclen = 0;           /* W2DO? */
1214     dp->d_type = dt[i];
1215
1216     strncpy(dp->d_name, av[i], sizeof(dp->d_name));
1217 if (_ftp_debug)
1218 fprintf(stderr, "*** ftpReaddir(%p) %p \"%s\"\n", dir, dp, dp->d_name);
1219     
1220     return dp;
1221 }
1222
1223 static int ftpClosedir(DIR * dir)
1224 {
1225 if (_ftp_debug)
1226 fprintf(stderr, "*** ftpClosedir(%p)\n", dir);
1227     if (dir == NULL || !ISFTPMAGIC(dir)) {
1228         /* XXX TODO: EBADF errno. */
1229         return -1;
1230     }
1231     free((void *)dir);
1232     dir = NULL;
1233     return 0;
1234 }
1235
1236 int Stat(const char * path, struct stat * st)
1237 {
1238     const char * lpath;
1239     int ut = urlPath(path, &lpath);
1240
1241 if (_rpmio_debug)
1242 fprintf(stderr, "*** Stat(%s,%p)\n", path, st);
1243     switch (ut) {
1244     case URL_IS_FTP:
1245         return ftpStat(path, st);
1246         /*@notreached@*/ break;
1247     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
1248     case URL_IS_PATH:
1249         path = lpath;
1250         /*@fallthrough@*/
1251     case URL_IS_UNKNOWN:
1252         break;
1253     case URL_IS_DASH:
1254     default:
1255         return -2;
1256         /*@notreached@*/ break;
1257     }
1258     return stat(path, st);
1259 }
1260
1261 int Lstat(const char * path, struct stat * st)
1262 {
1263     const char * lpath;
1264     int ut = urlPath(path, &lpath);
1265
1266 if (_rpmio_debug)
1267 fprintf(stderr, "*** Lstat(%s,%p)\n", path, st);
1268     switch (ut) {
1269     case URL_IS_FTP:
1270         return ftpLstat(path, st);
1271         /*@notreached@*/ break;
1272     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
1273     case URL_IS_PATH:
1274         path = lpath;
1275         /*@fallthrough@*/
1276     case URL_IS_UNKNOWN:
1277         break;
1278     case URL_IS_DASH:
1279     default:
1280         return -2;
1281         /*@notreached@*/ break;
1282     }
1283     return lstat(path, st);
1284 }
1285
1286 int Readlink(const char * path, char * buf, size_t bufsiz)
1287 {
1288     const char * lpath;
1289     int ut = urlPath(path, &lpath);
1290
1291     switch (ut) {
1292     case URL_IS_FTP:
1293         return ftpReadlink(path, buf, bufsiz);
1294         /*@notreached@*/ break;
1295     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
1296     case URL_IS_PATH:
1297         path = lpath;
1298         /*@fallthrough@*/
1299     case URL_IS_UNKNOWN:
1300         break;
1301     case URL_IS_DASH:
1302     default:
1303         return -2;
1304         /*@notreached@*/ break;
1305     }
1306     return readlink(path, buf, bufsiz);
1307 }
1308
1309 int Access(const char * path, int amode)
1310 {
1311     const char * lpath;
1312     int ut = urlPath(path, &lpath);
1313
1314 if (_rpmio_debug)
1315 fprintf(stderr, "*** Access(%s,%d)\n", path, amode);
1316     switch (ut) {
1317     case URL_IS_FTP:            /* XXX WRONG WRONG WRONG */
1318     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
1319     case URL_IS_PATH:
1320         path = lpath;
1321         /*@fallthrough@*/
1322     case URL_IS_UNKNOWN:
1323         break;
1324     case URL_IS_DASH:
1325     default:
1326         return -2;
1327         /*@notreached@*/ break;
1328     }
1329     return access(path, amode);
1330 }
1331
1332 int Glob(const char *pattern, int flags,
1333         int errfunc(const char * epath, int eerrno), glob_t *pglob)
1334 {
1335     const char * lpath;
1336     int ut = urlPath(pattern, &lpath);
1337
1338 /*@-castfcnptr@*/
1339 if (_rpmio_debug)
1340 fprintf(stderr, "*** Glob(%s,0x%x,%p,%p)\n", pattern, (unsigned)flags, (void *)errfunc, pglob);
1341 /*@=castfcnptr@*/
1342     switch (ut) {
1343     case URL_IS_FTP:
1344         pglob->gl_closedir = Closedir;
1345         pglob->gl_readdir = Readdir;
1346         pglob->gl_opendir = Opendir;
1347         pglob->gl_lstat = Lstat;
1348         pglob->gl_stat = Stat;
1349         flags |= GLOB_ALTDIRFUNC;
1350         break;
1351     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
1352     case URL_IS_PATH:
1353         pattern = lpath;
1354         /*@fallthrough@*/
1355     case URL_IS_UNKNOWN:
1356         break;
1357     case URL_IS_DASH:
1358     default:
1359         return -2;
1360         /*@notreached@*/ break;
1361     }
1362     return glob(pattern, flags, errfunc, pglob);
1363 }
1364
1365 void Globfree(glob_t *pglob)
1366 {
1367 if (_rpmio_debug)
1368 fprintf(stderr, "*** Globfree(%p)\n", pglob);
1369     globfree(pglob);
1370 }
1371
1372 DIR * Opendir(const char * path)
1373 {
1374     const char * lpath;
1375     int ut = urlPath(path, &lpath);
1376
1377 if (_rpmio_debug)
1378 fprintf(stderr, "*** Opendir(%s)\n", path);
1379     switch (ut) {
1380     case URL_IS_FTP:
1381         return ftpOpendir(path);
1382         /*@notreached@*/ break;
1383     case URL_IS_HTTP:           /* XXX WRONG WRONG WRONG */
1384     case URL_IS_PATH:
1385         path = lpath;
1386         /*@fallthrough@*/
1387     case URL_IS_UNKNOWN:
1388         break;
1389     case URL_IS_DASH:
1390     default:
1391         return NULL;
1392         /*@notreached@*/ break;
1393     }
1394     /*@-dependenttrans@*/
1395     return opendir(path);
1396     /*@=dependenttrans@*/
1397 }
1398
1399 /*@+voidabstract@*/
1400 struct dirent * Readdir(DIR * dir)
1401 {
1402 if (_rpmio_debug)
1403 fprintf(stderr, "*** Readdir(%p)\n", (void *)dir);
1404     if (dir == NULL || ISFTPMAGIC(dir))
1405         return ftpReaddir(dir);
1406     return readdir(dir);
1407 }
1408
1409 int Closedir(DIR * dir)
1410 {
1411 if (_rpmio_debug)
1412 fprintf(stderr, "*** Closedir(%p)\n", (void *)dir);
1413     if (dir == NULL || ISFTPMAGIC(dir))
1414         return ftpClosedir(dir);
1415     return closedir(dir);
1416 }
1417 /*@=voidabstract@*/
1418 /*@=type@*/