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