toybox/lib/dirtree.c
<<
>>
Prefs
   1/* dirtree.c - Functions for dealing with directory trees.
   2 *
   3 * Copyright 2007 Rob Landley <rob@landley.net>
   4 */
   5
   6#include "toys.h"
   7
   8int isdotdot(char *name)
   9{
  10  if (name[0]=='.' && (!name[1] || (name[1]=='.' && !name[2]))) return 1;
  11
  12  return 0;
  13}
  14
  15// Default callback, filters out "." and ".." except at top level.
  16
  17int dirtree_notdotdot(struct dirtree *catch)
  18{
  19  // Should we skip "." and ".."?
  20  return (!catch->parent||!isdotdot(catch->name))
  21    *(DIRTREE_SAVE|DIRTREE_RECURSE);
  22}
  23
  24// Create a dirtree node from a path, with stat and symlink info.
  25// (This doesn't open directory filehandles yet so as not to exhaust the
  26// filehandle space on large trees, dirtree_handle_callback() does that.)
  27
  28struct dirtree *dirtree_add_node(struct dirtree *parent, char *name, int flags)
  29{
  30  struct dirtree *dt = 0;
  31  struct stat st;
  32  int len = 0, linklen = 0, statless = 0;
  33
  34  if (name) {
  35    // open code fd = because haven't got node to call dirtree_parentfd() on yet
  36    int fd = parent ? parent->dirfd : AT_FDCWD,
  37      sym = AT_SYMLINK_NOFOLLOW*!(flags&DIRTREE_SYMFOLLOW);
  38
  39    // stat dangling symlinks
  40    if (fstatat(fd, name, &st, sym)) {
  41      // If we got ENOENT without NOFOLLOW, try again with NOFOLLOW.
  42      if (errno!=ENOENT || sym || fstatat(fd, name, &st, AT_SYMLINK_NOFOLLOW)) {
  43        if (flags&DIRTREE_STATLESS) statless++;
  44        else goto error;
  45      }
  46    }
  47    if (!statless && S_ISLNK(st.st_mode)) {
  48      if (0>(linklen = readlinkat(fd, name, libbuf, 4095))) goto error;
  49      libbuf[linklen++]=0;
  50    }
  51    len = strlen(name);
  52  }
  53
  54  // Allocate/populate return structure
  55  memset(dt = xmalloc((len = sizeof(struct dirtree)+len+1)+linklen), 0,
  56    statless ? sizeof(struct dirtree) : offsetof(struct dirtree, st));
  57  dt->parent = parent;
  58  dt->again = statless ? 2 : 0;
  59  if (!statless) memcpy(&dt->st, &st, sizeof(struct stat));
  60  if (name) strcpy(dt->name, name);
  61  else *dt->name = 0, dt->st.st_mode = S_IFDIR;
  62  if (linklen) dt->symlink = memcpy(len+(char *)dt, libbuf, linklen);
  63
  64  return dt;
  65
  66error:
  67  if (!(flags&DIRTREE_SHUTUP) && !isdotdot(name)) {
  68    char *path = parent ? dirtree_path(parent, 0) : "";
  69
  70    perror_msg("%s%s%s", path, parent ? "/" : "", name);
  71    if (parent) free(path);
  72  }
  73  if (parent) parent->symlink = (char *)1;
  74  free(dt);
  75  return 0;
  76}
  77
  78// Return path to this node.
  79
  80// Initial call can pass in NULL to plen, or point to an int initialized to 0
  81// to return the length of the path, or a value greater than 0 to allocate
  82// extra space if you want to append your own text to the string.
  83
  84char *dirtree_path(struct dirtree *node, int *plen)
  85{
  86  struct dirtree *nn;
  87  char *path;
  88  int ii, ll, len;
  89
  90  ll = len = plen ? *plen : 0;
  91  if (!node->parent)
  92    return strcpy(xmalloc(strlen(node->name)+ll+1), node->name);
  93  for (nn = node; nn; nn = nn->parent)
  94    if ((ii = strlen(nn->name))) len += ii+1-(nn->name[ii-1]=='/');
  95  if (plen) *plen = len;
  96  path = xmalloc(len)+len-ll;
  97  for (nn = node; nn; nn = nn->parent) if ((len = strlen(nn->name))) {
  98    *--path = '/'*(nn != node);
  99    if (nn->name[len-1]=='/') len--;
 100    memcpy(path -= len, nn->name, len);
 101  }
 102
 103  return path;
 104}
 105
 106int dirtree_parentfd(struct dirtree *node)
 107{
 108  return node->parent ? node->parent->dirfd : AT_FDCWD;
 109}
 110
 111// Handle callback for a node in the tree. Returns saved node(s) if
 112// callback returns DIRTREE_SAVE, otherwise frees consumed nodes and
 113// returns NULL. If !callback return top node unchanged.
 114// If !new return DIRTREE_ABORTVAL
 115
 116static struct dirtree *dirtree_handle_callback(struct dirtree *new,
 117  int (*callback)(struct dirtree *node))
 118{
 119  int flags;
 120
 121  if (!new) return DIRTREE_ABORTVAL;
 122  if (!callback) return new;
 123  flags = callback(new);
 124
 125  if (S_ISDIR(new->st.st_mode) && (flags & (DIRTREE_RECURSE|DIRTREE_COMEAGAIN)))
 126    flags = dirtree_recurse(new, callback, !*new->name ? AT_FDCWD :
 127      openat(dirtree_parentfd(new), new->name, O_CLOEXEC), flags);
 128
 129  // Free node that didn't request saving and has no saved children.
 130  if (!new->child && !(flags & DIRTREE_SAVE)) {
 131    free(new);
 132    new = 0;
 133  }
 134
 135  return (flags & DIRTREE_ABORT)==DIRTREE_ABORT ? DIRTREE_ABORTVAL : new;
 136}
 137
 138// Recursively read/process children of directory node, filtering through
 139// callback(). Uses and closes supplied ->dirfd.
 140
 141int dirtree_recurse(struct dirtree *node,
 142          int (*callback)(struct dirtree *node), int dirfd, int flags)
 143{
 144  struct dirtree *new, **ddt = &(node->child);
 145  struct dirent *entry;
 146  DIR *dir = 0;
 147
 148  // Why doesn't fdopendir() support AT_FDCWD?
 149  if (AT_FDCWD == (node->dirfd = dirfd)) dir = opendir(".");
 150  else if (node->dirfd != -1) dir = fdopendir(node->dirfd);
 151  if (!dir) {
 152    if (!(flags & DIRTREE_SHUTUP)) {
 153      char *path = dirtree_path(node, 0);
 154      perror_msg_raw(path);
 155      free(path);
 156    }
 157    close(node->dirfd);
 158
 159    return flags;
 160  }
 161
 162  // according to the fddir() man page, the filehandle in the DIR * can still
 163  // be externally used by things that don't lseek() it.
 164
 165  // The extra parentheses are to shut the stupid compiler up.
 166  while ((entry = readdir(dir))) {
 167    if ((flags&DIRTREE_PROC) && !isdigit(*entry->d_name)) continue;
 168    if (!(new = dirtree_add_node(node, entry->d_name, flags))) continue;
 169    if (!new->st.st_blksize && !new->st.st_mode)
 170      new->st.st_mode = entry->d_type<<12;
 171    new = dirtree_handle_callback(new, callback);
 172    if (new == DIRTREE_ABORTVAL) break;
 173    if (new) {
 174      *ddt = new;
 175      ddt = &((*ddt)->next);
 176    }
 177  }
 178
 179  if (flags & DIRTREE_COMEAGAIN) {
 180    node->again |= 1;
 181    flags = callback(node);
 182  }
 183
 184  // This closes filehandle as well, so note it
 185  closedir(dir);
 186  node->dirfd = -1;
 187
 188  return flags;
 189}
 190
 191// Create dirtree from path, using callback to filter nodes. If !callback
 192// return just the top node. Use dirtree_notdotdot callback to allocate a
 193// tree of struct dirtree nodes and return pointer to root node for later
 194// processing.
 195// Returns DIRTREE_ABORTVAL if path didn't exist (use DIRTREE_SHUTUP to handle
 196// error message yourself).
 197
 198struct dirtree *dirtree_flagread(char *path, int flags,
 199  int (*callback)(struct dirtree *node))
 200{
 201  return dirtree_handle_callback(dirtree_add_node(0, path, flags), callback);
 202}
 203
 204// Common case
 205struct dirtree *dirtree_read(char *path, int (*callback)(struct dirtree *node))
 206{
 207  return dirtree_flagread(path, 0, callback);
 208}
 209