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