HACK: pinfo->private_data points to smb_info again
[wireshark-wip.git] / epan / filesystem.c
blobfa292da4ce664add96df5e7beed129ad2fc97603
1 /* filesystem.c
2 * Filesystem utility routines
4 * $Id$
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "config.h"
28 * Required with GNU libc to get dladdr().
29 * We define it here because <dlfcn.h> apparently gets included by
30 * one of the headers we include below.
32 #define _GNU_SOURCE
34 #ifdef HAVE_DIRENT_H
35 #include <dirent.h>
36 #endif
38 #include <stdio.h>
39 #include <ctype.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <errno.h>
44 #include <glib.h>
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
50 #ifdef HAVE_FCNTL_H
51 #include <fcntl.h>
52 #endif
54 #ifdef HAVE_SYS_STAT_H
55 #include <sys/stat.h>
56 #endif
58 #ifdef _WIN32
59 #include <windows.h>
60 #include <tchar.h>
61 #include <shlobj.h>
62 #include <wsutil/unicode-utils.h>
63 #else /* _WIN32 */
64 #ifdef __APPLE__
65 #include <mach-o/dyld.h>
66 #endif
67 #ifdef __linux__
68 #include <sys/utsname.h>
69 #endif
70 #ifdef __FreeBSD__
71 #include <sys/types.h>
72 #include <sys/sysctl.h>
73 #endif
74 #ifdef HAVE_DLADDR
75 #include <dlfcn.h>
76 #endif
77 #include <pwd.h>
78 #endif /* _WIN32 */
80 #include "filesystem.h"
81 #include <wsutil/report_err.h>
82 #include <wsutil/privileges.h>
83 #include <wsutil/file_util.h>
85 #include <wiretap/wtap.h> /* for WTAP_ERR_SHORT_WRITE */
87 #define PROFILES_DIR "profiles"
88 #define PLUGINS_DIR_NAME "plugins"
90 #define U3_MY_CAPTURES "\\My Captures"
92 char *persconffile_dir = NULL;
93 char *persdatafile_dir = NULL;
94 char *persconfprofile = NULL;
96 static gboolean do_store_persconffiles = FALSE;
97 static GHashTable *profile_files = NULL;
100 * Given a pathname, return a pointer to the last pathname separator
101 * character in the pathname, or NULL if the pathname contains no
102 * separators.
104 char *
105 find_last_pathname_separator(const char *path)
107 char *separator;
109 #ifdef _WIN32
110 char c;
113 * We have to scan for '\' or '/'.
114 * Get to the end of the string.
116 separator = strchr(path, '\0'); /* points to ending '\0' */
117 while (separator > path) {
118 c = *--separator;
119 if (c == '\\' || c == '/')
120 return separator; /* found it */
124 * OK, we didn't find any, so no directories - but there might
125 * be a drive letter....
127 return strchr(path, ':');
128 #else
129 separator = strrchr(path, '/');
130 return separator;
131 #endif
135 * Given a pathname, return the last component.
137 const char *
138 get_basename(const char *path)
140 const char *filename;
142 g_assert(path != NULL);
143 filename = find_last_pathname_separator(path);
144 if (filename == NULL) {
146 * There're no directories, drive letters, etc. in the
147 * name; the pathname *is* the file name.
149 filename = path;
150 } else {
152 * Skip past the pathname or drive letter separator.
154 filename++;
156 return filename;
160 * Given a pathname, return a string containing everything but the
161 * last component. NOTE: this overwrites the pathname handed into
162 * it....
164 char *
165 get_dirname(char *path)
167 char *separator;
169 g_assert(path != NULL);
170 separator = find_last_pathname_separator(path);
171 if (separator == NULL) {
173 * There're no directories, drive letters, etc. in the
174 * name; there is no directory path to return.
176 return NULL;
180 * Get rid of the last pathname separator and the final file
181 * name following it.
183 *separator = '\0';
186 * "path" now contains the pathname of the directory containing
187 * the file/directory to which it referred.
189 return path;
193 * Given a pathname, return:
195 * the errno, if an attempt to "stat()" the file fails;
197 * EISDIR, if the attempt succeeded and the file turned out
198 * to be a directory;
200 * 0, if the attempt succeeded and the file turned out not
201 * to be a directory.
205 * Visual C++ on Win32 systems doesn't define these. (Old UNIX systems don't
206 * define them either.)
208 * Visual C++ on Win32 systems doesn't define S_IFIFO, it defines _S_IFIFO.
210 #ifndef S_ISREG
211 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
212 #endif
213 #ifndef S_IFIFO
214 #define S_IFIFO _S_IFIFO
215 #endif
216 #ifndef S_ISFIFO
217 #define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)
218 #endif
219 #ifndef S_ISDIR
220 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
221 #endif
224 test_for_directory(const char *path)
226 ws_statb64 statb;
228 if (ws_stat64(path, &statb) < 0)
229 return errno;
231 if (S_ISDIR(statb.st_mode))
232 return EISDIR;
233 else
234 return 0;
238 test_for_fifo(const char *path)
240 ws_statb64 statb;
242 if (ws_stat64(path, &statb) < 0)
243 return errno;
245 if (S_ISFIFO(statb.st_mode))
246 return ESPIPE;
247 else
248 return 0;
252 * Directory from which the executable came.
254 static char *progfile_dir;
256 #ifdef __APPLE__
258 * Directory of the application bundle in which we're contained,
259 * if we're contained in an application bundle. Otherwise, NULL.
261 * Note: Table 2-5 "Subdirectories of the Contents directory" of
263 * https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html#//apple_ref/doc/uid/10000123i-CH101-SW1
265 * says that the "Frameworks" directory
267 * Contains any private shared libraries and frameworks used by the
268 * executable. The frameworks in this directory are revision-locked
269 * to the application and cannot be superseded by any other, even
270 * newer, versions that may be available to the operating system. In
271 * other words, the frameworks included in this directory take precedence
272 * over any other similarly named frameworks found in other parts of
273 * the operating system. For information on how to add private
274 * frameworks to your application bundle, see Framework Programming Guide.
276 * so if we were to ship with any frameworks (e.g. Qt) we should
277 * perhaps put them in a Frameworks directory rather than under
278 * Resources.
280 * It also says that the "PlugIns" directory
282 * Contains loadable bundles that extend the basic features of your
283 * application. You use this directory to include code modules that
284 * must be loaded into your applicationbs process space in order to
285 * be used. You would not use this directory to store standalone
286 * executables.
288 * Our plugins are just raw .so/.dylib files; I don't know whether by
289 * "bundles" they mean application bundles (i.e., directory hierarchies)
290 * or just "bundles" in the Mach-O sense (which are an image type that
291 * can be loaded with dlopen() but not linked as libraries; our plugins
292 * are, I think, built as dylibs and can be loaded either way).
294 * And it says that the "SharedSupport" directory
296 * Contains additional non-critical resources that do not impact the
297 * ability of the application to run. You might use this directory to
298 * include things like document templates, clip art, and tutorials
299 * that your application expects to be present but that do not affect
300 * the ability of your application to run.
302 * I don't think I'd put the files that currently go under Resources/share
303 * into that category; they're not, for example, sample Lua scripts that
304 * don't actually get run by Wireshark, they're configuration/data files
305 * for Wireshark whose absence might not prevent Wireshark from running
306 * but that would affect how it behaves when run.
308 static char *appbundle_dir;
309 #endif
312 * TRUE if we're running from the build directory and we aren't running
313 * with special privileges.
315 static gboolean running_in_build_directory_flag = FALSE;
317 #ifndef _WIN32
319 * Get the pathname of the executable using various platform-
320 * dependent mechanisms for various UN*Xes.
322 * These calls all should return something independent of the argv[0]
323 * passed to the program, so it shouldn't be fooled by an argv[0]
324 * that doesn't match the executable path.
326 * Sadly, not all UN*Xes necessarily have dladdr(), and those that
327 * do don't necessarily have dladdr(main) return information about
328 * the executable image, and those that do aren't necessarily running
329 * on a platform wherein the executable image can get its own path
330 * from the kernel (either by a call or by it being handed to it along
331 * with argv[] and the environment), and those that can don't
332 * necessarily use that to supply the path you get from dladdr(main),
333 * so we try this first and, if that fails, use dladdr(main) if
334 * available.
336 * In particular, some dynamic linkers supply a dladdr() such that
337 * dladdr(main) just returns something derived from argv[0], so
338 * just using dladdr(main) is the wrong thing to do if there's
339 * another mechanism that can get you a more reliable version of
340 * the executable path.
342 * However, at least in newer versions of DragonFly BSD, the dynamic
343 * linker *does* get it from the aux vector passed to the program
344 * by the kernel, readlink /proc/curproc/file - which came first?
346 * On OpenBSD, dladdr(main) returns a value derived from argv[0],
347 * and there doesn't appear to be any way to get the executable path
348 * from the kernel, so we're out of luck there.
350 * So, on platforms where some versions have a version of dladdr()
351 * that gives an argv[0]-based path and that also have a mechanism
352 * to get a more reliable version of the path, we try that. On
353 * other platforms, we return NULL. If our caller gets back a NULL
354 * from us, it falls back on dladdr(main) if dladdr() is available,
355 * and if that fails or is unavailable, it falls back on processing
356 * argv[0] itself.
358 * This is not guaranteed to return an absolute path; if it doesn't,
359 * our caller must prepend the current directory if it's a path.
361 * This is not guaranteed to return the "real path"; it might return
362 * something with symbolic links in the path. Our caller must
363 * use realpath() if they want the real thing, but that's also true of
364 * something obtained by looking at argv[0].
366 const char *
367 get_executable_path(void)
369 #if defined(__APPLE__)
370 char *executable_path;
371 uint32_t path_buf_size;
373 path_buf_size = PATH_MAX;
374 executable_path = (char *)g_malloc(path_buf_size);
375 if (_NSGetExecutablePath(executable_path, &path_buf_size) == -1) {
376 executable_path = (char *)g_realloc(executable_path, path_buf_size);
377 if (_NSGetExecutablePath(executable_path, &path_buf_size) == -1)
378 return NULL;
380 return executable_path;
381 #elif defined(__linux__)
383 * In older versions of GNU libc's dynamic linker, as used on Linux,
384 * dladdr(main) supplies a path based on argv[0], so we use
385 * /proc/self/exe instead; there are Linux distributions with
386 * kernels that support /proc/self/exe and those older versions
387 * of the dynamic linker, and this will get a better answer on
388 * those versions.
390 * It only works on Linux 2.2 or later, so we just give up on
391 * earlier versions.
393 * XXX - are there OS versions that support "exe" but not "self"?
395 struct utsname name;
396 static char executable_path[PATH_MAX];
398 if (uname(&name) == -1)
399 return NULL;
400 if (strncmp(name.release, "1.", 2) == 0)
401 return NULL; /* Linux 1.x */
402 if (strcmp(name.release, "2.0") == 0 ||
403 strncmp(name.release, "2.0.", 4) == 0 ||
404 strcmp(name.release, "2.1") == 0 ||
405 strncmp(name.release, "2.1.", 4) == 0)
406 return NULL; /* Linux 2.0.x or 2.1.x */
407 if (readlink("/proc/self/exe", executable_path, sizeof executable_path) == -1)
408 return NULL;
409 return executable_path;
410 #elif defined(__FreeBSD__) && defined(KERN_PROC_PATHNAME)
412 * In older versions of FreeBSD's dynamic linker, dladdr(main)
413 * supplies a path based on argv[0], so we use the KERN_PROC_PATHNAME
414 * sysctl instead; there are, I think, versions of FreeBSD
415 * that support the sysctl that have and those older versions
416 * of the dynamic linker, and this will get a better answer on
417 * those versions.
419 int mib[4];
420 char *executable_path;
421 size_t path_buf_size;
423 mib[0] = CTL_KERN;
424 mib[1] = KERN_PROC;
425 mib[2] = KERN_PROC_PATHNAME;
426 mib[3] = -1;
427 path_buf_size = PATH_MAX;
428 executable_path = (char *)g_malloc(path_buf_size);
429 if (sysctl(mib, 4, executable_path, &path_buf_size, NULL, 0) == -1) {
430 if (errno != ENOMEM)
431 return NULL;
432 executable_path = (char *)g_realloc(executable_path, path_buf_size);
433 if (sysctl(mib, 4, executable_path, &path_buf_size, NULL, 0) == -1)
434 return NULL;
436 return executable_path;
437 #elif defined(__NetBSD__)
439 * In all versions of NetBSD's dynamic linker as of 2013-08-12,
440 * dladdr(main) supplies a path based on argv[0], so we use
441 * /proc/curproc/exe instead.
443 * XXX - are there OS versions that support "exe" but not "curproc"
444 * or "self"? Are there any that support "self" but not "curproc"?
446 static char executable_path[PATH_MAX];
448 if (readlink("/proc/curproc/exe", executable_path, sizeof executable_path) == -1)
449 return NULL;
450 return executable_path;
451 #elif defined(__DragonFly__)
453 * In older versions of DragonFly BSD's dynamic linker, dladdr(main)
454 * supplies a path based on argv[0], so we use /proc/curproc/file
455 * instead; it appears to be supported by all versions of DragonFly
456 * BSD.
458 static char executable_path[PATH_MAX];
460 if (readlink("/proc/curproc/file", executable_path, sizeof executable_path) == -1)
461 return NULL;
462 return executable_path;
463 #elif (defined(sun) || defined(__sun)) && defined(HAVE_GETEXECNAME)
465 * It appears that getexecname() dates back to at least Solaris 8,
466 * but /proc/{pid}/path is first documented in the Solaris 10 documentation,
467 * so we use getexecname() if available, rather than /proc/self/path/a.out
468 * (which isn't documented, but appears to be a symlink to the
469 * executable image file).
471 return getexecname();
472 #else
473 /* Fill in your favorite UN*X's code here, if there is something */
474 return NULL;
475 #endif
477 #endif /* _WIN32 */
480 * Get the pathname of the directory from which the executable came,
481 * and save it for future use. Returns NULL on success, and a
482 * g_mallocated string containing an error on failure.
484 char *
485 init_progfile_dir(const char *arg0
486 #ifdef _WIN32
488 #endif
489 , int (*main_addr)(int, char **)
490 #if defined(_WIN32) || !defined(HAVE_DLADDR)
492 #endif
495 #ifdef _WIN32
496 TCHAR prog_pathname_w[_MAX_PATH+2];
497 char *prog_pathname;
498 DWORD error;
499 TCHAR *msg_w;
500 guchar *msg;
501 size_t msglen;
504 * Attempt to get the full pathname of the currently running
505 * program.
507 if (GetModuleFileName(NULL, prog_pathname_w, G_N_ELEMENTS(prog_pathname_w)) != 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
509 * XXX - Should we use g_utf16_to_utf8(), as in
510 * getenv_utf8()?
512 prog_pathname = utf_16to8(prog_pathname_w);
514 * We got it; strip off the last component, which would be
515 * the file name of the executable, giving us the pathname
516 * of the directory where the executable resides.
518 progfile_dir = g_path_get_dirname(prog_pathname);
519 if (progfile_dir != NULL) {
520 return NULL; /* we succeeded */
521 } else {
523 * OK, no. What do we do now?
525 return g_strdup_printf("No \\ in executable pathname \"%s\"",
526 prog_pathname);
528 } else {
530 * Oh, well. Return an indication of the error.
532 error = GetLastError();
533 if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
534 NULL, error, 0, (LPTSTR) &msg_w, 0, NULL) == 0) {
536 * Gak. We can't format the message.
538 return g_strdup_printf("GetModuleFileName failed: %u (FormatMessage failed: %u)",
539 error, GetLastError());
541 msg = utf_16to8(msg_w);
542 LocalFree(msg_w);
544 * "FormatMessage()" "helpfully" sticks CR/LF at the
545 * end of the message. Get rid of it.
547 msglen = strlen(msg);
548 if (msglen >= 2) {
549 msg[msglen - 1] = '\0';
550 msg[msglen - 2] = '\0';
552 return g_strdup_printf("GetModuleFileName failed: %s (%u)",
553 msg, error);
555 #else
556 #ifdef HAVE_DLADDR
557 Dl_info info;
558 #endif
559 const char *execname;
560 char *prog_pathname;
561 char *curdir;
562 long path_max;
563 char *pathstr;
564 char *path_start, *path_end;
565 size_t path_component_len;
566 char *retstr;
567 char *path;
568 char *dir_end;
571 * Check whether WIRESHARK_RUN_FROM_BUILD_DIRECTORY is set in the
572 * environment; if so, set running_in_build_directory_flag if we
573 * weren't started with special privileges. (If we were started
574 * with special privileges, it's not safe to allow the user to point
575 * us to some other directory; running_in_build_directory_flag, when
576 * set, causes us to look for plugins and the like in the build
577 * directory.)
579 if (getenv("WIRESHARK_RUN_FROM_BUILD_DIRECTORY") != NULL
580 && !started_with_special_privs())
581 running_in_build_directory_flag = TRUE;
583 execname = get_executable_path();
584 #ifdef HAVE_DLADDR
585 if (main_addr != NULL && execname == NULL) {
587 * Try to use dladdr() to find the pathname of the executable.
588 * dladdr() is not guaranteed to give you anything better than
589 * argv[0] (i.e., it might not contain a / at all, much less
590 * being an absolute path), and doesn't appear to do so on
591 * Linux, but on other platforms it could give you an absolute
592 * path and obviate the need for us to determine the absolute
593 * path.
595 if (dladdr((void *)main_addr, &info))
596 execname = info.dli_fname;
598 #endif
599 if (execname == NULL) {
601 * OK, guess based on argv[0].
603 execname = arg0;
607 * Try to figure out the directory in which the currently running
608 * program resides, given something purporting to be the executable
609 * name (from dladdr() or from the argv[0] it was started with.
610 * That might be the absolute path of the program, or a path relative
611 * to the current directory of the process that started it, or
612 * just a name for the program if it was started from the command
613 * line and was searched for in $PATH. It's not guaranteed to be
614 * any of those, however, so there are no guarantees....
616 if (execname[0] == '/') {
618 * It's an absolute path.
620 prog_pathname = g_strdup(execname);
621 } else if (strchr(execname, '/') != NULL) {
623 * It's a relative path, with a directory in it.
624 * Get the current directory, and combine it
625 * with that directory.
627 path_max = pathconf(".", _PC_PATH_MAX);
628 if (path_max == -1) {
630 * We have no idea how big a buffer to
631 * allocate for the current directory.
633 return g_strdup_printf("pathconf failed: %s\n",
634 g_strerror(errno));
636 curdir = (char *)g_malloc(path_max);
637 if (getcwd(curdir, path_max) == NULL) {
639 * It failed - give up, and just stick
640 * with DATAFILE_DIR.
642 g_free(curdir);
643 return g_strdup_printf("getcwd failed: %s\n",
644 g_strerror(errno));
646 path = g_strdup_printf("%s/%s", curdir, execname);
647 g_free(curdir);
648 prog_pathname = path;
649 } else {
651 * It's just a file name.
652 * Search the path for a file with that name
653 * that's executable.
655 prog_pathname = NULL; /* haven't found it yet */
656 pathstr = getenv("PATH");
657 path_start = pathstr;
658 if (path_start != NULL) {
659 while (*path_start != '\0') {
660 path_end = strchr(path_start, ':');
661 if (path_end == NULL)
662 path_end = path_start + strlen(path_start);
663 path_component_len = path_end - path_start;
664 path = (char *)g_malloc(path_component_len + 1
665 + strlen(execname) + 1);
666 memcpy(path, path_start, path_component_len);
667 path[path_component_len] = '\0';
668 strncat(path, "/", 2);
669 strncat(path, execname, strlen(execname) + 1);
670 if (access(path, X_OK) == 0) {
672 * Found it!
674 prog_pathname = path;
675 break;
679 * That's not it. If there are more
680 * path components to test, try them.
682 if (*path_end == '\0') {
684 * There's nothing more to try.
686 break;
688 if (*path_end == ':')
689 path_end++;
690 path_start = path_end;
691 g_free(path);
693 if (prog_pathname == NULL) {
695 * Program not found in path.
697 return g_strdup_printf("\"%s\" not found in \"%s\"",
698 execname, pathstr);
700 } else {
702 * PATH isn't set.
703 * XXX - should we pick a default?
705 return g_strdup("PATH isn't set");
710 * OK, we have what we think is the pathname
711 * of the program.
713 * First, find the last "/" in the directory,
714 * as that marks the end of the directory pathname.
716 dir_end = strrchr(prog_pathname, '/');
717 if (dir_end != NULL) {
719 * Found it. Strip off the last component,
720 * as that's the path of the program.
722 *dir_end = '\0';
725 * Is there a "/.libs" at the end?
727 dir_end = strrchr(prog_pathname, '/');
728 if (dir_end != NULL) {
729 if (strcmp(dir_end, "/.libs") == 0) {
731 * Yup, it's ".libs".
732 * Strip that off; it's an
733 * artifact of libtool.
735 *dir_end = '\0';
738 * This presumably means we're run from
739 * the libtool wrapper, which probably
740 * means we're being run from the build
741 * directory. If we weren't started
742 * with special privileges, set
743 * running_in_build_directory_flag.
745 * XXX - should we check whether what
746 * follows ".libs/" begins with "lt-"?
748 if (!started_with_special_privs())
749 running_in_build_directory_flag = TRUE;
751 #ifdef __APPLE__
752 else {
753 if (!started_with_special_privs()) {
755 * Scan up the path looking for a component
756 * named "Contents". If we find it, we assume
757 * we're in a bundle, and that the top-level
758 * directory of the bundle is the one containing
759 * "Contents".
761 * Not all executables are in the Contents/MacOS
762 * directory, so we can't just check for those
763 * in the path and strip them off.
765 * XXX - should we assume that it's either
766 * Contents/MacOS or Resources/bin?
768 char *component_end, *p;
770 component_end = strchr(prog_pathname, '\0');
771 p = component_end;
772 for (;;) {
773 while (p >= prog_pathname && *p != '/')
774 p--;
775 if (p == prog_pathname) {
777 * We're looking at the first component of
778 * the pathname now, so we're definitely
779 * not in a bundle, even if we're in
780 * "/Contents".
782 break;
784 if (strncmp(p, "/Contents", component_end - p) == 0) {
785 /* Found it. */
786 appbundle_dir = (char *)g_malloc(p - prog_pathname + 1);
787 memcpy(appbundle_dir, prog_pathname, p - prog_pathname);
788 appbundle_dir[p - prog_pathname] = '\0';
789 break;
791 component_end = p;
792 p--;
796 #endif
800 * OK, we have the path we want.
802 progfile_dir = prog_pathname;
803 return NULL;
804 } else {
806 * This "shouldn't happen"; we apparently
807 * have no "/" in the pathname.
808 * Just free up prog_pathname.
810 retstr = g_strdup_printf("No / found in \"%s\"", prog_pathname);
811 g_free(prog_pathname);
812 return retstr;
814 #endif
818 * Get the directory in which the program resides.
820 const char *
821 get_progfile_dir(void)
823 return progfile_dir;
827 * Get the directory in which the global configuration and data files are
828 * stored.
830 * On Windows, we use the directory in which the executable for this
831 * process resides.
833 * On UN*X, we use the DATAFILE_DIR value supplied by the configure
834 * script, unless we think we're being run from the build directory,
835 * in which case we use the directory in which the executable for this
836 * process resides.
838 * XXX - if we ever make libwireshark a real library, used by multiple
839 * applications (more than just TShark and versions of Wireshark with
840 * various UIs), should the configuration files belong to the library
841 * (and be shared by all those applications) or to the applications?
843 * If they belong to the library, that could be done on UNIX by the
844 * configure script, but it's trickier on Windows, as you can't just
845 * use the pathname of the executable.
847 * If they belong to the application, that could be done on Windows
848 * by using the pathname of the executable, but we'd have to have it
849 * passed in as an argument, in some call, on UNIX.
851 * Note that some of those configuration files might be used by code in
852 * libwireshark, some of them might be used by dissectors (would they
853 * belong to libwireshark, the application, or a separate library?),
854 * and some of them might be used by other code (the Wireshark preferences
855 * file includes resolver preferences that control the behavior of code
856 * in libwireshark, dissector preferences, and UI preferences, for
857 * example).
859 const char *
860 get_datafile_dir(void)
862 #ifdef _WIN32
863 char *u3deviceexecpath;
864 #endif
865 static const char *datafile_dir = NULL;
867 if (datafile_dir != NULL)
868 return datafile_dir;
870 #ifdef _WIN32
872 * See if we are running in a U3 environment.
874 u3deviceexecpath = getenv_utf8("U3_DEVICE_EXEC_PATH");
876 if (u3deviceexecpath != NULL) {
878 * We are; use the U3 device executable path.
880 datafile_dir = u3deviceexecpath;
881 } else {
883 * Do we have the pathname of the program? If so, assume we're
884 * running an installed version of the program. If we fail,
885 * we don't change "datafile_dir", and thus end up using the
886 * default.
888 * XXX - does NSIS put the installation directory into
889 * "\HKEY_LOCAL_MACHINE\SOFTWARE\Wireshark\InstallDir"?
890 * If so, perhaps we should read that from the registry,
891 * instead.
893 if (progfile_dir != NULL) {
895 * Yes, we do; use that.
897 datafile_dir = progfile_dir;
898 } else {
900 * No, we don't.
901 * Fall back on the default installation directory.
903 datafile_dir = "C:\\Program Files\\Wireshark\\";
906 #else
908 if (running_in_build_directory_flag) {
910 * We're (probably) being run from the build directory and
911 * weren't started with special privileges.
913 * (running_in_build_directory_flag is never set to TRUE
914 * if we're started with special privileges, so we need
915 * only check it; we don't need to call started_with_special_privs().)
917 * Use the top-level source directory as the datafile directory
918 * because most of our data files (radius/, COPYING) are there.
920 datafile_dir = g_strdup(TOP_SRCDIR);
921 return datafile_dir;
922 } else {
923 if (getenv("WIRESHARK_DATA_DIR") && !started_with_special_privs()) {
925 * The user specified a different directory for data files
926 * and we aren't running with special privileges.
927 * XXX - We might be able to dispense with the priv check
929 datafile_dir = g_strdup(getenv("WIRESHARK_DATA_DIR"));
931 #ifdef __APPLE__
933 * If we're running from an app bundle and weren't started
934 * with special privileges, use the Contents/Resources/share/wireshark
935 * subdirectory of the app bundle.
937 * (appbundle_dir is not set to a non-null value if we're
938 * started with special privileges, so we need only check
939 * it; we don't need to call started_with_special_privs().)
941 else if (appbundle_dir != NULL) {
942 datafile_dir = g_strdup_printf("%s/Contents/Resources/share/wireshark",
943 appbundle_dir);
945 #endif
946 else {
947 datafile_dir = DATAFILE_DIR;
951 #endif
952 return datafile_dir;
955 #ifdef HAVE_PYTHON
957 * Find the directory where the python dissectors are stored.
959 * On Windows, we use the "py_dissector" subdirectory of the datafile directory.
961 * On UN*X, we use the PYTHON_DIR value supplied by the configure
962 * script, unless we think we're being run from the build directory,
963 * in which case we use the "py_dissector" subdirectory of the datafile directory.
965 * In both cases, we then use the subdirectory of that directory whose
966 * name is the version number.
968 * XXX - if we think we're being run from the build directory, perhaps we
969 * should have the plugin code not look in the version subdirectory
970 * of the plugin directory, but look in all of the subdirectories
971 * of the plugin directory, so it can just fetch the plugins built
972 * as part of the build process.
974 static const char *wspython_dir = NULL;
976 static void
977 init_wspython_dir(void)
979 #ifdef _WIN32
981 * On Windows, the data file directory is the installation
982 * directory; the python dissectors are stored under it.
984 * Assume we're running the installed version of Wireshark;
985 * on Windows, the data file directory is the directory
986 * in which the Wireshark binary resides.
988 wspython_dir = g_strdup_printf("%s\\python\\%s", get_datafile_dir(),
989 VERSION);
992 * Make sure that pathname refers to a directory.
994 if (test_for_directory(wspython_dir) != EISDIR) {
996 * Either it doesn't refer to a directory or it
997 * refers to something that doesn't exist.
999 * Assume that means we're running a version of
1000 * Wireshark we've built in a build directory,
1001 * in which case {datafile dir}\python is the
1002 * top-level plugins source directory, and use
1003 * that directory and set the "we're running in
1004 * a build directory" flag, so the plugin
1005 * scanner will check all subdirectories of that
1006 * directory for python dissectors.
1008 g_free( (gpointer) wspython_dir);
1009 wspython_dir = g_strdup_printf("%s\\python", get_datafile_dir());
1010 running_in_build_directory_flag = TRUE;
1012 #else
1013 if (running_in_build_directory_flag) {
1015 * We're (probably) being run from the build directory and
1016 * weren't started with special privileges, so we'll use
1017 * the "python" subdirectory of the datafile directory
1018 * (the datafile directory is the build directory).
1020 wspython_dir = g_strdup_printf("%s/epan/wspython/", get_datafile_dir());
1021 } else {
1022 if (getenv("WIRESHARK_PYTHON_DIR") && !started_with_special_privs()) {
1024 * The user specified a different directory for plugins
1025 * and we aren't running with special privileges.
1027 wspython_dir = g_strdup(getenv("WIRESHARK_PYTHON_DIR"));
1029 #ifdef __APPLE__
1031 * If we're running from an app bundle and weren't started
1032 * with special privileges, use the Contents/Resources/lib/wireshark/python
1033 * subdirectory of the app bundle.
1035 * (appbundle_dir is not set to a non-null value if we're
1036 * started with special privileges, so we need only check
1037 * it; we don't need to call started_with_special_privs().)
1039 else if (appbundle_dir != NULL) {
1040 wspython_dir = g_strdup_printf("%s/Contents/Resources/lib/wireshark/python",
1041 appbundle_dir);
1043 #endif
1044 else {
1045 wspython_dir = PYTHON_DIR;
1048 #endif
1050 #endif /* HAVE_PYTHON */
1053 * Get the directory in which the python dissectors are stored.
1055 const char *
1056 get_wspython_dir(void)
1058 #ifdef HAVE_PYTHON
1059 if (!wspython_dir) init_wspython_dir();
1060 return wspython_dir;
1061 #else
1062 return NULL;
1063 #endif
1067 #if defined(HAVE_PLUGINS) || defined(HAVE_LUA)
1069 * Find the directory where the plugins are stored.
1071 * On Windows, we use the "plugin" subdirectory of the datafile directory.
1073 * On UN*X, we use the PLUGIN_DIR value supplied by the configure
1074 * script, unless we think we're being run from the build directory,
1075 * in which case we use the "plugin" subdirectory of the datafile directory.
1077 * In both cases, we then use the subdirectory of that directory whose
1078 * name is the version number.
1080 * XXX - if we think we're being run from the build directory, perhaps we
1081 * should have the plugin code not look in the version subdirectory
1082 * of the plugin directory, but look in all of the subdirectories
1083 * of the plugin directory, so it can just fetch the plugins built
1084 * as part of the build process.
1086 static const char *plugin_dir = NULL;
1088 static void
1089 init_plugin_dir(void)
1091 #ifdef _WIN32
1093 * On Windows, the data file directory is the installation
1094 * directory; the plugins are stored under it.
1096 * Assume we're running the installed version of Wireshark;
1097 * on Windows, the data file directory is the directory
1098 * in which the Wireshark binary resides.
1100 plugin_dir = g_strdup_printf("%s\\plugins\\%s", get_datafile_dir(),
1101 VERSION);
1104 * Make sure that pathname refers to a directory.
1106 if (test_for_directory(plugin_dir) != EISDIR) {
1108 * Either it doesn't refer to a directory or it
1109 * refers to something that doesn't exist.
1111 * Assume that means we're running a version of
1112 * Wireshark we've built in a build directory,
1113 * in which case {datafile dir}\plugins is the
1114 * top-level plugins source directory, and use
1115 * that directory and set the "we're running in
1116 * a build directory" flag, so the plugin
1117 * scanner will check all subdirectories of that
1118 * directory for plugins.
1120 g_free( (gpointer) plugin_dir);
1121 plugin_dir = g_strdup_printf("%s\\plugins", get_datafile_dir());
1122 running_in_build_directory_flag = TRUE;
1124 #else
1125 if (running_in_build_directory_flag) {
1127 * We're (probably) being run from the build directory and
1128 * weren't started with special privileges, so we'll use
1129 * the "plugins" subdirectory of the directory where the program
1130 * we're running is (that's the build directory).
1132 plugin_dir = g_strdup_printf("%s/plugins", get_progfile_dir());
1133 } else {
1134 if (getenv("WIRESHARK_PLUGIN_DIR") && !started_with_special_privs()) {
1136 * The user specified a different directory for plugins
1137 * and we aren't running with special privileges.
1139 plugin_dir = g_strdup(getenv("WIRESHARK_PLUGIN_DIR"));
1141 #ifdef __APPLE__
1143 * If we're running from an app bundle and weren't started
1144 * with special privileges, use the Contents/Resources/lib/wireshark/plugins
1145 * subdirectory of the app bundle.
1147 * (appbundle_dir is not set to a non-null value if we're
1148 * started with special privileges, so we need only check
1149 * it; we don't need to call started_with_special_privs().)
1151 else if (appbundle_dir != NULL) {
1152 plugin_dir = g_strdup_printf("%s/Contents/Resources/lib/wireshark/plugins",
1153 appbundle_dir);
1155 #endif
1156 else {
1157 plugin_dir = PLUGIN_DIR;
1160 #endif
1162 #endif /* HAVE_PLUGINS || HAVE_LUA */
1165 * Get the directory in which the plugins are stored.
1167 const char *
1168 get_plugin_dir(void)
1170 #if defined(HAVE_PLUGINS) || defined(HAVE_LUA)
1171 if (!plugin_dir) init_plugin_dir();
1172 return plugin_dir;
1173 #else
1174 return NULL;
1175 #endif
1179 * Get the flag indicating whether we're running from a build
1180 * directory.
1182 gboolean
1183 running_in_build_directory(void)
1185 return running_in_build_directory_flag;
1189 * Get the directory in which files that, at least on UNIX, are
1190 * system files (such as "/etc/ethers") are stored; on Windows,
1191 * there's no "/etc" directory, so we get them from the global
1192 * configuration and data file directory.
1194 const char *
1195 get_systemfile_dir(void)
1197 #ifdef _WIN32
1198 return get_datafile_dir();
1199 #else
1200 return "/etc";
1201 #endif
1205 * Name of directory, under the user's home directory, in which
1206 * personal configuration files are stored.
1208 #ifdef _WIN32
1209 #define PF_DIR "Wireshark"
1210 #else
1212 * XXX - should this be ".libepan"? For backwards-compatibility, I'll keep
1213 * it ".wireshark" for now.
1215 #define PF_DIR ".wireshark"
1216 #endif
1218 void
1219 set_profile_name(const gchar *profilename)
1221 g_free (persconfprofile);
1223 if (profilename && strlen(profilename) > 0 &&
1224 strcmp(profilename, DEFAULT_PROFILE) != 0) {
1225 persconfprofile = g_strdup (profilename);
1226 } else {
1227 /* Default Profile */
1228 persconfprofile = NULL;
1232 const char *
1233 get_profile_name(void)
1235 if (persconfprofile) {
1236 return persconfprofile;
1237 } else {
1238 return DEFAULT_PROFILE;
1242 gboolean
1243 is_default_profile(void)
1245 return (!persconfprofile || strcmp(persconfprofile, DEFAULT_PROFILE) == 0) ? TRUE : FALSE;
1248 gboolean
1249 has_global_profiles(void)
1251 WS_DIR *dir;
1252 WS_DIRENT *file;
1253 const gchar *global_dir = get_global_profiles_dir();
1254 gchar *filename;
1255 gboolean has_global = FALSE;
1257 if ((test_for_directory(global_dir) == EISDIR) &&
1258 ((dir = ws_dir_open(global_dir, 0, NULL)) != NULL))
1260 while ((file = ws_dir_read_name(dir)) != NULL) {
1261 filename = g_strdup_printf ("%s%s%s", global_dir, G_DIR_SEPARATOR_S,
1262 ws_dir_get_name(file));
1263 if (test_for_directory(filename) == EISDIR) {
1264 has_global = TRUE;
1265 g_free (filename);
1266 break;
1268 g_free (filename);
1270 ws_dir_close(dir);
1273 return has_global;
1276 void
1277 profile_store_persconffiles(gboolean store)
1279 if (store) {
1280 profile_files = g_hash_table_new (g_str_hash, g_str_equal);
1282 do_store_persconffiles = store;
1286 * Get the directory in which personal configuration files reside;
1287 * in UNIX-compatible systems, it's ".wireshark", under the user's home
1288 * directory, and on Windows systems, it's "Wireshark", under %APPDATA%
1289 * or, if %APPDATA% isn't set, it's "%USERPROFILE%\Application Data"
1290 * (which is what %APPDATA% normally is on Windows 2000).
1292 static const char *
1293 get_persconffile_dir_no_profile(void)
1295 #ifdef _WIN32
1296 char *appdatadir;
1297 char *userprofiledir;
1298 char *altappdatapath;
1299 #else
1300 const char *homedir;
1301 struct passwd *pwd;
1302 #endif
1304 /* Return the cached value, if available */
1305 if (persconffile_dir != NULL)
1306 return persconffile_dir;
1308 #ifdef _WIN32
1310 * See if the user has selected an alternate environment.
1312 altappdatapath = getenv_utf8("WIRESHARK_APPDATA");
1313 if (altappdatapath != NULL) {
1314 persconffile_dir = altappdatapath;
1315 return persconffile_dir;
1319 * See if we are running in a U3 environment.
1321 altappdatapath = getenv_utf8("U3_APP_DATA_PATH");
1322 if (altappdatapath != NULL) {
1324 * We are; use the U3 application data path.
1326 persconffile_dir = altappdatapath;
1327 } else {
1329 * Use %APPDATA% or %USERPROFILE%, so that configuration
1330 * files are stored in the user profile, rather than in
1331 * the home directory. The Windows convention is to store
1332 * configuration information in the user profile, and doing
1333 * so means you can use Wireshark even if the home directory
1334 * is an inaccessible network drive.
1336 appdatadir = getenv_utf8("APPDATA");
1337 if (appdatadir != NULL) {
1339 * Concatenate %APPDATA% with "\Wireshark".
1341 persconffile_dir = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1342 appdatadir, PF_DIR);
1343 } else {
1345 * OK, %APPDATA% wasn't set, so use
1346 * %USERPROFILE%\Application Data.
1348 userprofiledir = getenv_utf8("USERPROFILE");
1349 if (userprofiledir != NULL) {
1350 persconffile_dir = g_strdup_printf(
1351 "%s" G_DIR_SEPARATOR_S "Application Data" G_DIR_SEPARATOR_S "%s",
1352 userprofiledir, PF_DIR);
1353 } else {
1355 * Give up and use "C:".
1357 persconffile_dir = g_strdup_printf("C:" G_DIR_SEPARATOR_S "%s", PF_DIR);
1361 #else
1363 * If $HOME is set, use that.
1365 homedir = getenv("HOME");
1366 if (homedir == NULL) {
1368 * Get their home directory from the password file.
1369 * If we can't even find a password file entry for them,
1370 * use "/tmp".
1372 pwd = getpwuid(getuid());
1373 if (pwd != NULL) {
1374 homedir = pwd->pw_dir;
1375 } else {
1376 homedir = "/tmp";
1379 persconffile_dir = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", homedir, PF_DIR);
1380 #endif
1382 return persconffile_dir;
1385 const char *
1386 get_profiles_dir(void)
1388 static char *profiles_dir = NULL;
1390 g_free (profiles_dir);
1391 profiles_dir = g_strdup_printf ("%s%s%s", get_persconffile_dir_no_profile (),
1392 G_DIR_SEPARATOR_S, PROFILES_DIR);
1394 return profiles_dir;
1397 const char *
1398 get_global_profiles_dir(void)
1400 static char *global_profiles_dir = NULL;
1402 if (!global_profiles_dir) {
1403 global_profiles_dir = g_strdup_printf ("%s%s%s", get_datafile_dir(),
1404 G_DIR_SEPARATOR_S, PROFILES_DIR);
1407 return global_profiles_dir;
1410 static const char *
1411 get_persconffile_dir(const gchar *profilename)
1413 static char *persconffile_profile_dir = NULL;
1415 g_free (persconffile_profile_dir);
1417 if (profilename && strlen(profilename) > 0 &&
1418 strcmp(profilename, DEFAULT_PROFILE) != 0) {
1419 persconffile_profile_dir = g_strdup_printf ("%s%s%s", get_profiles_dir (),
1420 G_DIR_SEPARATOR_S, profilename);
1421 } else {
1422 persconffile_profile_dir = g_strdup (get_persconffile_dir_no_profile ());
1425 return persconffile_profile_dir;
1428 gboolean
1429 profile_exists(const gchar *profilename, gboolean global)
1431 if (global) {
1432 gchar *path = g_strdup_printf ("%s%s%s", get_global_profiles_dir(),
1433 G_DIR_SEPARATOR_S, profilename);
1434 if (test_for_directory (path) == EISDIR) {
1435 g_free (path);
1436 return TRUE;
1438 g_free (path);
1439 } else {
1440 if (test_for_directory (get_persconffile_dir (profilename)) == EISDIR) {
1441 return TRUE;
1445 return FALSE;
1448 static int
1449 delete_directory (const char *directory, char **pf_dir_path_return)
1451 WS_DIR *dir;
1452 WS_DIRENT *file;
1453 gchar *filename;
1454 int ret = 0;
1456 if ((dir = ws_dir_open(directory, 0, NULL)) != NULL) {
1457 while ((file = ws_dir_read_name(dir)) != NULL) {
1458 filename = g_strdup_printf ("%s%s%s", directory, G_DIR_SEPARATOR_S,
1459 ws_dir_get_name(file));
1460 if (test_for_directory(filename) != EISDIR) {
1461 ret = ws_remove(filename);
1462 #if 0
1463 } else {
1464 /* The user has manually created a directory in the profile directory */
1465 /* I do not want to delete the directory recursively yet */
1466 ret = delete_directory (filename, pf_dir_path_return);
1467 #endif
1469 if (ret != 0) {
1470 *pf_dir_path_return = filename;
1471 break;
1473 g_free (filename);
1475 ws_dir_close(dir);
1478 if (ret == 0 && (ret = ws_remove(directory)) != 0) {
1479 *pf_dir_path_return = g_strdup (directory);
1482 return ret;
1486 delete_persconffile_profile(const char *profilename, char **pf_dir_path_return)
1488 const char *profile_dir = get_persconffile_dir(profilename);
1489 int ret = 0;
1491 if (test_for_directory (profile_dir) == EISDIR) {
1492 ret = delete_directory (profile_dir, pf_dir_path_return);
1495 return ret;
1499 rename_persconffile_profile(const char *fromname, const char *toname,
1500 char **pf_from_dir_path_return, char **pf_to_dir_path_return)
1502 char *from_dir = g_strdup (get_persconffile_dir(fromname));
1503 char *to_dir = g_strdup (get_persconffile_dir(toname));
1504 int ret = 0;
1506 ret = ws_rename (from_dir, to_dir);
1507 if (ret != 0) {
1508 *pf_from_dir_path_return = g_strdup (from_dir);
1509 *pf_to_dir_path_return = g_strdup (to_dir);
1512 g_free (from_dir);
1513 g_free (to_dir);
1515 return ret;
1519 * Create the directory that holds personal configuration files, if
1520 * necessary. If we attempted to create it, and failed, return -1 and
1521 * set "*pf_dir_path_return" to the pathname of the directory we failed
1522 * to create (it's g_mallocated, so our caller should free it); otherwise,
1523 * return 0.
1526 create_persconffile_profile(const char *profilename, char **pf_dir_path_return)
1528 const char *pf_dir_path;
1529 #ifdef _WIN32
1530 char *pf_dir_path_copy, *pf_dir_parent_path;
1531 size_t pf_dir_parent_path_len;
1532 #endif
1533 ws_statb64 s_buf;
1534 int ret;
1536 if (profilename) {
1538 * Create the "Default" personal configuration files directory, if necessary.
1540 if (create_persconffile_profile (NULL, pf_dir_path_return) == -1) {
1541 return -1;
1545 * Check if profiles directory exists.
1546 * If not then create it.
1548 pf_dir_path = get_profiles_dir ();
1549 if (ws_stat64(pf_dir_path, &s_buf) != 0 && errno == ENOENT) {
1550 ret = ws_mkdir(pf_dir_path, 0755);
1551 if (ret == -1) {
1552 *pf_dir_path_return = g_strdup(pf_dir_path);
1553 return ret;
1558 pf_dir_path = get_persconffile_dir(profilename);
1559 if (ws_stat64(pf_dir_path, &s_buf) != 0 && errno == ENOENT) {
1560 #ifdef _WIN32
1562 * Does the parent directory of that directory
1563 * exist? %APPDATA% may not exist even though
1564 * %USERPROFILE% does.
1566 * We check for the existence of the directory
1567 * by first checking whether the parent directory
1568 * is just a drive letter and, if it's not, by
1569 * doing a "stat()" on it. If it's a drive letter,
1570 * or if the "stat()" succeeds, we assume it exists.
1572 pf_dir_path_copy = g_strdup(pf_dir_path);
1573 pf_dir_parent_path = get_dirname(pf_dir_path_copy);
1574 pf_dir_parent_path_len = strlen(pf_dir_parent_path);
1575 if (pf_dir_parent_path_len > 0
1576 && pf_dir_parent_path[pf_dir_parent_path_len - 1] != ':'
1577 && ws_stat64(pf_dir_parent_path, &s_buf) != 0) {
1579 * No, it doesn't exist - make it first.
1581 ret = ws_mkdir(pf_dir_parent_path, 0755);
1582 if (ret == -1) {
1583 *pf_dir_path_return = pf_dir_parent_path;
1584 return -1;
1587 g_free(pf_dir_path_copy);
1588 ret = ws_mkdir(pf_dir_path, 0755);
1589 #else
1590 ret = ws_mkdir(pf_dir_path, 0755);
1591 #endif
1592 } else {
1594 * Something with that pathname exists; if it's not
1595 * a directory, we'll get an error if we try to put
1596 * something in it, so we don't fail here, we wait
1597 * for that attempt fo fail.
1599 ret = 0;
1601 if (ret == -1)
1602 *pf_dir_path_return = g_strdup(pf_dir_path);
1603 return ret;
1607 create_persconffile_dir(char **pf_dir_path_return)
1609 return create_persconffile_profile(persconfprofile, pf_dir_path_return);
1613 copy_persconffile_profile(const char *toname, const char *fromname, gboolean from_global,
1614 char **pf_filename_return, char **pf_to_dir_path_return, char **pf_from_dir_path_return)
1616 gchar *from_dir;
1617 gchar *to_dir = g_strdup (get_persconffile_dir(toname));
1618 gchar *filename, *from_file, *to_file;
1619 GList *files, *file;
1621 if (from_global) {
1622 if (strcmp(fromname, DEFAULT_PROFILE) == 0) {
1623 from_dir = g_strdup (get_global_profiles_dir());
1624 } else {
1625 from_dir = g_strdup_printf ("%s%s%s", get_global_profiles_dir(), G_DIR_SEPARATOR_S, fromname);
1627 } else {
1628 from_dir = g_strdup (get_persconffile_dir(fromname));
1631 files = g_hash_table_get_keys(profile_files);
1632 file = g_list_first(files);
1633 while (file) {
1634 filename = (gchar *)file->data;
1635 from_file = g_strdup_printf ("%s%s%s", from_dir, G_DIR_SEPARATOR_S, filename);
1636 to_file = g_strdup_printf ("%s%s%s", to_dir, G_DIR_SEPARATOR_S, filename);
1638 if (file_exists(from_file) && !copy_file_binary_mode(from_file, to_file)) {
1639 *pf_filename_return = g_strdup(filename);
1640 *pf_to_dir_path_return = to_dir;
1641 *pf_from_dir_path_return = from_dir;
1642 g_free (from_file);
1643 g_free (to_file);
1644 return -1;
1647 g_free (from_file);
1648 g_free (to_file);
1650 file = g_list_next(file);
1653 g_list_free (files);
1654 g_free (from_dir);
1655 g_free (to_dir);
1657 return 0;
1661 * Get the (default) directory in which personal data is stored.
1663 * On Win32, this is the "My Documents" folder in the personal profile,
1664 * except that, if we're running from a U3 device, this is the
1665 * "$U3_DEVICE_DOCUMENT_PATH\My Captures" folder.
1666 * On UNIX this is simply the current directory.
1668 /* XXX - should this and the get_home_dir() be merged? */
1669 extern const char *
1670 get_persdatafile_dir(void)
1672 #ifdef _WIN32
1673 char *u3devicedocumentpath;
1674 TCHAR tszPath[MAX_PATH];
1675 char *szPath;
1676 BOOL bRet;
1678 /* Return the cached value, if available */
1679 if (persdatafile_dir != NULL)
1680 return persdatafile_dir;
1683 * See if we are running in a U3 environment.
1685 u3devicedocumentpath = getenv_utf8("U3_DEVICE_DOCUMENT_PATH");
1687 if (u3devicedocumentpath != NULL) {
1688 /* the "My Captures" sub-directory is created (if it doesn't
1689 exist) by u3util.exe when the U3 Wireshark is first run */
1691 szPath = g_strdup_printf("%s%s", u3devicedocumentpath, U3_MY_CAPTURES);
1693 persdatafile_dir = szPath;
1694 return szPath;
1695 } else {
1697 * Hint: SHGetFolderPath is not available on MSVC 6 - without
1698 * Platform SDK
1700 bRet = SHGetSpecialFolderPath(NULL, tszPath, CSIDL_PERSONAL,
1701 FALSE);
1702 if(bRet == TRUE) {
1703 szPath = utf_16to8(tszPath);
1704 persdatafile_dir = szPath;
1705 return szPath;
1706 } else {
1707 return "";
1710 #else
1711 return "";
1712 #endif
1715 #ifdef _WIN32
1717 * Returns the user's home directory on Win32.
1719 static const char *
1720 get_home_dir(void)
1722 static const char *home = NULL;
1723 char *homedrive, *homepath;
1724 char *homestring;
1725 char *lastsep;
1727 /* Return the cached value, if available */
1728 if (home)
1729 return home;
1732 * XXX - should we use USERPROFILE anywhere in this process?
1733 * Is there a chance that it might be set but one or more of
1734 * HOMEDRIVE or HOMEPATH isn't set?
1736 homedrive = getenv_utf8("HOMEDRIVE");
1737 if (homedrive != NULL) {
1738 homepath = getenv_utf8("HOMEPATH");
1739 if (homepath != NULL) {
1741 * This is cached, so we don't need to worry about
1742 * allocating multiple ones of them.
1744 homestring = g_strdup_printf("%s%s", homedrive, homepath);
1747 * Trim off any trailing slash or backslash.
1749 lastsep = find_last_pathname_separator(homestring);
1750 if (lastsep != NULL && *(lastsep + 1) == '\0') {
1752 * Last separator is the last character
1753 * in the string. Nuke it.
1755 *lastsep = '\0';
1757 home = homestring;
1758 } else
1759 home = homedrive;
1760 } else {
1762 * Give up and use C:.
1764 home = "C:";
1767 return home;
1769 #endif
1772 * Construct the path name of a personal configuration file, given the
1773 * file name.
1775 * On Win32, if "for_writing" is FALSE, we check whether the file exists
1776 * and, if not, construct a path name relative to the ".wireshark"
1777 * subdirectory of the user's home directory, and check whether that
1778 * exists; if it does, we return that, so that configuration files
1779 * from earlier versions can be read.
1781 * The returned file name was g_malloc()'d so it must be g_free()d when the
1782 * caller is done with it.
1784 char *
1785 get_persconffile_path(const char *filename, gboolean from_profile)
1787 char *path;
1788 if (do_store_persconffiles && from_profile && !g_hash_table_lookup (profile_files, filename)) {
1789 /* Store filenames so we know which filenames belongs to a configuration profile */
1790 g_hash_table_insert (profile_files, g_strdup(filename), g_strdup(filename));
1793 if (from_profile) {
1794 path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1795 get_persconffile_dir(persconfprofile), filename);
1796 } else {
1797 path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1798 get_persconffile_dir(NULL), filename);
1801 return path;
1805 * process command line option belonging to the filesystem settings
1806 * (move this e.g. to main.c and have set_persconffile_dir() instead in this file?)
1809 filesystem_opt(int opt _U_, const char *optstr)
1811 gchar *p, *colonp;
1813 colonp = strchr(optstr, ':');
1814 if (colonp == NULL) {
1815 return 1;
1818 p = colonp;
1819 *p++ = '\0';
1822 * Skip over any white space (there probably won't be any, but
1823 * as we allow it in the preferences file, we might as well
1824 * allow it here).
1826 while (isspace((guchar)*p))
1827 p++;
1828 if (*p == '\0') {
1830 * Put the colon back, so if our caller uses, in an
1831 * error message, the string they passed us, the message
1832 * looks correct.
1834 *colonp = ':';
1835 return 1;
1838 /* directory should be existing */
1839 /* XXX - is this a requirement? */
1840 if(test_for_directory(p) != EISDIR) {
1842 * Put the colon back, so if our caller uses, in an
1843 * error message, the string they passed us, the message
1844 * looks correct.
1846 *colonp = ':';
1847 return 1;
1850 if (strcmp(optstr,"persconf") == 0) {
1851 persconffile_dir = p;
1852 } else if (strcmp(optstr,"persdata") == 0) {
1853 persdatafile_dir = p;
1854 /* XXX - might need to add the temp file path */
1855 } else {
1856 return 1;
1858 *colonp = ':'; /* put the colon back */
1859 return 0;
1863 * Construct the path name of a global configuration file, given the
1864 * file name.
1866 * The returned file name was g_malloc()'d so it must be g_free()d when the
1867 * caller is done with it.
1869 char *
1870 get_datafile_path(const char *filename)
1872 if (running_in_build_directory_flag && !strcmp(filename, "AUTHORS-SHORT")) {
1873 /* We're running in the build directory and the requested file is a
1874 * generated file. Return the file name in the build directory (not
1875 * in the source/data directory).
1877 return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", get_progfile_dir(), filename);
1878 } else {
1879 return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", get_datafile_dir(), filename);
1883 /* Get the personal plugin dir */
1884 /* Return value is malloced so the caller should g_free() it. */
1885 char *
1886 get_plugins_pers_dir(void)
1888 return get_persconffile_path(PLUGINS_DIR_NAME, FALSE);
1891 /* Delete a file */
1892 gboolean
1893 deletefile(const char *path)
1895 return ws_unlink(path) == 0;
1899 * Construct and return the path name of a file in the
1900 * appropriate temporary file directory.
1902 char *get_tempfile_path(const char *filename)
1904 return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", g_get_tmp_dir(), filename);
1908 * Return an error message for UNIX-style errno indications on open or
1909 * create operations.
1911 const char *
1912 file_open_error_message(int err, gboolean for_writing)
1914 const char *errmsg;
1915 static char errmsg_errno[1024+1];
1917 switch (err) {
1919 case ENOENT:
1920 if (for_writing)
1921 errmsg = "The path to the file \"%s\" doesn't exist.";
1922 else
1923 errmsg = "The file \"%s\" doesn't exist.";
1924 break;
1926 case EACCES:
1927 if (for_writing)
1928 errmsg = "You don't have permission to create or write to the file \"%s\".";
1929 else
1930 errmsg = "You don't have permission to read the file \"%s\".";
1931 break;
1933 case EISDIR:
1934 errmsg = "\"%s\" is a directory (folder), not a file.";
1935 break;
1937 case ENOSPC:
1938 errmsg = "The file \"%s\" could not be created because there is no space left on the file system.";
1939 break;
1941 #ifdef EDQUOT
1942 case EDQUOT:
1943 errmsg = "The file \"%s\" could not be created because you are too close to, or over, your disk quota.";
1944 break;
1945 #endif
1947 case EINVAL:
1948 errmsg = "The file \"%s\" could not be created because an invalid filename was specified.";
1949 break;
1951 case ENOMEM:
1953 * The problem probably has nothing to do with how much RAM the
1954 * user has on their machine, so don't confuse them by saying
1955 * "memory". The problem is probably either virtual address
1956 * space or swap space.
1958 #if GLIB_SIZEOF_VOID_P == 4
1960 * ILP32; we probably ran out of virtual address space.
1962 #define ENOMEM_REASON "it can't be handled by a 32-bit application"
1963 #else
1965 * LP64 or LLP64; we probably ran out of swap space.
1967 #if defined(_WIN32)
1969 * You need to make the pagefile bigger.
1971 #define ENOMEM_REASON "the pagefile is too small"
1972 #elif defined(__APPLE__)
1974 * dynamic_pager couldn't, or wouldn't, create more swap files.
1976 #define ENOMEM_REASON "your system ran out of swap file space"
1977 #else
1979 * Either you have a fixed swap partition or a fixed swap file,
1980 * and it needs to be made bigger.
1982 * This is UN*X, but it's not OS X, so we assume the user is
1983 * *somewhat* nerdy.
1985 #define ENOMEM_REASON "your system is out of swap space"
1986 #endif
1987 #endif /* GLIB_SIZEOF_VOID_P == 4 */
1988 if (for_writing)
1989 errmsg = "The file \"%s\" could not be created because " ENOMEM_REASON ".";
1990 else
1991 errmsg = "The file \"%s\" could not be opened because " ENOMEM_REASON ".";
1992 break;
1994 default:
1995 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
1996 "The file \"%%s\" could not be %s: %s.",
1997 for_writing ? "created" : "opened",
1998 g_strerror(err));
1999 errmsg = errmsg_errno;
2000 break;
2002 return errmsg;
2006 * Return an error message for UNIX-style errno indications on write
2007 * operations.
2009 const char *
2010 file_write_error_message(int err)
2012 const char *errmsg;
2013 static char errmsg_errno[1024+1];
2015 switch (err) {
2017 case ENOSPC:
2018 errmsg = "The file \"%s\" could not be saved because there is no space left on the file system.";
2019 break;
2021 #ifdef EDQUOT
2022 case EDQUOT:
2023 errmsg = "The file \"%s\" could not be saved because you are too close to, or over, your disk quota.";
2024 break;
2025 #endif
2027 default:
2028 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2029 "An error occurred while writing to the file \"%%s\": %s.",
2030 g_strerror(err));
2031 errmsg = errmsg_errno;
2032 break;
2034 return errmsg;
2038 gboolean
2039 file_exists(const char *fname)
2041 ws_statb64 file_stat;
2043 if (!fname) {
2044 return FALSE;
2047 #ifdef _WIN32
2049 * This is a bit tricky on win32. The st_ino field is documented as:
2050 * "The inode, and therefore st_ino, has no meaning in the FAT, ..."
2051 * but it *is* set to zero if stat() returns without an error,
2052 * so this is working, but maybe not quite the way expected. ULFL
2054 file_stat.st_ino = 1; /* this will make things work if an error occurred */
2055 ws_stat64(fname, &file_stat);
2056 if (file_stat.st_ino == 0) {
2057 return TRUE;
2058 } else {
2059 return FALSE;
2061 #else
2062 if (ws_stat64(fname, &file_stat) != 0 && errno == ENOENT) {
2063 return FALSE;
2064 } else {
2065 return TRUE;
2067 #endif
2071 * Check that the from file is not the same as to file
2072 * We do it here so we catch all cases ...
2073 * Unfortunately, the file requester gives us an absolute file
2074 * name and the read file name may be relative (if supplied on
2075 * the command line), so we can't just compare paths. From Joerg Mayer.
2077 gboolean
2078 files_identical(const char *fname1, const char *fname2)
2080 /* Two different implementations, because:
2082 * - _fullpath is not available on UN*X, so we can't get full
2083 * paths and compare them (which wouldn't work with hard links
2084 * in any case);
2086 * - st_ino isn't filled in with a meaningful value on Windows.
2088 #ifdef _WIN32
2089 char full1[MAX_PATH], full2[MAX_PATH];
2092 * Get the absolute full paths of the file and compare them.
2093 * That won't work if you have hard links, but those aren't
2094 * much used on Windows, even though NTFS supports them.
2096 * XXX - will _fullpath work with UNC?
2098 if( _fullpath( full1, fname1, MAX_PATH ) == NULL ) {
2099 return FALSE;
2102 if( _fullpath( full2, fname2, MAX_PATH ) == NULL ) {
2103 return FALSE;
2106 if(strcmp(full1, full2) == 0) {
2107 return TRUE;
2108 } else {
2109 return FALSE;
2111 #else
2112 ws_statb64 filestat1, filestat2;
2115 * Compare st_dev and st_ino.
2117 if (ws_stat64(fname1, &filestat1) == -1)
2118 return FALSE; /* can't get info about the first file */
2119 if (ws_stat64(fname2, &filestat2) == -1)
2120 return FALSE; /* can't get info about the second file */
2121 return (filestat1.st_dev == filestat2.st_dev &&
2122 filestat1.st_ino == filestat2.st_ino);
2123 #endif
2127 * Copy a file in binary mode, for those operating systems that care about
2128 * such things. This should be OK for all files, even text files, as
2129 * we'll copy the raw bytes, and we don't look at the bytes as we copy
2130 * them.
2132 * Returns TRUE on success, FALSE on failure. If a failure, it also
2133 * displays a simple dialog window with the error message.
2135 gboolean
2136 copy_file_binary_mode(const char *from_filename, const char *to_filename)
2138 int from_fd, to_fd, err;
2139 ssize_t nread, nwritten;
2140 guint8 *pd = NULL;
2142 /* Copy the raw bytes of the file. */
2143 from_fd = ws_open(from_filename, O_RDONLY | O_BINARY, 0000 /* no creation so don't matter */);
2144 if (from_fd < 0) {
2145 report_open_failure(from_filename, errno, FALSE);
2146 goto done;
2149 /* Use open() instead of creat() so that we can pass the O_BINARY
2150 flag, which is relevant on Win32; it appears that "creat()"
2151 may open the file in text mode, not binary mode, but we want
2152 to copy the raw bytes of the file, so we need the output file
2153 to be open in binary mode. */
2154 to_fd = ws_open(to_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
2155 if (to_fd < 0) {
2156 report_open_failure(to_filename, errno, TRUE);
2157 ws_close(from_fd);
2158 goto done;
2161 #define FS_READ_SIZE 65536
2162 pd = (guint8 *)g_malloc(FS_READ_SIZE);
2163 while ((nread = ws_read(from_fd, pd, FS_READ_SIZE)) > 0) {
2164 nwritten = ws_write(to_fd, pd, nread);
2165 if (nwritten < nread) {
2166 if (nwritten < 0)
2167 err = errno;
2168 else
2169 err = WTAP_ERR_SHORT_WRITE;
2170 report_write_failure(to_filename, err);
2171 ws_close(from_fd);
2172 ws_close(to_fd);
2173 goto done;
2176 if (nread < 0) {
2177 err = errno;
2178 report_read_failure(from_filename, err);
2179 ws_close(from_fd);
2180 ws_close(to_fd);
2181 goto done;
2183 ws_close(from_fd);
2184 if (ws_close(to_fd) < 0) {
2185 report_write_failure(to_filename, errno);
2186 goto done;
2189 g_free(pd);
2190 pd = NULL;
2191 return TRUE;
2193 done:
2194 g_free(pd);
2195 return FALSE;
2199 * Editor modelines
2201 * Local Variables:
2202 * c-basic-offset: 4
2203 * tab-width: 8
2204 * indent-tabs-mode: nil
2205 * End:
2207 * ex: set shiftwidth=4 tabstop=8 expandtab:
2208 * :indentSize=4:tabSize=8:noTabs=true: