Add ws_load_library and ws_module_open, which respectively call
[obnox/wireshark/wip.git] / epan / filesystem.c
index 4c6fc3c4618e76d038ee43e886bb440b882aa38c..b5e149029f75fd72d223335cbb48833f970db380 100644 (file)
 # include "config.h"
 #endif
 
+/*
+ * Required with GNU libc to get dladdr().
+ * We define it here because <dlfcn.h> apparently gets included by
+ * one of the headers we include below.
+ */
+#define _GNU_SOURCE
+
 #ifdef HAVE_DIRENT_H
 #include <dirent.h>
 #endif
 #include <unistd.h>
 #endif
 
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
 #ifdef HAVE_SYS_STAT_H
 #include <sys/stat.h>
 #endif
 #include <tchar.h>
 #include <shlobj.h>
 #include <wsutil/unicode-utils.h>
-#else
+#else /* _WIN32 */
+#ifdef DLADDR_FINDS_EXECUTABLE_PATH
+#include <dlfcn.h>
+#endif /* DLADDR_FINDS_EXECUTABLE_PATH */
 #include <pwd.h>
-#endif
+#endif /* _WIN32 */
 
 #include "filesystem.h"
+#include "report_err.h"
 #include <wsutil/privileges.h>
 #include <wsutil/file_util.h>
 
+#include <wiretap/wtap.h>      /* for WTAP_ERR_SHORT_WRITE */
+
 #define PROFILES_DIR    "profiles"
+#define PLUGINS_DIR_NAME    "plugins"
+
 #define U3_MY_CAPTURES  "\\My Captures"
 
 char *persconffile_dir = NULL;
 char *persdatafile_dir = NULL;
 char *persconfprofile = NULL;
 
+static gboolean do_store_persconffiles = FALSE;
+static GHashTable *profile_files = NULL;
+
 /*
  * Given a pathname, return a pointer to the last pathname separator
  * character in the pathname, or NULL if the pathname contains no
  * separators.
  */
-static char *
+char *
 find_last_pathname_separator(const char *path)
 {
        char *separator;
@@ -239,6 +261,10 @@ init_progfile_dir(const char *arg0
 #ifdef _WIN32
        _U_
 #endif
+, int (*main_addr)(int, char **)
+#if defined(_WIN32) || !defined(DLADDR_FINDS_EXECUTABLE_PATH)
+       _U_
+#endif
 )
 {
        char *dir_end;
@@ -246,22 +272,22 @@ init_progfile_dir(const char *arg0
 #ifdef _WIN32
        TCHAR prog_pathname_w[_MAX_PATH+2];
        size_t progfile_dir_len;
-        char *prog_pathname;
-        DWORD error;
-        TCHAR *msg_w;
-        guchar *msg;
-        size_t msglen;
+       char *prog_pathname;
+       DWORD error;
+       TCHAR *msg_w;
+       guchar *msg;
+       size_t msglen;
 
        /*
         * Attempt to get the full pathname of the currently running
         * program.
         */
-       if (GetModuleFileName(NULL, prog_pathname_w, sizeof prog_pathname_w) != 0) {
-                /*
-                 * XXX - Should we use g_utf16_to_utf8(), as in
-                 * getenv_utf8()?
-                 */
-                prog_pathname = utf_16to8(prog_pathname_w);
+       if (GetModuleFileName(NULL, prog_pathname_w, G_N_ELEMENTS(prog_pathname_w)) != 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
+               /*
+                * XXX - Should we use g_utf16_to_utf8(), as in
+                * getenv_utf8()?
+                */
+               prog_pathname = utf_16to8(prog_pathname_w);
                /*
                 * We got it; strip off the last component, which would be
                 * the file name of the executable, giving us the pathname
@@ -327,6 +353,9 @@ init_progfile_dir(const char *arg0
                    msg, error);
        }
 #else
+#ifdef DLADDR_FINDS_EXECUTABLE_PATH
+       Dl_info info;
+#endif
        char *prog_pathname;
        char *curdir;
        long path_max;
@@ -348,10 +377,24 @@ init_progfile_dir(const char *arg0
            && !started_with_special_privs())
                running_in_build_directory_flag = TRUE;
 
+#ifdef DLADDR_FINDS_EXECUTABLE_PATH
+       /*
+        * Try to use dladdr() to find the pathname of the executable.
+        * dladdr() is not guaranteed to give you anything better than
+        * argv[0] (i.e., it might not contain a / at all, much less
+        * being an absolute path), and doesn't appear to do so on
+        * Linux, but on other platforms it could give you an absolute
+        * path and obviate the need for us to determine the absolute
+        * path.
+        */
+       if (dladdr((void *)main_addr, &info))
+               arg0 = info.dli_fname;
+#endif
        /*
         * Try to figure out the directory in which the currently running
-        * program resides, given the argv[0] it was started with.  That
-        * might be the absolute path of the program, or a path relative
+        * program resides, given something purporting to be the executable
+        * name (from dladdr() or from the argv[0] it was started with.
+        * That might be the absolute path of the program, or a path relative
         * to the current directory of the process that started it, or
         * just a name for the program if it was started from the command
         * line and was searched for in $PATH.  It's not guaranteed to be
@@ -377,7 +420,7 @@ init_progfile_dir(const char *arg0
                        return g_strdup_printf("pathconf failed: %s\n",
                            strerror(errno));
                }
-               curdir = g_malloc(path_max);
+               curdir = (char *)g_malloc(path_max);
                if (getcwd(curdir, path_max) == NULL) {
                        /*
                         * It failed - give up, and just stick
@@ -405,7 +448,7 @@ init_progfile_dir(const char *arg0
                                if (path_end == NULL)
                                        path_end = path_start + strlen(path_start);
                                path_component_len = path_end - path_start;
-                               path = g_malloc(path_component_len + 1
+                               path = (char *)g_malloc(path_component_len + 1
                                    + strlen(arg0) + 1);
                                memcpy(path, path_start, path_component_len);
                                path[path_component_len] = '\0';
@@ -560,7 +603,7 @@ get_datafile_dir(void)
 #ifdef _WIN32
        char *u3deviceexecpath;
 #endif
-       static char *datafile_dir = NULL;
+       static const char *datafile_dir = NULL;
 
        if (datafile_dir != NULL)
                return datafile_dir;
@@ -631,7 +674,103 @@ get_datafile_dir(void)
        return datafile_dir;
 }
 
-#ifdef HAVE_PLUGINS
+#ifdef HAVE_PYTHON
+/*
+ * Find the directory where the python dissectors are stored.
+ *
+ * On Windows, we use the "py_dissector" subdirectory of the datafile directory.
+ *
+ * On UN*X, we use the PYTHON_DIR value supplied by the configure
+ * script, unless we think we're being run from the build directory,
+ * in which case we use the "py_dissector" subdirectory of the datafile directory.
+ *
+ * In both cases, we then use the subdirectory of that directory whose
+ * name is the version number.
+ *
+ * XXX - if we think we're being run from the build directory, perhaps we
+ * should have the plugin code not look in the version subdirectory
+ * of the plugin directory, but look in all of the subdirectories
+ * of the plugin directory, so it can just fetch the plugins built
+ * as part of the build process.
+ */
+static const char *wspython_dir = NULL;
+
+static void
+init_wspython_dir(void)
+{
+#ifdef _WIN32
+       /*
+        * On Windows, the data file directory is the installation
+        * directory; the python dissectors are stored under it.
+        *
+        * Assume we're running the installed version of Wireshark;
+        * on Windows, the data file directory is the directory
+        * in which the Wireshark binary resides.
+        */
+        wspython_dir = g_strdup_printf("%s\\python\\%s", get_datafile_dir(),
+                                        VERSION);
+
+       /*
+        * Make sure that pathname refers to a directory.
+        */
+       if (test_for_directory(wspython_dir) != EISDIR) {
+               /*
+                * Either it doesn't refer to a directory or it
+                * refers to something that doesn't exist.
+                *
+                * Assume that means we're running a version of
+                * Wireshark we've built in a build directory,
+                * in which case {datafile dir}\python is the
+                * top-level plugins source directory, and use
+                * that directory and set the "we're running in
+                * a build directory" flag, so the plugin
+                * scanner will check all subdirectories of that
+                * directory for python dissectors.
+                */
+               g_free( (gpointer) wspython_dir);
+               wspython_dir = g_strdup_printf("%s\\python", get_datafile_dir());
+               running_in_build_directory_flag = TRUE;
+       }
+#else
+       if (running_in_build_directory_flag) {
+               /*
+                * We're (probably) being run from the build directory and
+                * weren't started with special privileges, so we'll use
+                * the "python" subdirectory of the datafile directory
+                * (the datafile directory is the build directory).
+                */
+               wspython_dir = g_strdup_printf("%s/epan/wspython/", get_datafile_dir());
+       } else {
+               if (getenv("WIRESHARK_PYTHON_DIR") && !started_with_special_privs()) {
+                       /*
+                        * The user specified a different directory for plugins
+                        * and we aren't running with special privileges.
+                        */
+                       wspython_dir = g_strdup(getenv("WIRESHARK_PYTHON_DIR"));
+               } else {
+                       wspython_dir = PYTHON_DIR;
+               }
+       }
+#endif
+}
+#endif /* HAVE_PYTHON */
+
+/*
+ * Get the directory in which the python dissectors are stored.
+ */
+const char *
+get_wspython_dir(void)
+{
+#ifdef HAVE_PYTHON
+       if (!wspython_dir) init_wspython_dir();
+       return wspython_dir;
+#else
+       return NULL;
+#endif
+}
+
+
+#if defined(HAVE_PLUGINS) || defined(HAVE_LUA_5_1)
 /*
  * Find the directory where the plugins are stored.
  *
@@ -710,7 +849,7 @@ init_plugin_dir(void)
        }
 #endif
 }
-#endif /* HAVE_PLUGINS */
+#endif /* HAVE_PLUGINS || HAVE_LUA_5_1 */
 
 /*
  * Get the directory in which the plugins are stored.
@@ -718,7 +857,7 @@ init_plugin_dir(void)
 const char *
 get_plugin_dir(void)
 {
-#ifdef HAVE_PLUGINS
+#if defined(HAVE_PLUGINS) || defined(HAVE_LUA_5_1)
        if (!plugin_dir) init_plugin_dir();
        return plugin_dir;
 #else
@@ -805,9 +944,7 @@ char *getenv_utf8(const char *varname)
 void
 set_profile_name(const gchar *profilename)
 {
-       if (persconfprofile) {
-               g_free (persconfprofile);
-       }
+       g_free (persconfprofile);
 
        if (profilename && strlen(profilename) > 0 &&
            strcmp(profilename, DEFAULT_PROFILE) != 0) {
@@ -828,6 +965,15 @@ get_profile_name(void)
        }
 }
 
+void
+profile_store_persconffiles(gboolean store)
+{
+       if (store) {
+               profile_files = g_hash_table_new (g_str_hash, g_str_equal);
+       }
+       do_store_persconffiles = store;
+}
+
 /*
  * Get the directory in which personal configuration files reside;
  * in UNIX-compatible systems, it's ".wireshark", under the user's home
@@ -927,10 +1073,7 @@ get_profiles_dir(void)
 {
        static char *profiles_dir = NULL;
 
-       if (profiles_dir) {
-               g_free (profiles_dir);
-       }
-
+       g_free (profiles_dir);
        profiles_dir = g_strdup_printf ("%s%s%s", get_persconffile_dir_no_profile (),
                                        G_DIR_SEPARATOR_S, PROFILES_DIR);
 
@@ -942,16 +1085,14 @@ get_persconffile_dir(const gchar *profilename)
 {
        static char *persconffile_profile_dir = NULL;
 
-       if (persconffile_profile_dir) {
-               g_free (persconffile_profile_dir);
-       }
+       g_free (persconffile_profile_dir);
 
        if (profilename && strlen(profilename) > 0 &&
            strcmp(profilename, DEFAULT_PROFILE) != 0) {
          persconffile_profile_dir = g_strdup_printf ("%s%s%s", get_profiles_dir (),
                                                      G_DIR_SEPARATOR_S, profilename);
        } else {
-         persconffile_profile_dir = g_strdup_printf (get_persconffile_dir_no_profile ());
+         persconffile_profile_dir = g_strdup (get_persconffile_dir_no_profile ());
        }
 
        return persconffile_profile_dir;
@@ -1124,15 +1265,69 @@ create_persconffile_dir(char **pf_dir_path_return)
   return create_persconffile_profile(persconfprofile, pf_dir_path_return);
 }
 
+#if ! GLIB_CHECK_VERSION(2,14,0)
+static void
+hash_table_get_keys(gpointer key, gpointer value _U_, gpointer user_data)
+{
+       GList **files = ((GList **)user_data);
+       *files = g_list_append (*files, key);
+}
+#endif
+
+int
+copy_persconffile_profile(const char *toname, const char *fromname, char **pf_filename_return,
+                           char **pf_to_dir_path_return, char **pf_from_dir_path_return)
+{
+       gchar *from_dir = g_strdup (get_persconffile_dir(fromname));
+       gchar *to_dir = g_strdup (get_persconffile_dir(toname));
+       gchar *filename, *from_file, *to_file;
+       GList *files, *file;
+
+#if GLIB_CHECK_VERSION(2,14,0)
+       files = g_hash_table_get_keys(profile_files);
+#else
+       files = NULL;
+       g_hash_table_foreach(profile_files, hash_table_get_keys, &files);
+#endif
+
+       file = g_list_first(files);
+       while (file) {
+               filename = (gchar *)file->data;
+               from_file = g_strdup_printf ("%s%s%s", from_dir, G_DIR_SEPARATOR_S, filename);
+               to_file =  g_strdup_printf ("%s%s%s", to_dir, G_DIR_SEPARATOR_S, filename);
+
+               if (file_exists(from_file) && !copy_file_binary_mode(from_file, to_file)) {
+                       *pf_filename_return = g_strdup(filename);
+                       *pf_to_dir_path_return = to_dir;
+                       *pf_from_dir_path_return = from_dir;
+                       g_free (from_file);
+                       g_free (to_file);
+                       return -1;
+               }
+
+               g_free (from_file);
+               g_free (to_file);
+
+               file = g_list_next(file);
+       }
+
+       g_list_free (files);
+       g_free (from_dir);
+       g_free (to_dir);
+
+       return 0;
+}
+
 /*
  * Get the (default) directory in which personal data is stored.
  *
- * On Win32, this is the "My Documents" folder in the personal profile.
+ * On Win32, this is the "My Documents" folder in the personal profile,
+ * except that, if we're running from a U3 device, this is the
+ * "$U3_DEVICE_DOCUMENT_PATH\My Captures" folder.
  * On UNIX this is simply the current directory.
- * On a U3 device this is "$U3_DEVICE_DOCUMENT_PATH\My Captures" folder.
  */
 /* XXX - should this and the get_home_dir() be merged? */
-extern char *
+extern const char *
 get_persdatafile_dir(void)
 {
 #ifdef _WIN32
@@ -1141,7 +1336,6 @@ get_persdatafile_dir(void)
        char *szPath;
        BOOL bRet;
 
-
        /* Return the cached value, if available */
        if (persdatafile_dir != NULL)
                return persdatafile_dir;
@@ -1152,28 +1346,30 @@ get_persdatafile_dir(void)
        u3devicedocumentpath = getenv_utf8("U3_DEVICE_DOCUMENT_PATH");
 
        if (u3devicedocumentpath != NULL) {
+               /* the "My Captures" sub-directory is created (if it doesn't
+                  exist) by u3util.exe when the U3 Wireshark is first run */
 
-         /* the "My Captures" sub-directory is created (if it doesn't exist)
-                by u3util.exe when the U3 Wireshark is first run */
-
-         szPath = g_strdup_printf("%s%s", u3devicedocumentpath, U3_MY_CAPTURES);
+               szPath = g_strdup_printf("%s%s", u3devicedocumentpath, U3_MY_CAPTURES);
 
-         persdatafile_dir = szPath;
-         return szPath;
-
-               } else {
-       /* Hint: SHGetFolderPath is not available on MSVC 6 - without Platform SDK */
-       bRet = SHGetSpecialFolderPath(NULL, tszPath, CSIDL_PERSONAL, FALSE);
-       if(bRet == TRUE) {
-               szPath = utf_16to8(tszPath);
                persdatafile_dir = szPath;
                return szPath;
        } else {
-               return "";
+               /*
+                * Hint: SHGetFolderPath is not available on MSVC 6 - without
+                * Platform SDK
+                */
+               bRet = SHGetSpecialFolderPath(NULL, tszPath, CSIDL_PERSONAL,
+                   FALSE);
+               if(bRet == TRUE) {
+                       szPath = utf_16to8(tszPath);
+                       persdatafile_dir = szPath;
+                       return szPath;
+               } else {
+                       return "";
+               }
        }
-}
 #else
-  return "";
+       return "";
 #endif
 }
 
@@ -1258,6 +1454,10 @@ get_persconffile_path(const char *filename, gboolean from_profile, gboolean for_
        struct stat s_buf;
        char *old_path;
 #endif
+       if (do_store_persconffiles && from_profile && !g_hash_table_lookup (profile_files, filename)) {
+               /* Store filenames so we know which filenames belongs to a configuration profile */
+               g_hash_table_insert (profile_files, g_strdup(filename), g_strdup(filename));
+       }
 
        if (from_profile) {
          path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
@@ -1364,6 +1564,14 @@ get_datafile_path(const char *filename)
                filename);
 }
 
+/* Get the personal plugin dir */
+/* Return value is malloced so the caller should g_free() it. */
+char *
+get_plugins_pers_dir(void)
+{
+    return get_persconffile_path(PLUGINS_DIR_NAME, FALSE, FALSE);
+}
+
 /* Delete a file */
 gboolean
 deletefile(const char *path)
@@ -1457,6 +1665,10 @@ file_write_error_message(int err)
                break;
 #endif
 
+       case WTAP_ERR_SHORT_WRITE:
+               errmsg = "A full write couldn't be done to the file \"%s\".";
+               break;
+
        default:
                g_snprintf(errmsg_errno, sizeof(errmsg_errno),
                    "An error occurred while writing to the file \"%%s\": %s.",
@@ -1552,6 +1764,72 @@ files_identical(const char *fname1, const char *fname2)
 #endif
 }
 
+/*
+ * Copy a file in binary mode, for those operating systems that care about
+ * such things.  This should be OK for all files, even text files, as
+ * we'll copy the raw bytes, and we don't look at the bytes as we copy
+ * them.
+ *
+ * Returns TRUE on success, FALSE on failure. If a failure, it also
+ * displays a simple dialog window with the error message.
+ */
+gboolean
+copy_file_binary_mode(const char *from_filename, const char *to_filename)
+{
+  int           from_fd, to_fd, nread, nwritten, err;
+  guint8        pd[65536];
+
+  /* Copy the raw bytes of the file. */
+  from_fd = ws_open(from_filename, O_RDONLY | O_BINARY, 0000 /* no creation so don't matter */);
+  if (from_fd < 0) {
+    report_open_failure(from_filename, errno, FALSE);
+    goto done;
+  }
+
+  /* Use open() instead of creat() so that we can pass the O_BINARY
+     flag, which is relevant on Win32; it appears that "creat()"
+     may open the file in text mode, not binary mode, but we want
+     to copy the raw bytes of the file, so we need the output file
+     to be open in binary mode. */
+  to_fd = ws_open(to_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
+  if (to_fd < 0) {
+    report_open_failure(to_filename, errno, TRUE);
+    ws_close(from_fd);
+    goto done;
+  }
+
+  while ((nread = ws_read(from_fd, pd, sizeof pd)) > 0) {
+    nwritten = ws_write(to_fd, pd, nread);
+    if (nwritten < nread) {
+      if (nwritten < 0)
+       err = errno;
+      else
+       err = WTAP_ERR_SHORT_WRITE;
+      report_write_failure(to_filename, err);
+      ws_close(from_fd);
+      ws_close(to_fd);
+      goto done;
+    }
+  }
+  if (nread < 0) {
+    err = errno;
+    report_read_failure(from_filename, err);
+    ws_close(from_fd);
+    ws_close(to_fd);
+    goto done;
+  }
+  ws_close(from_fd);
+  if (ws_close(to_fd) < 0) {
+    report_write_failure(to_filename, errno);
+    goto done;
+  }
+
+  return TRUE;
+
+done:
+  return FALSE;
+}
+
 /*
  * Editor modelines
  *
@@ -1564,4 +1842,3 @@ files_identical(const char *fname1, const char *fname2)
  * ex: set shiftwidth=4 tabstop=4 noexpandtab
  * :indentSize=4:tabSize=4:noTabs=false:
  */
-