libextractor

GNU libextractor
Log | Files | Refs | Submodules | README | LICENSE

extractor_plugpath.c (16945B)


      1 /*
      2      This file is part of libextractor.
      3      Copyright (C) 2002, 2003, 2004, 2005, 2006, 2009, 2012 Vidyut Samanta and Christian Grothoff
      4 
      5      libextractor is free software; you can redistribute it and/or modify
      6      it under the terms of the GNU General Public License as published
      7      by the Free Software Foundation; either version 3, or (at your
      8      option) any later version.
      9 
     10      libextractor is distributed in the hope that it will be useful, but
     11      WITHOUT ANY WARRANTY; without even the implied warranty of
     12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     13      General Public License for more details.
     14 
     15      You should have received a copy of the GNU General Public License
     16      along with libextractor; see the file COPYING.  If not, write to the
     17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
     18      Boston, MA 02110-1301, USA.
     19  */
     20 /**
     21  * @file main/extractor_plugpath.c
     22  * @brief determine path where plugins are installed
     23  * @author Christian Grothoff
     24  */
     25 
     26 #include "platform.h"
     27 #include "extractor.h"
     28 #include <dirent.h>
     29 #include <sys/types.h>
     30 #include <signal.h>
     31 #include <ltdl.h>
     32 #include <stdbool.h>
     33 
     34 #include "extractor_plugpath.h"
     35 #include "extractor_logging.h"
     36 
     37 /**
     38  * Function to call on paths.
     39  *
     40  * @param cls closure
     41  * @param path a directory path
     42  */
     43 typedef void (*EXTRACTOR_PathProcessor) (void *cls,
     44                                          const char *path);
     45 
     46 
     47 /**
     48  * Remove a trailing '/bin/' from 'in' (if present).
     49  *
     50  * @param in input string, modified
     51  * @return NULL if 'in' is NULL, otherwise 'in' with '/bin/' removed
     52  */
     53 static char *
     54 cut_bin (char *in)
     55 {
     56   size_t p;
     57 
     58   if (NULL == in)
     59     return NULL;
     60   p = strlen (in);
     61   if (p < 4)
     62     return in;
     63   if ( ('/' == in[p - 1]) ||
     64        ('\\' == in[p - 1]) )
     65     in[--p] = '\0';
     66   if (0 == strcmp (&in[p - 4],
     67                    "/bin"))
     68   {
     69     in[p - 4] = '\0';
     70     p -= 4;
     71   }
     72   else if (0 == strcmp (&in[p - 4],
     73                         "\\bin"))
     74   {
     75     in[p - 4] = '\0';
     76     p -= 4;
     77   }
     78   return in;
     79 }
     80 
     81 
     82 #if GNU_LINUX
     83 /**
     84  * Try to determine path by reading /proc/PID/exe or
     85  * /proc/PID/maps.
     86  *
     87  * Note that this may fail if LE is installed in one directory
     88  * and the binary linking against it sits elsewhere.
     89  */
     90 static char *
     91 get_path_from_proc_exe ()
     92 {
     93   char fn[64];
     94   char line[1024];
     95   char dir[1024];
     96   char *lnk;
     97   char *ret;
     98   char *lestr;
     99   ssize_t size;
    100   FILE *f;
    101 
    102   snprintf (fn,
    103             sizeof (fn),
    104             "/proc/%u/maps",
    105             getpid ());
    106   if (NULL != (f = fopen (fn, "r")))
    107   {
    108     while (NULL != fgets (line, 1024, f))
    109     {
    110       if ( (1 == sscanf (line,
    111                          "%*x-%*x %*c%*c%*c%*c %*x %*2x:%*2x %*u%*[ ]%1023s",
    112                          dir)) &&
    113            (NULL != (lestr = strstr (dir,
    114                                      "libextractor")) ) )
    115       {
    116         lestr[0] = '\0';
    117         fclose (f);
    118         return strdup (dir);
    119       }
    120     }
    121     fclose (f);
    122   }
    123   snprintf (fn,
    124             sizeof (fn),
    125             "/proc/%u/exe",
    126             getpid ());
    127   if (NULL == (lnk = malloc (1029))) /* 1024 + 6 for "/lib/" catenation */
    128     return NULL;
    129   size = readlink (fn, lnk, 1023);
    130   if ( (size <= 0) || (size >= 1024) )
    131   {
    132     free (lnk);
    133     return NULL;
    134   }
    135   lnk[size] = '\0';
    136   while ( ('/' != lnk[size]) &&
    137           (size > 0) )
    138     size--;
    139   if ( (size < 4) ||
    140        ('/' != lnk[size - 4]) )
    141   {
    142     /* not installed in "/bin/" -- binary path probably useless */
    143     free (lnk);
    144     return NULL;
    145   }
    146   lnk[size] = '\0';
    147   lnk = cut_bin (lnk);
    148   if (NULL == (ret = realloc (lnk, strlen (lnk) + 6)))
    149   {
    150     LOG_STRERROR ("realloc");
    151     free (lnk);
    152     return NULL;
    153   }
    154   strcat (ret, "/lib/"); /* guess "lib/" as the library dir */
    155   return ret;
    156 }
    157 
    158 
    159 #endif
    160 
    161 
    162 #if WINDOWS
    163 static HMODULE le_dll = NULL;
    164 
    165 BOOL WINAPI
    166 DllMain (HINSTANCE hinstDLL,
    167          DWORD fdwReason,
    168          LPVOID lpvReserved)
    169 {
    170   switch (fdwReason)
    171   {
    172   case DLL_PROCESS_ATTACH:
    173     le_dll = (HMODULE) hinstDLL;
    174     break;
    175   }
    176 
    177   return TRUE;
    178 }
    179 
    180 
    181 /**
    182  * Try to determine path with win32-specific function
    183  */
    184 static char *
    185 get_path_from_module_filename ()
    186 {
    187   char *path;
    188   char *ret;
    189   char *idx;
    190 
    191   if (NULL == (path = malloc (4103))) /* 4096+nil+6 for "/lib/" catenation */
    192     return NULL;
    193   GetModuleFileName (le_dll, path, 4096);
    194   idx = path + strlen (path);
    195   while ( (idx > path) &&
    196           ('\\' != *idx) &&
    197           ('/' != *idx) )
    198     idx--;
    199   *idx = '\0';
    200   path = cut_bin (path);
    201   if (NULL == (ret = realloc (path, strlen (path) + 6)))
    202   {
    203     LOG_STRERROR ("realloc");
    204     free (path);
    205     return NULL;
    206   }
    207   strcat (ret, "/lib/"); /* guess "lib/" as the library dir */
    208   return ret;
    209 }
    210 
    211 
    212 #endif
    213 
    214 
    215 #if DARWIN
    216 #include <dlfcn.h>
    217 #include <mach-o/dyld.h>
    218 
    219 /**
    220  * Signature of the '_NSGetExecutablePath" function.
    221  *
    222  * @param buf where to write the path
    223  * @param number of bytes available in 'buf'
    224  * @return 0 on success, otherwise desired number of bytes is stored in 'bufsize'
    225  */
    226 typedef int
    227 (*MyNSGetExecutablePathProto) (char *buf,
    228                                size_t *bufsize);
    229 
    230 
    231 /**
    232  * Try to obtain the path of our executable using '_NSGetExecutablePath'.
    233  *
    234  * @return NULL on error
    235  */
    236 static char *
    237 get_path_from_NSGetExecutablePath ()
    238 {
    239   static char zero;
    240   char *path;
    241   char *ret;
    242   size_t len;
    243   MyNSGetExecutablePathProto func;
    244 
    245   path = NULL;
    246   if (NULL == (func =
    247                  (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT,
    248                                                      "_NSGetExecutablePath")))
    249     return NULL;
    250   path = &zero;
    251   len = 0;
    252   /* get the path len, including the trailing \0 */
    253   (void) func (path, &len);
    254   if (0 == len)
    255     return NULL;
    256   if (NULL == (path = malloc (len)))
    257   {
    258     LOG_STRERROR ("malloc");
    259     return NULL;
    260   }
    261   if (0 != func (path, &len))
    262   {
    263     free (path);
    264     return NULL;
    265   }
    266   len = strlen (path);
    267   while ((path[len] != '/') && (len > 0))
    268     len--;
    269   path[len] = '\0';
    270   if (NULL != strstr (path, "/lib"))
    271     return path;
    272   path = cut_bin (path);
    273   if (NULL == (ret = realloc (path, strlen (path) + 5)))
    274   {
    275     LOG_STRERROR ("realloc");
    276     free (path);
    277     return NULL;
    278   }
    279   strcat (ret, "/lib/");
    280   return ret;
    281 }
    282 
    283 
    284 /**
    285  * Try to obtain the directory of the image that contains this code,
    286  * normally libextractor itself.  (We do not compare against
    287  * _mh_dylib_header, which only exists in a dylib: the plugin helper
    288  * is an executable built from the same sources.)
    289  *
    290  * @return NULL on error
    291  */
    292 static char *
    293 get_path_from_dyld_image ()
    294 {
    295   Dl_info info;
    296   char *s;
    297   char *p;
    298 
    299   if ( (0 == dladdr ((void *) &get_path_from_dyld_image,
    300                      &info)) ||
    301        (NULL == info.dli_fname) ||
    302        ('\0' == info.dli_fname[0]) )
    303     return NULL;
    304   if (NULL == (p = strdup (info.dli_fname)))
    305   {
    306     LOG_STRERROR ("strdup");
    307     return NULL;
    308   }
    309   s = p + strlen (p);
    310   while ( (s > p) && ('/' != *s) )
    311     s--;
    312   s++;
    313   *s = '\0';
    314   return p;
    315 }
    316 
    317 
    318 #endif
    319 
    320 
    321 /**
    322  * Return the actual path to a file found in the current
    323  * PATH environment variable.
    324  *
    325  * @return path to binary, NULL if not found
    326  */
    327 static char *
    328 get_path_from_PATH ()
    329 {
    330   struct stat sbuf;
    331   char *path;
    332   char *pos;
    333   char *end;
    334   char *buf;
    335   char *ret;
    336   const char *p;
    337 
    338   if (NULL == (p = getenv ("PATH")))
    339     return NULL;
    340   if (NULL == (path = strdup (p))) /* because we write on it */
    341   {
    342     LOG_STRERROR ("strdup");
    343     return NULL;
    344   }
    345   if (NULL == (buf = malloc (strlen (path) + 20)))
    346   {
    347     LOG_STRERROR ("malloc");
    348     free (path);
    349     return NULL;
    350   }
    351   pos = path;
    352   while (NULL != (end = strchr (pos, ':')))
    353   {
    354     *end = '\0';
    355     sprintf (buf, "%s/%s", pos, "extract");
    356     if (0 == stat (buf, &sbuf))
    357     {
    358       free (buf);
    359       if (NULL == (pos = strdup (pos)))
    360       {
    361         LOG_STRERROR ("strdup");
    362         free (path);
    363         return NULL;
    364       }
    365       free (path);
    366       pos = cut_bin (pos);
    367       if (NULL == (ret = realloc (pos, strlen (pos) + 6)))
    368       {
    369         LOG_STRERROR ("realloc");
    370         free (pos);
    371         return NULL;
    372       }
    373       strcat (ret, "/lib/");
    374       return ret;
    375     }
    376     pos = end + 1;
    377   }
    378   sprintf (buf, "%s/%s", pos, "extract");
    379   if (0 == stat (buf, &sbuf))
    380   {
    381     pos = strdup (pos);
    382     free (buf);
    383     free (path);
    384     if (NULL == pos)
    385       return NULL;
    386     pos = cut_bin (pos);
    387     if (NULL == (ret = realloc (pos, strlen (pos) + 6)))
    388     {
    389       LOG_STRERROR ("realloc");
    390       free (pos);
    391       return NULL;
    392     }
    393     strcat (ret, "/lib/");
    394     return ret;
    395   }
    396   free (buf);
    397   free (path);
    398   return NULL;
    399 }
    400 
    401 
    402 /**
    403  * Create a filename by appending 'fname' to 'path'.
    404  *
    405  * @param path the base path
    406  * @param fname the filename to append
    407  * @return '$path/$fname', NULL on error
    408  */
    409 static char *
    410 append_to_dir (const char *path,
    411                const char *fname)
    412 {
    413   char *ret;
    414   size_t slen;
    415 
    416   if (0 == (slen = strlen (path)))
    417     return NULL;
    418   if ('/' == fname[0])
    419     fname++;
    420   ret = malloc (slen + strlen (fname) + 2);
    421   if (NULL == ret)
    422     return NULL;
    423 #ifdef MINGW
    424   if ('\\' == path[slen - 1])
    425     sprintf (ret,
    426              "%s%s",
    427              path,
    428              fname);
    429   else
    430     sprintf (ret,
    431              "%s\\%s",
    432              path,
    433              fname);
    434 #else
    435   if ('/' == path[slen - 1])
    436     sprintf (ret,
    437              "%s%s",
    438              path,
    439              fname);
    440   else
    441     sprintf (ret,
    442              "%s/%s",
    443              path,
    444              fname);
    445 #endif
    446   return ret;
    447 }
    448 
    449 
    450 /**
    451  * Iterate over all paths where we expect to find GNU libextractor
    452  * plugins.
    453  *
    454  * @param pp function to call for each path
    455  * @param pp_cls cls argument for pp.
    456  */
    457 static void
    458 get_installation_paths (EXTRACTOR_PathProcessor pp,
    459                         void *pp_cls)
    460 {
    461   const char *p;
    462   char *path;
    463   char *prefix;
    464   char *d;
    465   char *saveptr;
    466   bool skip; /* true if we should skip GETENV */
    467 
    468   prefix = NULL;
    469 #ifdef HAVE_SECURE_GETENV
    470   /* secure_getenv() already ignores the environment in secure execution
    471      mode, so we never have to suppress the lookup ourselves */
    472   #define GETENV secure_getenv
    473     skip = false;
    474 #elif WINDOWS
    475   /* no set-user-ID/set-group-ID notion to worry about */
    476   #define GETENV getenv
    477     skip = false;
    478 #elif defined(HAVE_ISSETUGID)
    479   #define GETENV getenv
    480     skip = (0 != issetugid ());
    481 #else
    482   /* poor man's approximation of the secure execution mode test
    483      that secure_getenv() would do for us */
    484   #define GETENV getenv
    485     skip = ( (getuid () != geteuid ()) ||
    486              (getgid () != getegid ()) );
    487 #endif
    488 
    489   if ( (! skip) &&
    490        (NULL != (p = GETENV ("LIBEXTRACTOR_PREFIX"))) )
    491   {
    492     if (NULL == (d = strdup (p)))
    493     {
    494       LOG_STRERROR ("strdup");
    495       return;
    496     }
    497     for (prefix = strtok_r (d, ":", &saveptr);
    498          NULL != prefix;
    499          prefix = strtok_r (NULL, ":", &saveptr))
    500       pp (pp_cls, prefix);
    501     free (d);
    502     return;
    503   }
    504 #if GNU_LINUX
    505   if (NULL == prefix)
    506     prefix = get_path_from_proc_exe ();
    507 #endif
    508 #if WINDOWS
    509   if (NULL == prefix)
    510     prefix = get_path_from_module_filename ();
    511 #endif
    512 #if DARWIN
    513   if (NULL == prefix)
    514     prefix = get_path_from_NSGetExecutablePath ();
    515   if (NULL == prefix)
    516     prefix = get_path_from_dyld_image ();
    517 #endif
    518   if (NULL == prefix)
    519     prefix = get_path_from_PATH ();
    520   pp (pp_cls, PLUGININSTDIR);
    521   if (NULL == prefix)
    522     return;
    523   path = append_to_dir (prefix, PLUGINDIR);
    524   if (NULL != path)
    525   {
    526     if (0 != strcmp (path,
    527                      PLUGININSTDIR))
    528       pp (pp_cls, path);
    529     free (path);
    530   }
    531   free (prefix);
    532 }
    533 
    534 
    535 /**
    536  * Closure for #find_plugin_in_path().
    537  */
    538 struct SearchContext
    539 {
    540   /**
    541    * Name of the plugin we are looking for.
    542    */
    543   const char *short_name;
    544 
    545   /**
    546    * Location for storing the path to the plugin upon success.
    547    */
    548   char *path;
    549 };
    550 
    551 
    552 /**
    553  * Load all plugins from the given directory.
    554  *
    555  * @param cls pointer to the "struct EXTRACTOR_PluginList*" to extend
    556  * @param path path to a directory with plugins
    557  */
    558 static void
    559 find_plugin_in_path (void *cls,
    560                      const char *path)
    561 {
    562   struct SearchContext *sc = cls;
    563   DIR *dir;
    564   struct dirent *ent;
    565   const char *sym_name;
    566   char *sym;
    567   char *dot;
    568   size_t dlen;
    569 
    570   if (NULL != sc->path)
    571     return;
    572   if (NULL == (dir = opendir (path)))
    573     return;
    574   while (NULL != (ent = readdir (dir)))
    575   {
    576     if ('.' == ent->d_name[0])
    577       continue;
    578     dlen = strlen (ent->d_name);
    579     if ( (dlen < 4) ||
    580          ( (0 != strcmp (&ent->d_name[dlen - 3], ".so")) &&
    581            (0 != strcasecmp (&ent->d_name[dlen - 4], ".dll")) ) )
    582       continue; /* only load '.so' and '.dll' */
    583     if (NULL == (sym_name = strrchr (ent->d_name, '_')))
    584       continue;
    585     sym_name++;
    586     if (NULL == (sym = strdup (sym_name)))
    587     {
    588       LOG_STRERROR ("strdup");
    589       closedir (dir);
    590       return;
    591     }
    592     dot = strchr (sym, '.');
    593     if (NULL != dot)
    594       *dot = '\0';
    595     if (0 == strcmp (sym, sc->short_name))
    596     {
    597       sc->path = append_to_dir (path, ent->d_name);
    598       free (sym);
    599       break;
    600     }
    601     free (sym);
    602   }
    603   closedir (dir);
    604 }
    605 
    606 
    607 /**
    608  * Given a short name of a library (i.e. "mime"), find
    609  * the full path of the respective plugin.
    610  */
    611 char *
    612 EXTRACTOR_find_plugin_ (const char *short_name)
    613 {
    614   struct SearchContext sc;
    615 
    616   sc.path = NULL;
    617   sc.short_name = short_name;
    618   get_installation_paths (&find_plugin_in_path,
    619                           &sc);
    620   return sc.path;
    621 }
    622 
    623 
    624 /**
    625  * Look for the plugin helper program in the given directory.
    626  *
    627  * @param cls the `struct SearchContext`, whose short_name is the
    628  *        file name of the helper
    629  * @param path directory to look in
    630  */
    631 static void
    632 find_helper_in_path (void *cls,
    633                      const char *path)
    634 {
    635   struct SearchContext *sc = cls;
    636   char *fn;
    637 
    638   if (NULL != sc->path)
    639     return;
    640   if (NULL == (fn = append_to_dir (path,
    641                                    sc->short_name)))
    642     return;
    643   if (0 == access (fn,
    644                    X_OK))
    645     sc->path = fn;
    646   else
    647     free (fn);
    648 }
    649 
    650 
    651 /**
    652  * Find the program that runs plugins out-of-process.  It is installed
    653  * next to the plugins, so we look where we look for them.
    654  *
    655  * @return full path of the helper, NULL if it was not found
    656  */
    657 char *
    658 EXTRACTOR_find_helper_ (void)
    659 {
    660   struct SearchContext sc;
    661 
    662   sc.path = NULL;
    663   sc.short_name = PLUGINHELPER;
    664   get_installation_paths (&find_helper_in_path,
    665                           &sc);
    666   /* LIBEXTRACTOR_PREFIX may only name directories with additional
    667      plugins, but the installed helper can run those as well */
    668   find_helper_in_path (&sc,
    669                        PLUGININSTDIR);
    670   return sc.path;
    671 }
    672 
    673 
    674 /**
    675  * Closure for #load_plugins_from_dir().
    676  */
    677 struct DefaultLoaderContext
    678 {
    679   /**
    680    * Accumulated result list.
    681    */
    682   struct EXTRACTOR_PluginList *res;
    683 
    684   /**
    685    * Flags to use for all plugins.
    686    */
    687   enum EXTRACTOR_Options flags;
    688 };
    689 
    690 
    691 /**
    692  * Load all plugins from the given directory.
    693  *
    694  * @param cls pointer to the "struct EXTRACTOR_PluginList*" to extend
    695  * @param path path to a directory with plugins
    696  */
    697 static void
    698 load_plugins_from_dir (void *cls,
    699                        const char *path)
    700 {
    701   struct DefaultLoaderContext *dlc = cls;
    702   DIR *dir;
    703   struct dirent *ent;
    704   const char *sym_name;
    705   char *sym;
    706   char *dot;
    707   size_t dlen;
    708 
    709   if (NULL == (dir = opendir (path)))
    710     return;
    711   while (NULL != (ent = readdir (dir)))
    712   {
    713     if (ent->d_name[0] == '.')
    714       continue;
    715     dlen = strlen (ent->d_name);
    716     if ( (dlen < 4) ||
    717          ( (0 != strcmp (&ent->d_name[dlen - 3], ".so")) &&
    718            (0 != strcasecmp (&ent->d_name[dlen - 4], ".dll")) ) )
    719       continue; /* only load '.so' and '.dll' */
    720     if (NULL == (sym_name = strrchr (ent->d_name, '_')))
    721       continue;
    722     sym_name++;
    723     if (NULL == (sym = strdup (sym_name)))
    724     {
    725       LOG_STRERROR ("strdup");
    726       closedir (dir);
    727       return;
    728     }
    729     if (NULL != (dot = strchr (sym, '.')))
    730       *dot = '\0';
    731     dlc->res = EXTRACTOR_plugin_add (dlc->res,
    732                                      sym,
    733                                      NULL,
    734                                      dlc->flags);
    735     free (sym);
    736   }
    737   closedir (dir);
    738 }
    739 
    740 
    741 /**
    742  * Load the default set of plugins. The default can be changed
    743  * by setting the LIBEXTRACTOR_LIBRARIES environment variable.
    744  * If it is set to "env", then this function will return
    745  * #EXTRACTOR_plugin_add_config(NULL, env, flags).  Otherwise,
    746  * it will load all of the installed plugins and return them.
    747  *
    748  * @param flags options for all of the plugins loaded
    749  * @return the default set of plugins, NULL if no plugins were found
    750  */
    751 struct EXTRACTOR_PluginList *
    752 EXTRACTOR_plugin_add_defaults (enum EXTRACTOR_Options flags)
    753 {
    754   struct DefaultLoaderContext dlc;
    755   char *env;
    756 
    757   env = getenv ("LIBEXTRACTOR_LIBRARIES");
    758   if (NULL != env)
    759     return EXTRACTOR_plugin_add_config (NULL, env, flags);
    760   dlc.res = NULL;
    761   dlc.flags = flags;
    762   get_installation_paths (&load_plugins_from_dir,
    763                           &dlc);
    764   return dlc.res;
    765 }
    766 
    767 
    768 /* end of extractor_plugpath.c */