home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 3 / PDCD_3.iso / tex / texsrc1 / Src / lib / old-c / pathsrch < prev    next >
Encoding:
C/C++ Source or Header  |  1993-01-03  |  15.0 KB  |  503 lines

  1. /* pathsrch.c: look for files based on paths, i.e., colon-separated
  2.    lists of directories.  
  3.    
  4.    Perhaps we should allow % specifiers in the paths for the resolution, etc.
  5.  
  6. Copyright (C) 1992 Free Software Foundation, Inc.
  7.  
  8. This program is free software; you can redistribute it and/or modify
  9. it under the terms of the GNU General Public License as published by
  10. the Free Software Foundation; either version 2, or (at your option)
  11. any later version.
  12.  
  13. This program is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. GNU General Public License for more details.
  17.  
  18. You should have received a copy of the GNU General Public License
  19. along with this program; if not, write to the Free Software
  20. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. #include "config.h"
  23.  
  24. #include "c-pathch.h"
  25. #include "c-namemx.h"
  26. #include "c-pathmx.h"
  27. #include "paths.h"
  28. #include "xstat.h"
  29.  
  30. #include "c-ctype.h"
  31. #if !defined (DOS) && !defined (VMS) && !defined (VMCMS)
  32. #include <pwd.h>
  33. #endif
  34. #include "dirio.h"
  35. #include "pathsrch.h"
  36.  
  37. static boolean absolute_p P1H(string filename);
  38. static void add_directory P3H(string **, unsigned *, string);
  39. static void expand_subdir P3H(string **, unsigned *, string);
  40. static string *find_dir_list P1H(string);
  41. static string readable P1H(string);
  42. static void save_dir_list P2H(string, string *);
  43. static string truncate_pathname P1H(string);
  44.  
  45. /* If FILENAME is absolute or explicitly relative (i.e., starts with
  46.    `/', `./', or `../'), or if DIR_LIST is null, we return whether
  47.    FILENAME is readable as-is.  Otherwise, we test if FILENAME is in any of
  48.    the directories listed in DIR_LIST.  (The last entry of DIR_LIST must
  49.    be null.)  We return the complete path if found, NULL else.
  50.    
  51.    In the interests of doing minimal work here, we assume that each
  52.    element of DIR_LIST already ends with a `/'.
  53.    
  54.    DIR_LIST is most conveniently made by calling `initialize_path_list'.
  55.    This is a separate routine because we allow recursive searching, and
  56.    it may take some time to discover the list of directories.  
  57.    We do not want to incur that overhead every time we want to look for
  58.    a file.
  59.    
  60.    (Actually, `/' is not hardwired into this routine; we use PATH_SEP,
  61.    defined above.)  */
  62.  
  63. string
  64. find_path_filename P2C(string, filename,  string *, dir_list)
  65. {
  66.   string found_name = NULL;
  67.   
  68.   /* Do this before testing for absolute-ness, as a leading ~ will be an
  69.      absolute pathname.  */
  70.   filename = expand_tilde (filename);
  71.   
  72.   /* If FILENAME is absolute or explicitly relative, or if DIR_LIST is
  73.      null, only check if FILENAME is readable.  */
  74.   if (absolute_p (filename) || dir_list == NULL)
  75.     found_name = readable (filename);
  76.   else
  77.     { /* Test if FILENAME is in any of the directories in DIR_LIST.  */
  78.       string save_filename = filename;
  79.       
  80.       while (*dir_list != NULL)
  81.         {
  82.           filename = concat (*dir_list, save_filename);
  83.           found_name = readable (filename);
  84.           if (found_name == NULL)
  85.             {
  86.               free (filename);
  87.               dir_list++;
  88.             }
  89.           else
  90.             {
  91.               if (found_name != filename)
  92.                 free (filename);
  93.               break;
  94.             }
  95.         }
  96.     }
  97.   
  98.   return found_name;
  99. }
  100.  
  101.  
  102. /* If NAME is readable, return it.  If the error is ENAMETOOLONG,
  103.    truncate any too-long path components and return the result (unless
  104.    there were no too-long components, i.e., a overall too-long name
  105.    caused the error, in which case return NULL).  On any other error,
  106.    return NULL.
  107.    
  108.    POSIX invented this brain-damage of not necessarily truncating
  109.    pathname components; the system's behavior is defined by the value of
  110.    the symbol _POSIX_NO_TRUNC, but you can't change it dynamically!  */
  111.  
  112. static string
  113. readable (name)
  114.     string name;
  115. {
  116.   string ret;
  117.   
  118.   if (access (name, R_OK) == 0 && !dir_p (name))
  119.     ret = name;
  120. #ifdef ENAMETOOLONG
  121.   else if (errno == ENAMETOOLONG)
  122.     { 
  123.       ret = truncate_pathname (name);
  124.  
  125.       /* Perhaps some other error will occur with the truncated name, so
  126.          let's call access again.  */
  127.       if (!(access (ret, R_OK) == 0 && !dir_p (ret)))
  128.         { /* Failed.  */
  129.           free (ret);
  130.           ret = NULL;
  131.         }
  132.     }
  133. #endif
  134.   else
  135.     ret = NULL; /* Some other error.  */
  136.   
  137.   return ret;
  138. }
  139.  
  140.  
  141.  
  142. /* Truncate any too-long path components in NAME, returning the result.  */
  143.  
  144. static string
  145. truncate_pathname (name)
  146.     string name;
  147. {
  148.   unsigned c_len = 0;        /* Length of current component.  */
  149.   unsigned ret_len = 0; /* Length of constructed result.  */
  150.   string ret = (string) xmalloc (PATH_MAX + 1);
  151.  
  152.   for (; *name; name++)
  153.     {
  154.       if (*name == PATH_SEP)
  155.         { /* At a directory delimiter, reset component length.  */
  156.           c_len = 0;
  157.         }
  158.       else if (c_len > NAME_MAX)
  159.         { /* If past the max for a component, ignore this character.  */
  160.           continue;
  161.         }
  162.  
  163.       /* If we've already copied the max, give up.  */
  164.       if (ret_len == PATH_MAX)
  165.         {
  166.           free (ret);
  167.           return NULL;
  168.         }
  169.  
  170.       /* Copy this character.  */
  171.       ret[ret_len++] = *name;
  172.       c_len++;
  173.     }
  174.   ret[ret_len] = 0;
  175.  
  176.   return ret;
  177. }
  178.  
  179.  
  180. /* Return true if FILENAME is absolute or explicitly relative, else
  181.    false.  */
  182.  
  183. static boolean
  184. absolute_p P1C(string, filename)
  185. {
  186.   boolean absolute = *filename == PATH_SEP
  187. #ifdef DOS
  188.                       || ISALPHA (*filename) && filename[1] == ':'
  189. #endif
  190.               ;
  191.   boolean explicit_relative
  192.     = (*filename == '.'
  193.        && (filename[1] == PATH_SEP
  194.            || (filename[1] == '.' && filename[2] == PATH_SEP)));
  195.  
  196.   return absolute || explicit_relative;
  197. }
  198.  
  199. /* Return a NULL-terminated array of directory names, each name ending
  200.    with PATH_SEP, created by parsing the PATH_DELIMITER-separated list
  201.    in the value of the environment variable ENV_NAME, or DEFAULT_PATH if
  202.    the envvar is not set.
  203.    
  204.    A leading or trailing colon in the value of ENV_NAME is replaced by
  205.    DEFAULT_PATH.
  206.    
  207.    Any element of the path that ends with double PATH_SEP characters
  208.    (e.g., `foo//') is replaced by all its subdirectories.
  209.  
  210.    If ENV_NAME is null, only parse DEFAULT_PATH.  If both are null, do
  211.    nothing and return NULL.  */
  212.  
  213. string *
  214. initialize_path_list P2C(string, env_name,  string, default_path)
  215. {
  216.   string dir, path;
  217.   string *dir_list;
  218.   unsigned dir_count = 0;
  219.   string env_value = env_name ? getenv (env_name) : NULL;
  220.   string orig_path = expand_default (env_value, default_path);
  221.  
  222.   if (orig_path == NULL || *orig_path == 0)
  223.     return NULL;
  224.  
  225.   /* If we've already seen this colon-separated list, then just get it
  226.      back instead of going back to the filesystem.  */
  227.   dir_list = find_dir_list (orig_path);
  228.   if (dir_list != NULL)
  229.     return dir_list;
  230.   
  231.   /* Be sure `path' is in writable memory.  */
  232.   path = (orig_path == env_value || orig_path == default_path
  233.           ? xstrdup (orig_path) : orig_path);
  234.  
  235.   /* Find each element in the path in turn.  */
  236.   for (dir = strtok (path, PATH_DELIMITER_STRING); dir != NULL;
  237.        dir = strtok (NULL, PATH_DELIMITER_STRING))
  238.     {
  239.       int len;
  240.       /* If the path starts with ~ or ~user, expand it.  Do this
  241.          before calling `expand_subdir' or `add_directory', so that
  242.          1) we don't expand the same ~ for every subdirectory; and 
  243.          2) pathnames in `expand_subdir' don't have a `~' in them
  244.             (since the system won't grok `~/foo' as a directory).  */
  245.       dir = expand_tilde (dir);
  246.       len = strlen (dir);
  247.  
  248.       /* If `dir' is the empty string, ignore it.  */
  249.       if (len == 0)
  250.         continue;
  251.  
  252.       /* If `dir' ends in double slashes, do subdirectories (and remove
  253.          the second slash, so the final pathnames we return don't look
  254.          like foo//bar).  Because we obviously want to do subdirectories
  255.          of `dir', we don't check if it is a leaf.  This means that if
  256.          `dir' is `foo//', and `foo' contains only symlinks (so our leaf
  257.          test below would be true), the symlinks are chased.  */
  258.       if (len > 2 && dir[len - 1] == PATH_SEP && dir[len - 2] == PATH_SEP)
  259.         {
  260.           dir[len - 1] = 0;
  261.           if (dir_p (dir))
  262.             {
  263.               add_directory (&dir_list, &dir_count, dir);
  264.               expand_subdir (&dir_list, &dir_count, dir);
  265.         }
  266.         }
  267.       else
  268.         { /* Don't bother to add the directory if it doesn't exist.  */
  269.           if (dir_p (dir))
  270.             add_directory (&dir_list, &dir_count, dir);
  271.     }
  272.     }
  273.   
  274.   /* Add the terminating null entry to `dir_list'.  */
  275.   dir_count++;
  276.   XRETALLOC (dir_list, dir_count, string);
  277.   dir_list[dir_count - 1] = NULL;
  278.   
  279.   /* Save the directory list we just found.  */
  280.   save_dir_list (orig_path, dir_list);
  281.  
  282.   return dir_list;
  283. }
  284.  
  285. /* Subroutines for `initialize_path_list'.  */
  286.  
  287. /* Add a newly-allocated copy of DIR to the end of the array pointed to
  288.    by DIR_LIST_PTR. Increment DIR_COUNT_PTR.  Append a `/' to DIR if
  289.    necessary.  We assume DIR is a directory, to avoid unnecessary an
  290.    unnecessary call to `stat'.  */
  291.  
  292. static void
  293. add_directory (dir_list_ptr, dir_count_ptr, dir)
  294.     string **dir_list_ptr;
  295.     unsigned *dir_count_ptr;
  296.     string dir;
  297. {
  298.   /* If `dir' does not end with a `/', add it.  We can't just
  299.      write it in place, since that would overwrite the null that
  300.      strtok may have put in.  So we always make a copy of DIR.  */
  301.   dir = (dir[strlen (dir) - 1] == PATH_SEP ? xstrdup (dir)
  302.          : concat (dir, PATH_SEP_STRING));
  303.  
  304.   /* Add `dir' to the list of the directories.  */
  305.   (*dir_count_ptr)++;
  306.   XRETALLOC (*dir_list_ptr, *dir_count_ptr, string);
  307.   (*dir_list_ptr)[*dir_count_ptr - 1] = dir;
  308. }
  309.  
  310.  
  311. /* Add DIRNAME to DIR_LIST and look for subdirectories, recursively.  We
  312.    assume DIRNAME is the name of a directory.  */
  313.  
  314. static void
  315. expand_subdir (dir_list_ptr, dir_count_ptr, dirname)
  316.     string **dir_list_ptr;
  317.     unsigned *dir_count_ptr;
  318.     string dirname;
  319. {
  320.   DIR *dir;
  321.   struct dirent *e;
  322.   unsigned length;
  323.   char potential[PATH_MAX];
  324.   struct stat st;
  325.   
  326.    /* We will be looking at its contents.  */
  327.   dir = opendir (dirname);
  328.   if (dir == NULL)
  329.     return;
  330.   
  331.   /* Compute the length of DIRNAME, since it's loop-invariant.  */
  332.   length = strlen (dirname);
  333.  
  334.   /* Construct the part of the pathname that doesn't change.  */
  335.   strcpy (potential, dirname);
  336.   if (potential[length - 1] != PATH_SEP)
  337.     {
  338.       potential[length] = PATH_SEP;
  339.       potential[length + 1] = 0;
  340.       length++;
  341.     }
  342.   
  343.   while ((e = readdir (dir)) != NULL)
  344.     { /* If it's . or .., never mind.  */
  345.       if (!(e->d_name[0] == '.'
  346.             && (e->d_name[1] == 0
  347.                 || (e->d_name[1] == '.' && e->d_name[2] == 0))))
  348.         { /* If it's not a directory, we will skip it on the
  349.              recursive call.  */
  350.           strcat (potential, e->d_name);
  351.  
  352.           /* If we can't stat it, or if it isn't a directory, continue.  */
  353.           if (stat (potential, &st) == 0 && S_ISDIR (st.st_mode))
  354.             { /* It's a subdirectory; add `potential' to the list.  */
  355.               add_directory (dir_list_ptr, dir_count_ptr, potential);
  356.  
  357.               /* If it's not a leaf, quit.  Assume that leaf
  358.                  directories have two links (one for . and one for ..).
  359.                  This means that symbolic links to directories do not affect
  360.                  the leaf-ness.  This is arguably wrong, but the only
  361.                  alternative I know of is to stat every entry in the
  362.                  directory, and that is unacceptably slow.  */
  363.               if (st.st_nlink > 2)
  364.                 { /* All criteria are met; find subdirectories.  */
  365.                   expand_subdir (dir_list_ptr, dir_count_ptr, potential);
  366.                 }
  367.             }
  368.  
  369.           /* ``Remove'' the directory entry name.  */
  370.           potential[length] = 0;
  371.         }
  372.     }
  373.   
  374.   closedir (dir);
  375. }
  376.  
  377. /* These routines, while not strictly needed to be exported, are
  378.    plausibly useful to be called by outsiders.  */
  379.  
  380. /* Replace a leading or trailing `:' in ENV_PATH with DEFAULT_PATH.  If
  381.    neither is present, return ENV_PATH if that is non-null, else
  382.    DEFAULT_PATH.  */
  383.  
  384. string 
  385. expand_default (env_path, default_path)
  386.    string env_path;
  387.    string default_path;
  388. {
  389.   string expansion;
  390.   
  391.   if (env_path == NULL)
  392.     expansion = default_path;
  393.   else if (*env_path == PATH_DELIMITER)
  394.     expansion = concat (default_path, env_path);
  395.   else if (env_path[strlen (env_path) - 1] == PATH_DELIMITER)
  396.     expansion = concat (env_path, default_path);
  397.   else
  398.     expansion = env_path;
  399.   
  400.   return expansion;
  401. }
  402.  
  403.  
  404. /* Expand a leading ~ or ~user, Unix-style, unless we are some weirdo
  405.    operating system.  */
  406.  
  407. string
  408. expand_tilde P1C(string, name)
  409. {
  410. #if defined (DOS) || defined (VMS) || defined (VMCMS)
  411.   return name;
  412. #else
  413.   string expansion;
  414.   string home;
  415.   
  416.   /* If no leading tilde, do nothing.  */
  417.   if (*name != '~')
  418.     expansion = name;
  419.   
  420.   /* If `~' or `~/', use $HOME if it exists, or `.' if it doesn't.  */
  421.   else if (name[1] == PATH_SEP || name[1] == 0)
  422.     {
  423.       home = getenv ("HOME");
  424.       if (home == NULL)
  425.         home = ".";
  426.         
  427.       expansion
  428.         = name[1] == 0 ? home : concat3 (home, PATH_SEP_STRING, name + 2);
  429.     }
  430.   
  431.   /* If `~user' or `~user/', look up user in the passwd database.  */
  432.   else
  433.     {
  434.       struct passwd *p;
  435.       string user;
  436.       unsigned c = 2;
  437.       while (name[c] != PATH_SEP && name[c] != 0)
  438.         c++;
  439.       
  440.       user = (string) xmalloc (c);
  441.       strncpy (user, name + 1, c - 1);
  442.       user[c - 1] = 0;
  443.       
  444.       /* We only need the cast here for those (old deficient) systems
  445.          which do not declare `getpwnam' in <pwd.h>.  */
  446.       p = (struct passwd *) getpwnam (user);
  447.       free (user);
  448.       /* If no such user, just use `.'.  */
  449.       home = p == NULL ? "." : p->pw_dir;
  450.       
  451.       expansion = name[c] == 0 ? home : concat (home, name + c);
  452.     }
  453.   
  454.   return expansion;
  455. #endif /* not (DOS or VMS or VM/CMS) */
  456. }
  457.  
  458. /* Routines to save and retrieve a directory list keyed by the original
  459.    colon-separated path.  This is useful because 1) it can take a
  460.    significant amount of time to discover all the subdirectories of a
  461.    given directory, and 2) many paths all have the same basic default,
  462.    and thus would recompute the directory list.  */
  463.  
  464. typedef struct
  465. {
  466.   string path;
  467.   string *dir_list;
  468. } saved_path_entry;
  469.  
  470. static saved_path_entry *saved_paths = NULL;
  471. static unsigned saved_paths_length = 0;
  472.  
  473.  
  474. /* We implement the data structure as a simple linear list, since it's
  475.    unlikely to ever be more than a dozen or so elements long.  We don't
  476.    bother to check here if PATH has already been saved; we always add it
  477.    to our list.  */
  478.  
  479. static void
  480. save_dir_list P2C(string, path,  string *, dir_list)
  481. {
  482.   saved_paths_length++;
  483.   XRETALLOC (saved_paths, saved_paths_length, saved_path_entry);
  484.   saved_paths[saved_paths_length - 1].path = path;
  485.   saved_paths[saved_paths_length - 1].dir_list = dir_list;
  486. }
  487.  
  488. /* When we retrieve, just check the list in order.  */
  489.  
  490. static string *
  491. find_dir_list P1C(string, path)
  492. {
  493.   unsigned p;
  494.   
  495.   for (p = 0; p < saved_paths_length; p++)
  496.     {
  497.       if (strcmp (saved_paths[p].path, path) == 0)
  498.         return saved_paths[p].dir_list;
  499.     }
  500.   
  501.   return NULL;
  502. }
  503.