fix: prevent segfault if malicious server sends 1 GB of data through ftpNLST.
[platform/upstream/rpm.git] / rpmio / rpmrpc.c
index bf69c15..9f3be35 100644 (file)
@@ -1,13 +1,26 @@
+/** \ingroup rpmio
+ * \file rpmio/rpmrpc.c
+ */
+
 #include "system.h"
 
+#if defined(HAVE_PTHREAD_H) && !defined(__LCLINT__)
+#include <pthread.h>
+#endif
+
 #include <rpmio_internal.h>
-#include <popt.h>
 #include "ugid.h"
+#include "debug.h"
 
-extern int _rpmio_debug;
+/*@access DIR@*/
+/*@access FD_t@*/
+/*@access urlinfo@*/
 
 /* =============================================================== */
-static int ftpMkdir(const char * path, /*@unused@*/ mode_t mode) {
+static int ftpMkdir(const char * path, /*@unused@*/ mode_t mode)
+       /*@globals fileSystem, internalState @*/
+       /*@modifies fileSystem, internalState @*/
+{
     int rc;
     if ((rc = ftpCmd("MKD", path, NULL)) != 0)
        return rc;
@@ -20,28 +33,41 @@ static int ftpMkdir(const char * path, /*@unused@*/ mode_t mode) {
     return rc;
 }
 
-static int ftpChdir(const char * path) {
+static int ftpChdir(const char * path)
+       /*@globals fileSystem, internalState @*/
+       /*@modifies fileSystem, internalState @*/
+{
     return ftpCmd("CWD", path, NULL);
 }
 
-static int ftpRmdir(const char * path) {
+static int ftpRmdir(const char * path)
+       /*@globals fileSystem, internalState @*/
+       /*@modifies fileSystem, internalState @*/
+{
     return ftpCmd("RMD", path, NULL);
 }
 
-static int ftpRename(const char * oldpath, const char * newpath) {
+static int ftpRename(const char * oldpath, const char * newpath)
+       /*@globals fileSystem, internalState @*/
+       /*@modifies fileSystem, internalState @*/
+{
     int rc;
     if ((rc = ftpCmd("RNFR", oldpath, NULL)) != 0)
        return rc;
     return ftpCmd("RNTO", newpath, NULL);
 }
 
-static int ftpUnlink(const char * path) {
+static int ftpUnlink(const char * path)
+       /*@globals fileSystem, internalState @*/
+       /*@modifies fileSystem, internalState @*/
+{
     return ftpCmd("DELE", path, NULL);
 }
 
 /* =============================================================== */
 /* XXX rebuilddb.c: analogues to mkdir(2)/rmdir(2). */
-int Mkdir (const char *path, mode_t mode) {
+int Mkdir (const char * path, mode_t mode)
+{
     const char * lpath;
     int ut = urlPath(path, &lpath);
 
@@ -63,7 +89,8 @@ int Mkdir (const char *path, mode_t mode) {
     return mkdir(path, mode);
 }
 
-int Chdir (const char *path) {
+int Chdir (const char * path)
+{
     const char * lpath;
     int ut = urlPath(path, &lpath);
 
@@ -85,7 +112,8 @@ int Chdir (const char *path) {
     return chdir(path);
 }
 
-int Rmdir (const char *path) {
+int Rmdir (const char * path)
+{
     const char * lpath;
     int ut = urlPath(path, &lpath);
 
@@ -109,7 +137,8 @@ int Rmdir (const char *path) {
 
 /* XXX rpmdb.c: analogue to rename(2). */
 
-int Rename (const char *oldpath, const char * newpath) {
+int Rename (const char * oldpath, const char * newpath)
+{
     const char *oe = NULL;
     const char *ne = NULL;
     int oldut, newut;
@@ -136,7 +165,7 @@ int Rename (const char *oldpath, const char * newpath) {
 if (_rpmio_debug)
 fprintf(stderr, "*** rename old %*s new %*s\n", (int)(oe - oldpath), oldpath, (int)(ne - newpath), newpath);
        if (!(oldut == newut && oe && ne && (oe - oldpath) == (ne - newpath) &&
-           !strncasecmp(oldpath, newpath, (oe - oldpath))))
+           !xstrncasecmp(oldpath, newpath, (oe - oldpath))))
            return -2;
        return ftpRename(oldpath, newpath);
        /*@notreached@*/ break;
@@ -155,7 +184,8 @@ fprintf(stderr, "*** rename old %*s new %*s\n", (int)(oe - oldpath), oldpath, (i
     return rename(oldpath, newpath);
 }
 
-int Link (const char *oldpath, const char * newpath) {
+int Link (const char * oldpath, const char * newpath)
+{
     const char *oe = NULL;
     const char *ne = NULL;
     int oldut, newut;
@@ -181,7 +211,7 @@ int Link (const char *oldpath, const char * newpath) {
 if (_rpmio_debug)
 fprintf(stderr, "*** link old %*s new %*s\n", (int)(oe - oldpath), oldpath, (int)(ne - newpath), newpath);
        if (!(oldut == newut && oe && ne && (oe - oldpath) == (ne - newpath) &&
-           !strncasecmp(oldpath, newpath, (oe - oldpath))))
+           !xstrncasecmp(oldpath, newpath, (oe - oldpath))))
            return -2;
        oldpath = oe;
        newpath = ne;
@@ -223,23 +253,31 @@ int Unlink(const char * path) {
 /* XXX swiped from mc-4.5.39-pre9 vfs/ftpfs.c */
 
 #define        g_strdup        xstrdup
-#define        g_free          xfree
+#define        g_free          free
 
 /*
  * FIXME: this is broken. It depends on mc not crossing border on month!
  */
+/*@unchecked@*/
 static int current_mday;
+/*@unchecked@*/
 static int current_mon;
+/*@unchecked@*/
 static int current_year;
 
 /* Following stuff (parse_ls_lga) is used by ftpfs and extfs */
 #define MAXCOLS                30
 
+/*@unchecked@*/
 static char *columns [MAXCOLS];        /* Points to the string in column n */
+/*@unchecked@*/
 static int   column_ptr [MAXCOLS]; /* Index from 0 to the starting positions of the columns */
 
+/*@-boundswrite@*/
 static int
 vfs_split_text (char *p)
+       /*@globals columns, column_ptr @*/
+       /*@modifies *p, columns, column_ptr @*/
 {
     char *original = p;
     int  numcols;
@@ -257,92 +295,108 @@ vfs_split_text (char *p)
     }
     return numcols;
 }
+/*@=boundswrite@*/
 
+/*@-boundsread@*/
 static int
 is_num (int idx)
+       /*@*/
 {
     if (!columns [idx] || columns [idx][0] < '0' || columns [idx][0] > '9')
        return 0;
     return 1;
 }
+/*@=boundsread@*/
 
+/*@-boundsread@*/
 static int
-is_dos_date(char *str)
+is_dos_date(/*@null@*/ const char *str)
+       /*@*/
 {
-    if (strlen(str) == 8 && str[2] == str[5] && strchr("\\-/", (int)str[2]) != NULL)
-       return (1);
-
-    return (0);
+    if (str != NULL && strlen(str) == 8 &&
+               str[2] == str[5] && strchr("\\-/", (int)str[2]) != NULL)
+       return 1;
+    return 0;
 }
+/*@=boundsread@*/
 
 static int
-is_week (char *str, struct tm *tim)
+is_week (/*@null@*/ const char * str, /*@out@*/ struct tm * tim)
+       /*@modifies *tim @*/
 {
-    static char *week = "SunMonTueWedThuFriSat";
-    char *pos;
+/*@observer@*/ static const char * week = "SunMonTueWedThuFriSat";
+    const char * pos;
 
-    if((pos=strstr(week, str)) != NULL){
-        if(tim != NULL)
+    /*@-observertrans -mayaliasunique@*/
+    if (str != NULL && (pos=strstr(week, str)) != NULL) {
+    /*@=observertrans =mayaliasunique@*/
+        if (tim != NULL)
            tim->tm_wday = (pos - week)/3;
-       return (1);
+       return 1;
     }
-    return (0);    
+    return 0;    
 }
 
 static int
-is_month (char *str, struct tm *tim)
+is_month (/*@null@*/ const char * str, /*@out@*/ struct tm * tim)
+       /*@modifies *tim @*/
 {
-    static char *month = "JanFebMarAprMayJunJulAugSepOctNovDec";
-    char *pos;
+/*@observer@*/ static const char * month = "JanFebMarAprMayJunJulAugSepOctNovDec";
+    const char * pos;
     
-    if((pos=strstr(month, str)) != NULL){
-        if(tim != NULL)
+    /*@-observertrans -mayaliasunique@*/
+    if (str != NULL && (pos = strstr(month, str)) != NULL) {
+    /*@=observertrans -mayaliasunique@*/
+        if (tim != NULL)
            tim->tm_mon = (pos - month)/3;
-       return (1);
+       return 1;
     }
-    return (0);
+    return 0;
 }
 
 static int
-is_time (char *str, struct tm *tim)
+is_time (/*@null@*/ const char * str, /*@out@*/ struct tm * tim)
+       /*@modifies *tim @*/
 {
-    char *p, *p2;
+    const char * p, * p2;
 
-    if ((p=strchr(str, ':')) && (p2=strrchr(str, ':'))) {
+    if (str != NULL && (p = strchr(str, ':')) && (p2 = strrchr(str, ':'))) {
        if (p != p2) {
            if (sscanf (str, "%2d:%2d:%2d", &tim->tm_hour, &tim->tm_min, &tim->tm_sec) != 3)
-               return (0);
-       }
-       else {
+               return 0;
+       } else {
            if (sscanf (str, "%2d:%2d", &tim->tm_hour, &tim->tm_min) != 2)
-               return (0);
+               return 0;
        }
-    }
-    else 
-        return (0);
+    } else 
+        return 0;
     
-    return (1);
+    return 1;
 }
 
-static int is_year(char *str, struct tm *tim)
+static int is_year(/*@null@*/ const char * str, /*@out@*/ struct tm * tim)
+       /*@modifies *tim @*/
 {
     long year;
 
+    if (str == NULL)
+       return 0;
+
     if (strchr(str,':'))
-        return (0);
+        return 0;
 
-    if (strlen(str)!=4)
-        return (0);
+    if (strlen(str) != 4)
+        return 0;
 
     if (sscanf(str, "%ld", &year) != 1)
-        return (0);
+        return 0;
 
     if (year < 1900 || year > 3000)
-        return (0);
+        return 0;
 
     tim->tm_year = (int) (year - 1900);
 
-    return (1);
+    return 1;
 }
 
 /*
@@ -353,8 +407,9 @@ static int is_year(char *str, struct tm *tim)
 
 static int
 vfs_parse_filetype (char c)
+       /*@*/
 {
-    switch (c){
+    switch (c) {
         case 'd': return S_IFDIR; 
         case 'b': return S_IFBLK;
         case 'c': return S_IFCHR;
@@ -370,37 +425,38 @@ vfs_parse_filetype (char c)
     }
 }
 
-static int vfs_parse_filemode (char *p)
+static int vfs_parse_filemode (const char *p)
+       /*@*/
 {      /* converts rw-rw-rw- into 0666 */
     int res = 0;
-    switch (*(p++)){
+    switch (*(p++)) {
        case 'r': res |= 0400; break;
        case '-': break;
        default: return -1;
     }
-    switch (*(p++)){
+    switch (*(p++)) {
        case 'w': res |= 0200; break;
        case '-': break;
        default: return -1;
     }
-    switch (*(p++)){
+    switch (*(p++)) {
        case 'x': res |= 0100; break;
        case 's': res |= 0100 | S_ISUID; break;
        case 'S': res |= S_ISUID; break;
        case '-': break;
        default: return -1;
     }
-    switch (*(p++)){
+    switch (*(p++)) {
        case 'r': res |= 0040; break;
        case '-': break;
        default: return -1;
     }
-    switch (*(p++)){
+    switch (*(p++)) {
        case 'w': res |= 0020; break;
        case '-': break;
        default: return -1;
     }
-    switch (*(p++)){
+    switch (*(p++)) {
        case 'x': res |= 0010; break;
        case 's': res |= 0010 | S_ISGID; break;
         case 'l': /* Solaris produces these */
@@ -408,17 +464,17 @@ static int vfs_parse_filemode (char *p)
        case '-': break;
        default: return -1;
     }
-    switch (*(p++)){
+    switch (*(p++)) {
        case 'r': res |= 0004; break;
        case '-': break;
        default: return -1;
     }
-    switch (*(p++)){
+    switch (*(p++)) {
        case 'w': res |= 0002; break;
        case '-': break;
        default: return -1;
     }
-    switch (*(p++)){
+    switch (*(p++)) {
        case 'x': res |= 0001; break;
        case 't': res |= 0001 | S_ISVTX; break;
        case 'T': res |= S_ISVTX; break;
@@ -428,7 +484,9 @@ static int vfs_parse_filemode (char *p)
     return res;
 }
 
-static int vfs_parse_filedate(int idx, time_t *t)
+/*@-boundswrite@*/
+static int vfs_parse_filedate(int idx, /*@out@*/ time_t *t)
+       /*@modifies *t @*/
 {      /* This thing parses from idx in columns[] array */
 
     char *p;
@@ -473,9 +531,12 @@ static int vfs_parse_filedate(int idx, time_t *t)
 
        /* Here just this special case with MM-DD-YY */
         if (is_dos_date(p)){
+           /*@-mods@*/
             p[2] = p[5] = '-';
+           /*@=mods@*/
            
-           if(sscanf(p, "%2d-%2d-%2d", &d[0], &d[1], &d[2]) == 3){
+           memset(d, 0, sizeof(d));
+           if (sscanf(p, "%2d-%2d-%2d", &d[0], &d[1], &d[2]) == 3){
            /*  We expect to get:
                1. MM-DD-YY
                2. DD-MM-YY
@@ -531,9 +592,14 @@ static int vfs_parse_filedate(int idx, time_t *t)
         *t = 0;
     return idx;
 }
+/*@=boundswrite@*/
 
+/*@-boundswrite@*/
 static int
-vfs_parse_ls_lga (char *p, struct stat *s, char **filename, char **linkname)
+vfs_parse_ls_lga (char * p, /*@out@*/ struct stat * st,
+               /*@out@*/ const char ** filename,
+               /*@out@*/ const char ** linkname)
+       /*@modifies *p, *st, *filename, *linkname @*/
 {
     int idx, idx2, num_cols;
     int i;
@@ -549,22 +615,24 @@ vfs_parse_ls_lga (char *p, struct stat *s, char **filename, char **linkname)
     if ((i = vfs_parse_filetype(*(p++))) == -1)
         goto error;
 
-    s->st_mode = i;
+    st->st_mode = i;
     if (*p == ' ')     /* Notwell 4 */
         p++;
     if (*p == '['){
        if (strlen (p) <= 8 || p [8] != ']')
            goto error;
        /* Should parse here the Notwell permissions :) */
-       if (S_ISDIR (s->st_mode))
-           s->st_mode |= (S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR | S_IXUSR | S_IXGRP | S_IXOTH);
+       /*@-unrecog@*/
+       if (S_ISDIR (st->st_mode))
+           st->st_mode |= (S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR | S_IXUSR | S_IXGRP | S_IXOTH);
        else
-           s->st_mode |= (S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR);
+           st->st_mode |= (S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR);
        p += 9;
+       /*@=unrecog@*/
     } else {
        if ((i = vfs_parse_filemode(p)) == -1)
            goto error;
-        s->st_mode |= i;
+        st->st_mode |= i;
        p += 9;
 
         /* This is for an extra ACL attribute (HP-UX) */
@@ -576,45 +644,45 @@ vfs_parse_ls_lga (char *p, struct stat *s, char **filename, char **linkname)
     p_copy = g_strdup(p);
     num_cols = vfs_split_text (p);
 
-    s->st_nlink = atol (columns [0]);
-    if (s->st_nlink < 0)
+    st->st_nlink = atol (columns [0]);
+    if (st->st_nlink < 0)
         goto error;
 
     if (!is_num (1))
 #ifdef HACK
-       s->st_uid = finduid (columns [1]);
+       st->st_uid = finduid (columns [1]);
 #else
-       unameToUid (columns [1], &s->st_uid);
+       (void) unameToUid (columns [1], &st->st_uid);
 #endif
     else
-        s->st_uid = (uid_t) atol (columns [1]);
+        st->st_uid = (uid_t) atol (columns [1]);
 
     /* Mhm, the ls -lg did not produce a group field */
     for (idx = 3; idx <= 5; idx++) 
         if (is_month(columns [idx], NULL) || is_week(columns [idx], NULL) || is_dos_date(columns[idx]))
             break;
 
-    if (idx == 6 || (idx == 5 && !S_ISCHR (s->st_mode) && !S_ISBLK (s->st_mode)))
+    if (idx == 6 || (idx == 5 && !S_ISCHR (st->st_mode) && !S_ISBLK (st->st_mode)))
        goto error;
 
     /* We don't have gid */    
-    if (idx == 3 || (idx == 4 && (S_ISCHR(s->st_mode) || S_ISBLK (s->st_mode))))
+    if (idx == 3 || (idx == 4 && (S_ISCHR(st->st_mode) || S_ISBLK (st->st_mode))))
         idx2 = 2;
     else { 
        /* We have gid field */
        if (is_num (2))
-           s->st_gid = (gid_t) atol (columns [2]);
+           st->st_gid = (gid_t) atol (columns [2]);
        else
 #ifdef HACK
-           s->st_gid = findgid (columns [2]);
+           st->st_gid = findgid (columns [2]);
 #else
-           gnameToGid (columns [1], &s->st_gid);
+           (void) gnameToGid (columns [1], &st->st_gid);
 #endif
        idx2 = 3;
     }
 
     /* This is device */
-    if (S_ISCHR (s->st_mode) || S_ISBLK (s->st_mode)){
+    if (S_ISCHR (st->st_mode) || S_ISBLK (st->st_mode)){
        int maj, min;
        
        if (!is_num (idx2) || sscanf(columns [idx2], " %d,", &maj) != 1)
@@ -624,33 +692,33 @@ vfs_parse_ls_lga (char *p, struct stat *s, char **filename, char **linkname)
            goto error;
        
 #ifdef HAVE_ST_RDEV
-       s->st_rdev = ((maj & 0xff) << 8) | (min & 0xffff00ff);
+       st->st_rdev = ((maj & 0xff) << 8) | (min & 0xffff00ff);
 #endif
-       s->st_size = 0;
+       st->st_size = 0;
        
     } else {
        /* Common file size */
        if (!is_num (idx2))
            goto error;
        
-       s->st_size = (size_t) atol (columns [idx2]);
+       st->st_size = (size_t) atol (columns [idx2]);
 #ifdef HAVE_ST_RDEV
-       s->st_rdev = 0;
+       st->st_rdev = 0;
 #endif
     }
 
-    idx = vfs_parse_filedate(idx, &s->st_mtime);
+    idx = vfs_parse_filedate(idx, &st->st_mtime);
     if (!idx)
         goto error;
     /* Use resulting time value */
-    s->st_atime = s->st_ctime = s->st_mtime;
-    s->st_dev = 0;
-    s->st_ino = 0;
+    st->st_atime = st->st_ctime = st->st_mtime;
+    st->st_dev = 0;
+    st->st_ino = 0;
 #ifdef HAVE_ST_BLKSIZE
-    s->st_blksize = 512;
+    st->st_blksize = 512;
 #endif
 #ifdef HAVE_ST_BLOCKS
-    s->st_blocks = (s->st_size + 511) / 512;
+    st->st_blocks = (st->st_size + 511) / 512;
 #endif
 
     for (i = idx + 1, idx2 = 0; i < num_cols; i++ ) 
@@ -659,31 +727,31 @@ vfs_parse_ls_lga (char *p, struct stat *s, char **filename, char **linkname)
            break;
        }
     
-    if (((S_ISLNK (s->st_mode) || 
-        (num_cols == idx + 3 && s->st_nlink > 1))) /* Maybe a hardlink? (in extfs) */
+    if (((S_ISLNK (st->st_mode) || 
+        (num_cols == idx + 3 && st->st_nlink > 1))) /* Maybe a hardlink? (in extfs) */
         && idx2){
-       int p;
-       char *s;
+       int tlen;
+       char *t;
            
        if (filename){
 #ifdef HACK
-           s = g_strndup (p_copy + column_ptr [idx], column_ptr [idx2] - column_ptr [idx] - 1);
+           t = g_strndup (p_copy + column_ptr [idx], column_ptr [idx2] - column_ptr [idx] - 1);
 #else
            int nb = column_ptr [idx2] - column_ptr [idx] - 1;
-           s = xmalloc(nb+1);
-           strncpy(s, p_copy + column_ptr [idx], nb);
+           t = xmalloc(nb+1);
+           strncpy(t, p_copy + column_ptr [idx], nb);
 #endif
-           *filename = s;
+           *filename = t;
        }
        if (linkname){
-           s = g_strdup (p_copy + column_ptr [idx2+1]);
-           p = strlen (s);
-           if (s [p-1] == '\r' || s [p-1] == '\n')
-               s [p-1] = 0;
-           if (s [p-2] == '\r' || s [p-2] == '\n')
-               s [p-2] = 0;
+           t = g_strdup (p_copy + column_ptr [idx2+1]);
+           tlen = strlen (t);
+           if (t [tlen-1] == '\r' || t [tlen-1] == '\n')
+               t [tlen-1] = 0;
+           if (t [tlen-2] == '\r' || t [tlen-2] == '\n')
+               t [tlen-2] = 0;
                
-           *linkname = s;
+           *linkname = t;
        }
     } else {
        /* Extract the filename from the string copy, not from the columns
@@ -693,18 +761,18 @@ vfs_parse_ls_lga (char *p, struct stat *s, char **filename, char **linkname)
            /* 
            *filename = g_strdup (columns [idx++]);
            */
-           int p;
-           char *s;
+           int tlen;
+           char *t;
            
-           s = g_strdup (p_copy + column_ptr [idx++]);
-           p = strlen (s);
+           t = g_strdup (p_copy + column_ptr [idx]); idx++;
+           tlen = strlen (t);
            /* g_strchomp(); */
-           if (s [p-1] == '\r' || s [p-1] == '\n')
-               s [p-1] = 0;
-           if (s [p-2] == '\r' || s [p-2] == '\n')
-               s [p-2] = 0;
+           if (t [tlen-1] == '\r' || t [tlen-1] == '\n')
+               t [tlen-1] = 0;
+           if (t [tlen-2] == '\r' || t [tlen-2] == '\n')
+               t [tlen-2] = 0;
            
-           *filename = s;
+           *filename = t;
        }
        if (linkname)
            *linkname = NULL;
@@ -724,10 +792,13 @@ error:
     }
 #endif
 
+    /*@-usereleased@*/
     if (p_copy != p)           /* Carefull! */
+    /*@=usereleased@*/
        g_free (p_copy);
     return 0;
 }
+/*@=boundswrite@*/
 
 typedef enum {
        DO_FTP_STAT     = 1,
@@ -736,13 +807,26 @@ typedef enum {
        DO_FTP_ACCESS   = 4,
        DO_FTP_GLOB     = 5
 } ftpSysCall_t;
+
+/**
+ */
+/*@unchecked@*/
 static size_t ftpBufAlloced = 0;
-static char * ftpBuf = NULL;
+
+/**
+ */
+/*@unchecked@*/
+static /*@only@*/ char * ftpBuf = NULL;
        
 #define alloca_strdup(_s)       strcpy(alloca(strlen(_s)+1), (_s))
 
+/*@-boundswrite@*/
+/*@-mods@*/
 static int ftpNLST(const char * url, ftpSysCall_t ftpSysCall,
-       struct stat * st, char * rlbuf, size_t rlbufsiz)
+               /*@out@*/ /*@null@*/ struct stat * st,
+               /*@out@*/ /*@null@*/ char * rlbuf, size_t rlbufsiz)
+       /*@globals fileSystem, internalState @*/
+       /*@modifies *st, *rlbuf, fileSystem, internalState @*/
 {
     FD_t fd;
     const char * path;
@@ -767,16 +851,18 @@ static int ftpNLST(const char * url, ftpSysCall_t ftpSysCall,
        if (fd == NULL || u == NULL)
            return -1;
 
-       u->openError = ftpReq(fd, "NLST", path);
+       u->openError = ftpReq(fd, "LIST", path);
        break;
     default:
        urldn = alloca_strdup(url);
+       /*@-branchstate@*/
        if ((bn = strrchr(urldn, '/')) == NULL)
            return -2;
        else if (bn == path)
            bn = ".";
        else
            *bn++ = '\0';
+       /*@=branchstate@*/
        nbn = strlen(bn);
 
        rc = ftpChdir(urldn);           /* XXX don't care about CWD */
@@ -789,6 +875,11 @@ static int ftpNLST(const char * url, ftpSysCall_t ftpSysCall,
 
        /* XXX possibly should do "NLST -lais" to get st_ino/st_blocks also */
        u->openError = ftpReq(fd, "NLST", "-la");
+
+       if (bn == NULL || nbn <= 0) {
+           rc = -2;
+           goto exit;
+       }
        break;
     }
 
@@ -799,7 +890,7 @@ static int ftpNLST(const char * url, ftpSysCall_t ftpSysCall,
     }
 
     if (ftpBufAlloced == 0 || ftpBuf == NULL) {
-        ftpBufAlloced = url_iobuf_size;
+        ftpBufAlloced = _url_iobuf_size;
         ftpBuf = xcalloc(ftpBufAlloced, sizeof(ftpBuf[0]));
     }
     *ftpBuf = '\0';
@@ -809,9 +900,10 @@ static int ftpNLST(const char * url, ftpSysCall_t ftpSysCall,
 
     do {
 
-       /* XXX FIXME: realloc ftpBuf is < ~128 chars remain */
+       /* XXX FIXME: realloc ftpBuf if < ~128 chars remain */
        if ((ftpBufAlloced - bufLength) < (1024+80)) {
            ftpBufAlloced <<= 2;
+           assert(ftpBufAlloced < (8*1024*1024));
            ftpBuf = xrealloc(ftpBuf, ftpBufAlloced);
        }
        s = se = ftpBuf + bufLength;
@@ -832,38 +924,45 @@ static int ftpNLST(const char * url, ftpSysCall_t ftpSysCall,
 
            while (*se && *se != '\n') se++;
            if (se > s && se[-1] == '\r') se[-1] = '\0';
-           if (*se == '\0') break;
+           if (*se == '\0') 
+               /*@innerbreak@*/ break;
            *se++ = '\0';
 
-           if (!strncmp(s, "total ", sizeof("total ")-1)) continue;
+           if (!strncmp(s, "total ", sizeof("total ")-1))
+               /*@innercontinue@*/ continue;
 
            o = NULL;
            for (bingo = 0, n = se; n >= s; n--) {
                switch (*n) {
                case '\0':
                    oe = ne = n;
-                   break;
+                   /*@switchbreak@*/ break;
                case ' ':
                    if (o || !(n[-3] == ' ' && n[-2] == '-' && n[-1] == '>')) {
-                       while (*(++n) == ' ');
+                       while (*(++n) == ' ')
+                           {};
                        bingo++;
-                       break;
+                       /*@switchbreak@*/ break;
                    }
-                   for (o = n + 1; *o == ' '; o++);
+                   for (o = n + 1; *o == ' '; o++)
+                       {};
                    n -= 3;
                    ne = n;
-                   break;
+                   /*@switchbreak@*/ break;
                default:
-                   break;
+                   /*@switchbreak@*/ break;
                }
-               if (bingo) break;
+               if (bingo)
+                   /*@innerbreak@*/ break;
            }
 
-           if (nbn != (ne - n))        continue;       /* Same name length? */
-           if (strncmp(n, bn, nbn))    continue;       /* Same name? */
+           if (nbn != (ne - n))        /* Same name length? */
+               /*@innercontinue@*/ continue;
+           if (strncmp(n, bn, nbn))    /* Same name? */
+               /*@innercontinue@*/ continue;
 
            moretodo = 0;
-           break;
+           /*@innerbreak@*/ break;
        }
 
         if (moretodo && se > s) {
@@ -909,52 +1008,323 @@ static int ftpNLST(const char * url, ftpSysCall_t ftpSysCall,
     }
 
 exit:
-    ufdClose(fd);
+    (void) ufdClose(fd);
     return rc;
 }
+/*@=mods@*/
+/*@=boundswrite@*/
+
+static const char * statstr(const struct stat * st,
+               /*@returned@*/ /*@out@*/ char * buf)
+       /*@modifies *buf @*/
+{
+    sprintf(buf,
+       "*** dev %x ino %x mode %0o nlink %d uid %d gid %d rdev %x size %x\n",
+       (unsigned)st->st_dev,
+       (unsigned)st->st_ino,
+       st->st_mode,
+       (unsigned)st->st_nlink,
+       st->st_uid,
+       st->st_gid,
+       (unsigned)st->st_rdev,
+       (unsigned)st->st_size);
+    return buf;
+}
 
-static int ftpStat(const char * path, struct stat *st)
+/*@unchecked@*/
+static int ftp_st_ino = 0xdead0000;
+
+static int ftpStat(const char * path, /*@out@*/ struct stat *st)
+       /*@globals fileSystem, internalState @*/
+       /*@modifies *st, fileSystem, internalState @*/
 {
-    return ftpNLST(path, DO_FTP_STAT, st, NULL, 0);
+    char buf[1024];
+    int rc;
+    rc = ftpNLST(path, DO_FTP_STAT, st, NULL, 0);
+    /* XXX fts(3) needs/uses st_ino, make something up for now. */
+    /*@-mods@*/
+    if (st->st_ino == 0)
+       st->st_ino = ftp_st_ino++;
+    /*@=mods@*/
+if (_ftp_debug)
+fprintf(stderr, "*** ftpStat(%s) rc %d\n%s", path, rc, statstr(st, buf));
+    return rc;
 }
 
-static int ftpLstat(const char * path, struct stat *st) {
+static int ftpLstat(const char * path, /*@out@*/ struct stat *st)
+       /*@globals fileSystem, internalState @*/
+       /*@modifies *st, fileSystem, internalState @*/
+{
+    char buf[1024];
     int rc;
     rc = ftpNLST(path, DO_FTP_LSTAT, st, NULL, 0);
-if (_rpmio_debug)
-fprintf(stderr, "*** ftpLstat(%s) rc %d\n", path, rc);
+    /* XXX fts(3) needs/uses st_ino, make something up for now. */
+    /*@-mods@*/
+    if (st->st_ino == 0)
+       st->st_ino = ftp_st_ino++;
+    /*@=mods@*/
+if (_ftp_debug)
+fprintf(stderr, "*** ftpLstat(%s) rc %d\n%s\n", path, rc, statstr(st, buf));
     return rc;
 }
 
-static int ftpReadlink(const char * path, char * buf, size_t bufsiz) {
-    return ftpNLST(path, DO_FTP_READLINK, NULL, buf, bufsiz);
+static int ftpReadlink(const char * path, /*@out@*/ char * buf, size_t bufsiz)
+       /*@globals fileSystem, internalState @*/
+       /*@modifies *buf, fileSystem, internalState @*/
+{
+    int rc;
+    rc = ftpNLST(path, DO_FTP_READLINK, NULL, buf, bufsiz);
+if (_ftp_debug)
+fprintf(stderr, "*** ftpReadlink(%s) rc %d\n", path, rc);
+    return rc;
 }
 
-static int ftpGlob(const char * path, int flags,
-               int errfunc(const char * epath, int eerno), glob_t * pglob)
+struct __dirstream {
+    int fd;                    /* File descriptor.  */
+    char * data;               /* Directory block.  */
+    size_t allocation;         /* Space allocated for the block.  */
+    size_t size;               /* Total valid data in the block.  */
+    size_t offset;             /* Current offset into the block.  */
+    off_t filepos;             /* Position of next entry to read.  */
+#if defined(HAVE_PTHREAD_H) && !defined(__LCLINT__)
+    pthread_mutex_t lock;      /* Mutex lock for this structure.  */
+#endif
+};
+
+#if !defined(DT_DIR)
+# define DT_UNKNOWN    0
+# define DT_FIFO       1
+# define DT_CHR                2
+# define DT_DIR                4
+# define DT_BLK                6
+# define DT_REG                8
+# define DT_LNK                10
+# define DT_SOCK       12
+# define DT_WHT                14
+typedef struct __dirstream *   FTPDIR;
+#else
+typedef DIR *                  FTPDIR;
+#endif
+
+/*@unchecked@*/
+static int ftpmagicdir = 0x8440291;
+#define        ISFTPMAGIC(_dir) (!memcmp((_dir), &ftpmagicdir, sizeof(ftpmagicdir)))
+
+/*@-boundswrite@*/
+/*@-type@*/ /* FIX: abstract DIR */
+/*@null@*/
+static DIR * ftpOpendir(const char * path)
+       /*@globals fileSystem, internalState @*/
+       /*@modifies fileSystem, internalState @*/
 {
+    FTPDIR mydir;
+    struct dirent * dp;
+    size_t nb;
+    const char * s, * sb, * se;
+    const char ** av;
+    unsigned char * dt;
+    char * t;
+    int ac;
+    int c;
     int rc;
 
-    if (pglob == NULL)
-       return -2;
+if (_ftp_debug)
+fprintf(stderr, "*** ftpOpendir(%s)\n", path);
     rc = ftpNLST(path, DO_FTP_GLOB, NULL, NULL, 0);
-if (_rpmio_debug)
-fprintf(stderr, "*** ftpGlob(%s,0x%x,%p,%p) ftpNLST rc %d\n", path, flags, errfunc, pglob, rc);
     if (rc)
-       return rc;
-    rc = poptParseArgvString(ftpBuf, &pglob->gl_pathc, (const char ***)&pglob->gl_pathv);
-    pglob->gl_offs = -1;       /* XXX HACK HACK HACK */
-    return rc;
+       return NULL;
+
+    /*
+     * ftpBuf now contains absolute paths, newline terminated.
+     * Calculate the number of bytes to hold the directory info.
+     */
+    nb = sizeof(".") + sizeof("..");
+    ac = 2;
+    sb = NULL;
+    s = se = ftpBuf;
+    while ((c = *se) != '\0') {
+       se++;
+       switch (c) {
+       case '/':
+           sb = se;
+           /*@switchbreak@*/ break;
+       case '\r':
+           if (sb == NULL) {
+               for (sb = se; sb > s && sb[-1] != ' '; sb--)
+                   {};
+           }
+           ac++;
+           nb += (se - sb);
+
+           if (*se == '\n') se++;
+           sb = NULL;
+           s = se;
+           /*@switchbreak@*/ break;
+       default:
+           /*@switchbreak@*/ break;
+       }
+    }
+
+    nb += sizeof(*mydir) + sizeof(*dp) + ((ac + 1) * sizeof(*av)) + (ac + 1);
+    mydir = xcalloc(1, nb);
+    /*@-abstract@*/
+    dp = (struct dirent *) (mydir + 1);
+    av = (const char **) (dp + 1);
+    dt = (char *) (av + (ac + 1));
+    t = (char *) (dt + ac + 1);
+    /*@=abstract@*/
+
+    mydir->fd = ftpmagicdir;
+/*@-usereleased@*/
+    mydir->data = (char *) dp;
+/*@=usereleased@*/
+    mydir->allocation = nb;
+    mydir->size = ac;
+    mydir->offset = -1;
+    mydir->filepos = 0;
+
+    ac = 0;
+    /*@-dependenttrans -unrecog@*/
+    dt[ac] = DT_DIR;   av[ac++] = t;   t = stpcpy(t, ".");     t++;
+    dt[ac] = DT_DIR;   av[ac++] = t;   t = stpcpy(t, "..");    t++;
+    /*@=dependenttrans =unrecog@*/
+    sb = NULL;
+    s = se = ftpBuf;
+    while ((c = *se) != '\0') {
+       se++;
+       switch (c) {
+       case '/':
+           sb = se;
+           /*@switchbreak@*/ break;
+       case '\r':
+           /*@-dependenttrans@*/
+           av[ac] = t;
+           /*@=dependenttrans@*/
+           if (sb == NULL) {
+               /*@-unrecog@*/
+               switch(*s) {
+               case 'p':
+                   dt[ac] = DT_FIFO;
+                   /*@innerbreak@*/ break;
+               case 'c':
+                   dt[ac] = DT_CHR;
+                   /*@innerbreak@*/ break;
+               case 'd':
+                   dt[ac] = DT_DIR;
+                   /*@innerbreak@*/ break;
+               case 'b':
+                   dt[ac] = DT_BLK;
+                   /*@innerbreak@*/ break;
+               case '-':
+                   dt[ac] = DT_REG;
+                   /*@innerbreak@*/ break;
+               case 'l':
+                   dt[ac] = DT_LNK;
+                   /*@innerbreak@*/ break;
+               case 's':
+                   dt[ac] = DT_SOCK;
+                   /*@innerbreak@*/ break;
+               default:
+                   dt[ac] = DT_UNKNOWN;
+                   /*@innerbreak@*/ break;
+               }
+               /*@=unrecog@*/
+               for (sb = se; sb > s && sb[-1] != ' '; sb--)
+                   {};
+           }
+           ac++;
+           t = stpncpy(t, sb, (se - sb));
+           t[-1] = '\0';
+           if (*se == '\n') se++;
+           sb = NULL;
+           s = se;
+           /*@switchbreak@*/ break;
+       default:
+           /*@switchbreak@*/ break;
+       }
+    }
+    av[ac] = NULL;
+
+/*@-kepttrans@*/
+    return (DIR *) mydir;
+/*@=kepttrans@*/
 }
+/*@=boundswrite@*/
 
-static void ftpGlobfree(glob_t * pglob) {
-if (_rpmio_debug)
-fprintf(stderr, "*** ftpGlobfree(%p)\n", pglob);
-    if (pglob->gl_offs == -1)  /* XXX HACK HACK HACK */
-       xfree(pglob->gl_pathv);
+/*@dependent@*/ /*@null@*/
+static struct dirent * ftpReaddir(DIR * dir)
+       /*@globals fileSystem @*/
+       /*@modifies fileSystem @*/
+{
+    FTPDIR mydir = (FTPDIR)dir;
+    struct dirent * dp;
+    const char ** av;
+    unsigned char * dt;
+    int ac;
+    int i;
+
+    /*@+voidabstract@*/
+    if (mydir == NULL || !ISFTPMAGIC(mydir) || mydir->data == NULL) {
+       /* XXX TODO: EBADF errno. */
+       return NULL;
+    }
+    /*@=voidabstract@*/
+
+    dp = (struct dirent *) mydir->data;
+    av = (const char **) (dp + 1);
+    ac = mydir->size;
+    dt = (char *) (av + (ac + 1));
+    i = mydir->offset + 1;
+
+/*@-boundsread@*/
+    if (i < 0 || i >= ac || av[i] == NULL)
+       return NULL;
+/*@=boundsread@*/
+
+    mydir->offset = i;
+
+    /* XXX glob(3) uses REAL_DIR_ENTRY(dp) test on d_ino */
+    dp->d_ino = i + 1;         /* W2DO? */
+    dp->d_reclen = 0;          /* W2DO? */
+
+#if !defined(hpux) && !defined(sun)
+    dp->d_off = 0;             /* W2DO? */
+/*@-boundsread@*/
+    dp->d_type = dt[i];
+/*@=boundsread@*/
+#endif
+
+    strncpy(dp->d_name, av[i], sizeof(dp->d_name));
+/*@+voidabstract@*/
+if (_ftp_debug)
+fprintf(stderr, "*** ftpReaddir(%p) %p \"%s\"\n", (void *)mydir, dp, dp->d_name);
+/*@=voidabstract@*/
+    
+    return dp;
 }
+/*@=type@*/
 
-int Stat(const char * path, struct stat * st) {
+static int ftpClosedir(/*@only@*/ DIR * dir)
+       /*@globals fileSystem @*/
+       /*@modifies dir, fileSystem @*/
+{
+    FTPDIR mydir = (FTPDIR)dir;
+
+    /*@+voidabstract@*/
+if (_ftp_debug)
+fprintf(stderr, "*** ftpClosedir(%p)\n", (void *)mydir);
+    if (mydir == NULL || !ISFTPMAGIC(mydir)) {
+       /* XXX TODO: EBADF errno. */
+       return -1;
+    }
+    free((void *)mydir);
+    /*@=voidabstract@*/
+    mydir = NULL;
+    return 0;
+}
+
+int Stat(const char * path, struct stat * st)
+{
     const char * lpath;
     int ut = urlPath(path, &lpath);
 
@@ -978,7 +1348,8 @@ fprintf(stderr, "*** Stat(%s,%p)\n", path, st);
     return stat(path, st);
 }
 
-int Lstat(const char * path, struct stat * st) {
+int Lstat(const char * path, struct stat * st)
+{
     const char * lpath;
     int ut = urlPath(path, &lpath);
 
@@ -1002,7 +1373,8 @@ fprintf(stderr, "*** Lstat(%s,%p)\n", path, st);
     return lstat(path, st);
 }
 
-int Readlink(const char * path, char * buf, size_t bufsiz) {
+int Readlink(const char * path, char * buf, size_t bufsiz)
+{
     const char * lpath;
     int ut = urlPath(path, &lpath);
 
@@ -1021,10 +1393,13 @@ int Readlink(const char * path, char * buf, size_t bufsiz) {
        return -2;
        /*@notreached@*/ break;
     }
+/*@-compdef@*/
     return readlink(path, buf, bufsiz);
+/*@=compdef@*/
 }
 
-int Access(const char * path, int amode) {
+int Access(const char * path, int amode)
+{
     const char * lpath;
     int ut = urlPath(path, &lpath);
 
@@ -1046,21 +1421,30 @@ fprintf(stderr, "*** Access(%s,%d)\n", path, amode);
     return access(path, amode);
 }
 
-int Glob(const char *path, int flags,
+int Glob(const char *pattern, int flags,
        int errfunc(const char * epath, int eerrno), glob_t *pglob)
 {
     const char * lpath;
-    int ut = urlPath(path, &lpath);
+    int ut = urlPath(pattern, &lpath);
 
+/*@-castfcnptr@*/
 if (_rpmio_debug)
-fprintf(stderr, "*** Glob(%s,0x%x,%p,%p)\n", path, flags, errfunc, pglob);
+fprintf(stderr, "*** Glob(%s,0x%x,%p,%p)\n", pattern, (unsigned)flags, (void *)errfunc, pglob);
+/*@=castfcnptr@*/
     switch (ut) {
-    case URL_IS_FTP:           /* XXX WRONG WRONG WRONG */
-       return ftpGlob(path, flags, errfunc, pglob);
-       /*@notreached@*/ break;
+    case URL_IS_FTP:
+/*@-type@*/
+       pglob->gl_closedir = Closedir;
+       pglob->gl_readdir = Readdir;
+       pglob->gl_opendir = Opendir;
+       pglob->gl_lstat = Lstat;
+       pglob->gl_stat = Stat;
+/*@=type@*/
+       flags |= GLOB_ALTDIRFUNC;
+       break;
     case URL_IS_HTTP:          /* XXX WRONG WRONG WRONG */
     case URL_IS_PATH:
-       path = lpath;
+       pattern = lpath;
        /*@fallthrough@*/
     case URL_IS_UNKNOWN:
        break;
@@ -1069,17 +1453,14 @@ fprintf(stderr, "*** Glob(%s,0x%x,%p,%p)\n", path, flags, errfunc, pglob);
        return -2;
        /*@notreached@*/ break;
     }
-    return glob(path, flags, errfunc, pglob);
+    return glob(pattern, flags, errfunc, pglob);
 }
 
 void Globfree(glob_t *pglob)
 {
 if (_rpmio_debug)
 fprintf(stderr, "*** Globfree(%p)\n", pglob);
-    if (pglob->gl_offs == -1) /* XXX HACK HACK HACK */
-       ftpGlobfree(pglob);
-    else
-       globfree(pglob);
+    globfree(pglob);
 }
 
 DIR * Opendir(const char * path)
@@ -1090,7 +1471,9 @@ DIR * Opendir(const char * path)
 if (_rpmio_debug)
 fprintf(stderr, "*** Opendir(%s)\n", path);
     switch (ut) {
-    case URL_IS_FTP:           /* XXX WRONG WRONG WRONG */
+    case URL_IS_FTP:
+       return ftpOpendir(path);
+       /*@notreached@*/ break;
     case URL_IS_HTTP:          /* XXX WRONG WRONG WRONG */
     case URL_IS_PATH:
        path = lpath;
@@ -1102,19 +1485,27 @@ fprintf(stderr, "*** Opendir(%s)\n", path);
        return NULL;
        /*@notreached@*/ break;
     }
+    /*@-dependenttrans@*/
     return opendir(path);
+    /*@=dependenttrans@*/
 }
 
+/*@+voidabstract@*/
 struct dirent * Readdir(DIR * dir)
 {
 if (_rpmio_debug)
-fprintf(stderr, "*** Readdir(%p)\n", dir);
+fprintf(stderr, "*** Readdir(%p)\n", (void *)dir);
+    if (dir == NULL || ISFTPMAGIC(dir))
+       return ftpReaddir(dir);
     return readdir(dir);
 }
 
 int Closedir(DIR * dir)
 {
 if (_rpmio_debug)
-fprintf(stderr, "*** Closedir(%p)\n", dir);
+fprintf(stderr, "*** Closedir(%p)\n", (void *)dir);
+    if (dir == NULL || ISFTPMAGIC(dir))
+       return ftpClosedir(dir);
     return closedir(dir);
 }
+/*@=voidabstract@*/