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