strptime.c needs ctype.h.
[metze/wireshark/wip.git] / wsutil / filesystem.c
1 /* filesystem.c
2  * Filesystem utility routines
3  *
4  * Wireshark - Network traffic analyzer
5  * By Gerald Combs <gerald@wireshark.org>
6  * Copyright 1998 Gerald Combs
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include "config.h"
24
25 /*
26  * Required with GNU libc to get dladdr().
27  * We define it here because <dlfcn.h> apparently gets included by
28  * one of the headers we include below.
29  */
30 #define _GNU_SOURCE
31
32 #ifdef HAVE_DIRENT_H
33 #include <dirent.h>
34 #endif
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <errno.h>
40
41 #include <glib.h>
42
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46
47 #ifdef HAVE_FCNTL_H
48 #include <fcntl.h>
49 #endif
50
51 #ifdef HAVE_SYS_STAT_H
52 #include <sys/stat.h>
53 #endif
54
55 #ifdef _WIN32
56 #include <windows.h>
57 #include <tchar.h>
58 #include <shlobj.h>
59 #include <wsutil/unicode-utils.h>
60 #else /* _WIN32 */
61 #ifdef __APPLE__
62 #include <mach-o/dyld.h>
63 #endif
64 #ifdef __linux__
65 #include <sys/utsname.h>
66 #endif
67 #ifdef __FreeBSD__
68 #include <sys/types.h>
69 #include <sys/sysctl.h>
70 #endif
71 #ifdef HAVE_DLADDR
72 #include <dlfcn.h>
73 #endif
74 #include <pwd.h>
75 #endif /* _WIN32 */
76
77 #include "filesystem.h"
78 #include <wsutil/report_err.h>
79 #include <wsutil/privileges.h>
80 #include <wsutil/file_util.h>
81
82 #include <wiretap/wtap.h>   /* for WTAP_ERR_SHORT_WRITE */
83
84 #define PROFILES_DIR    "profiles"
85 #define PLUGINS_DIR_NAME    "plugins"
86
87 #define U3_MY_CAPTURES  "\\My Captures"
88
89 char *persconffile_dir = NULL;
90 char *persdatafile_dir = NULL;
91 char *persconfprofile = NULL;
92
93 static gboolean do_store_persconffiles = FALSE;
94 static GHashTable *profile_files = NULL;
95
96 /*
97  * Given a pathname, return a pointer to the last pathname separator
98  * character in the pathname, or NULL if the pathname contains no
99  * separators.
100  */
101 char *
102 find_last_pathname_separator(const char *path)
103 {
104     char *separator;
105
106 #ifdef _WIN32
107     char c;
108
109     /*
110      * We have to scan for '\' or '/'.
111      * Get to the end of the string.
112      */
113     separator = strchr(path, '\0');     /* points to ending '\0' */
114     while (separator > path) {
115         c = *--separator;
116         if (c == '\\' || c == '/')
117             return separator;   /* found it */
118     }
119
120     /*
121      * OK, we didn't find any, so no directories - but there might
122      * be a drive letter....
123      */
124     return strchr(path, ':');
125 #else
126     separator = strrchr(path, '/');
127     return separator;
128 #endif
129 }
130
131 /*
132  * Given a pathname, return the last component.
133  */
134 const char *
135 get_basename(const char *path)
136 {
137     const char *filename;
138
139     g_assert(path != NULL);
140     filename = find_last_pathname_separator(path);
141     if (filename == NULL) {
142         /*
143          * There're no directories, drive letters, etc. in the
144          * name; the pathname *is* the file name.
145          */
146         filename = path;
147     } else {
148         /*
149          * Skip past the pathname or drive letter separator.
150          */
151         filename++;
152     }
153     return filename;
154 }
155
156 /*
157  * Given a pathname, return a string containing everything but the
158  * last component.  NOTE: this overwrites the pathname handed into
159  * it....
160  */
161 char *
162 get_dirname(char *path)
163 {
164     char *separator;
165
166     g_assert(path != NULL);
167     separator = find_last_pathname_separator(path);
168     if (separator == NULL) {
169         /*
170          * There're no directories, drive letters, etc. in the
171          * name; there is no directory path to return.
172          */
173         return NULL;
174     }
175
176     /*
177      * Get rid of the last pathname separator and the final file
178      * name following it.
179      */
180     *separator = '\0';
181
182     /*
183      * "path" now contains the pathname of the directory containing
184      * the file/directory to which it referred.
185      */
186     return path;
187 }
188
189 /*
190  * Given a pathname, return:
191  *
192  *  the errno, if an attempt to "stat()" the file fails;
193  *
194  *  EISDIR, if the attempt succeeded and the file turned out
195  *  to be a directory;
196  *
197  *  0, if the attempt succeeded and the file turned out not
198  *  to be a directory.
199  */
200
201 /*
202  * Visual C++ on Win32 systems doesn't define these.  (Old UNIX systems don't
203  * define them either.)
204  *
205  * Visual C++ on Win32 systems doesn't define S_IFIFO, it defines _S_IFIFO.
206  */
207 #ifndef S_ISREG
208 #define S_ISREG(mode)   (((mode) & S_IFMT) == S_IFREG)
209 #endif
210 #ifndef S_IFIFO
211 #define S_IFIFO _S_IFIFO
212 #endif
213 #ifndef S_ISFIFO
214 #define S_ISFIFO(mode)  (((mode) & S_IFMT) == S_IFIFO)
215 #endif
216 #ifndef S_ISDIR
217 #define S_ISDIR(mode)   (((mode) & S_IFMT) == S_IFDIR)
218 #endif
219
220 int
221 test_for_directory(const char *path)
222 {
223     ws_statb64 statb;
224
225     if (ws_stat64(path, &statb) < 0)
226         return errno;
227
228     if (S_ISDIR(statb.st_mode))
229         return EISDIR;
230     else
231         return 0;
232 }
233
234 int
235 test_for_fifo(const char *path)
236 {
237     ws_statb64 statb;
238
239     if (ws_stat64(path, &statb) < 0)
240         return errno;
241
242     if (S_ISFIFO(statb.st_mode))
243         return ESPIPE;
244     else
245         return 0;
246 }
247
248 /*
249  * Directory from which the executable came.
250  */
251 static char *progfile_dir;
252
253 #ifdef __APPLE__
254 /*
255  * Directory of the application bundle in which we're contained,
256  * if we're contained in an application bundle.  Otherwise, NULL.
257  *
258  * Note: Table 2-5 "Subdirectories of the Contents directory" of
259  *
260  *    https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html#//apple_ref/doc/uid/10000123i-CH101-SW1
261  *
262  * says that the "Frameworks" directory
263  *
264  *    Contains any private shared libraries and frameworks used by the
265  *    executable.  The frameworks in this directory are revision-locked
266  *    to the application and cannot be superseded by any other, even
267  *    newer, versions that may be available to the operating system.  In
268  *    other words, the frameworks included in this directory take precedence
269  *    over any other similarly named frameworks found in other parts of
270  *    the operating system.  For information on how to add private
271  *    frameworks to your application bundle, see Framework Programming Guide.
272  *
273  * so if we were to ship with any frameworks (e.g. Qt) we should
274  * perhaps put them in a Frameworks directory rather than under
275  * Resources.
276  *
277  * It also says that the "PlugIns" directory
278  *
279  *    Contains loadable bundles that extend the basic features of your
280  *    application. You use this directory to include code modules that
281  *    must be loaded into your applicationbs process space in order to
282  *    be used. You would not use this directory to store standalone
283  *    executables.
284  *
285  * Our plugins are just raw .so/.dylib files; I don't know whether by
286  * "bundles" they mean application bundles (i.e., directory hierarchies)
287  * or just "bundles" in the Mach-O sense (which are an image type that
288  * can be loaded with dlopen() but not linked as libraries; our plugins
289  * are, I think, built as dylibs and can be loaded either way).
290  *
291  * And it says that the "SharedSupport" directory
292  *
293  *    Contains additional non-critical resources that do not impact the
294  *    ability of the application to run. You might use this directory to
295  *    include things like document templates, clip art, and tutorials
296  *    that your application expects to be present but that do not affect
297  *    the ability of your application to run.
298  *
299  * I don't think I'd put the files that currently go under Resources/share
300  * into that category; they're not, for example, sample Lua scripts that
301  * don't actually get run by Wireshark, they're configuration/data files
302  * for Wireshark whose absence might not prevent Wireshark from running
303  * but that would affect how it behaves when run.
304  */
305 static char *appbundle_dir;
306 #endif
307
308 /*
309  * TRUE if we're running from the build directory and we aren't running
310  * with special privileges.
311  */
312 static gboolean running_in_build_directory_flag = FALSE;
313
314 #ifndef _WIN32
315 /*
316  * Get the pathname of the executable using various platform-
317  * dependent mechanisms for various UN*Xes.
318  *
319  * These calls all should return something independent of the argv[0]
320  * passed to the program, so it shouldn't be fooled by an argv[0]
321  * that doesn't match the executable path.
322  *
323  * Sadly, not all UN*Xes necessarily have dladdr(), and those that
324  * do don't necessarily have dladdr(main) return information about
325  * the executable image, and those that do aren't necessarily running
326  * on a platform wherein the executable image can get its own path
327  * from the kernel (either by a call or by it being handed to it along
328  * with argv[] and the environment), and those that can don't
329  * necessarily use that to supply the path you get from dladdr(main),
330  * so we try this first and, if that fails, use dladdr(main) if
331  * available.
332  *
333  * In particular, some dynamic linkers supply a dladdr() such that
334  * dladdr(main) just returns something derived from argv[0], so
335  * just using dladdr(main) is the wrong thing to do if there's
336  * another mechanism that can get you a more reliable version of
337  * the executable path.
338  *
339  * However, at least in newer versions of DragonFly BSD, the dynamic
340  * linker *does* get it from the aux vector passed to the program
341  * by the kernel,  readlink /proc/curproc/file - which came first?
342  *
343  * On OpenBSD, dladdr(main) returns a value derived from argv[0],
344  * and there doesn't appear to be any way to get the executable path
345  * from the kernel, so we're out of luck there.
346  *
347  * So, on platforms where some versions have a version of dladdr()
348  * that gives an argv[0]-based path and that also have a mechanism
349  * to get a more reliable version of the path, we try that.  On
350  * other platforms, we return NULL.  If our caller gets back a NULL
351  * from us, it falls back on dladdr(main) if dladdr() is available,
352  * and if that fails or is unavailable, it falls back on processing
353  * argv[0] itself.
354  *
355  * This is not guaranteed to return an absolute path; if it doesn't,
356  * our caller must prepend the current directory if it's a path.
357  *
358  * This is not guaranteed to return the "real path"; it might return
359  * something with symbolic links in the path.  Our caller must
360  * use realpath() if they want the real thing, but that's also true of
361  * something obtained by looking at argv[0].
362  */
363 static const char *
364 get_executable_path(void)
365 {
366 #if defined(__APPLE__)
367     char *executable_path;
368     uint32_t path_buf_size;
369
370     path_buf_size = PATH_MAX;
371     executable_path = (char *)g_malloc(path_buf_size);
372     if (_NSGetExecutablePath(executable_path, &path_buf_size) == -1) {
373         executable_path = (char *)g_realloc(executable_path, path_buf_size);
374         if (_NSGetExecutablePath(executable_path, &path_buf_size) == -1)
375             return NULL;
376     }
377     return executable_path;
378 #elif defined(__linux__)
379     /*
380      * In older versions of GNU libc's dynamic linker, as used on Linux,
381      * dladdr(main) supplies a path based on argv[0], so we use
382      * /proc/self/exe instead; there are Linux distributions with
383      * kernels that support /proc/self/exe and those older versions
384      * of the dynamic linker, and this will get a better answer on
385      * those versions.
386      *
387      * It only works on Linux 2.2 or later, so we just give up on
388      * earlier versions.
389      *
390      * XXX - are there OS versions that support "exe" but not "self"?
391      */
392     struct utsname name;
393     static char executable_path[PATH_MAX];
394
395     if (uname(&name) == -1)
396         return NULL;
397     if (strncmp(name.release, "1.", 2) == 0)
398         return NULL; /* Linux 1.x */
399     if (strcmp(name.release, "2.0") == 0 ||
400         strncmp(name.release, "2.0.", 4) == 0 ||
401         strcmp(name.release, "2.1") == 0 ||
402         strncmp(name.release, "2.1.", 4) == 0)
403         return NULL; /* Linux 2.0.x or 2.1.x */
404     if (readlink("/proc/self/exe", executable_path, sizeof executable_path) == -1)
405         return NULL;
406     return executable_path;
407 #elif defined(__FreeBSD__) && defined(KERN_PROC_PATHNAME)
408     /*
409      * In older versions of FreeBSD's dynamic linker, dladdr(main)
410      * supplies a path based on argv[0], so we use the KERN_PROC_PATHNAME
411      * sysctl instead; there are, I think, versions of FreeBSD
412      * that support the sysctl that have and those older versions
413      * of the dynamic linker, and this will get a better answer on
414      * those versions.
415      */
416     int mib[4];
417     char *executable_path;
418     size_t path_buf_size;
419
420     mib[0] = CTL_KERN;
421     mib[1] = KERN_PROC;
422     mib[2] = KERN_PROC_PATHNAME;
423     mib[3] = -1;
424     path_buf_size = PATH_MAX;
425     executable_path = (char *)g_malloc(path_buf_size);
426     if (sysctl(mib, 4, executable_path, &path_buf_size, NULL, 0) == -1) {
427         if (errno != ENOMEM)
428             return NULL;
429         executable_path = (char *)g_realloc(executable_path, path_buf_size);
430         if (sysctl(mib, 4, executable_path, &path_buf_size, NULL, 0) == -1)
431             return NULL;
432     }
433     return executable_path;
434 #elif defined(__NetBSD__)
435     /*
436      * In all versions of NetBSD's dynamic linker as of 2013-08-12,
437      * dladdr(main) supplies a path based on argv[0], so we use
438      * /proc/curproc/exe instead.
439      *
440      * XXX - are there OS versions that support "exe" but not "curproc"
441      * or "self"?  Are there any that support "self" but not "curproc"?
442      */
443     static char executable_path[PATH_MAX];
444
445     if (readlink("/proc/curproc/exe", executable_path, sizeof executable_path) == -1)
446         return NULL;
447     return executable_path;
448 #elif defined(__DragonFly__)
449     /*
450      * In older versions of DragonFly BSD's dynamic linker, dladdr(main)
451      * supplies a path based on argv[0], so we use /proc/curproc/file
452      * instead; it appears to be supported by all versions of DragonFly
453      * BSD.
454      */
455     static char executable_path[PATH_MAX];
456
457     if (readlink("/proc/curproc/file", executable_path, sizeof executable_path) == -1)
458         return NULL;
459     return executable_path;
460 #elif (defined(sun) || defined(__sun)) && defined(HAVE_GETEXECNAME)
461     /*
462      * It appears that getexecname() dates back to at least Solaris 8,
463      * but /proc/{pid}/path is first documented in the Solaris 10 documentation,
464      * so we use getexecname() if available, rather than /proc/self/path/a.out
465      * (which isn't documented, but appears to be a symlink to the
466      * executable image file).
467      */
468     return getexecname();
469 #else
470     /* Fill in your favorite UN*X's code here, if there is something */
471     return NULL;
472 #endif
473 }
474 #endif /* _WIN32 */
475
476 /*
477  * Get the pathname of the directory from which the executable came,
478  * and save it for future use.  Returns NULL on success, and a
479  * g_mallocated string containing an error on failure.
480  */
481 char *
482 init_progfile_dir(const char *arg0
483 #ifdef _WIN32
484     _U_
485 #endif
486 , int (*main_addr)(int, char **)
487 #if defined(_WIN32) || !defined(HAVE_DLADDR)
488     _U_
489 #endif
490 )
491 {
492 #ifdef _WIN32
493     TCHAR prog_pathname_w[_MAX_PATH+2];
494     char *prog_pathname;
495     DWORD error;
496     TCHAR *msg_w;
497     guchar *msg;
498     size_t msglen;
499
500     /*
501      * Attempt to get the full pathname of the currently running
502      * program.
503      */
504     if (GetModuleFileName(NULL, prog_pathname_w, G_N_ELEMENTS(prog_pathname_w)) != 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
505         /*
506          * XXX - Should we use g_utf16_to_utf8(), as in
507          * getenv_utf8()?
508          */
509         prog_pathname = utf_16to8(prog_pathname_w);
510         /*
511          * We got it; strip off the last component, which would be
512          * the file name of the executable, giving us the pathname
513          * of the directory where the executable resides.
514          */
515         progfile_dir = g_path_get_dirname(prog_pathname);
516         if (progfile_dir != NULL) {
517             return NULL;    /* we succeeded */
518         } else {
519             /*
520              * OK, no. What do we do now?
521              */
522             return g_strdup_printf("No \\ in executable pathname \"%s\"",
523                 prog_pathname);
524         }
525     } else {
526         /*
527          * Oh, well.  Return an indication of the error.
528          */
529         error = GetLastError();
530         if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
531             NULL, error, 0, (LPTSTR) &msg_w, 0, NULL) == 0) {
532             /*
533              * Gak.  We can't format the message.
534              */
535             return g_strdup_printf("GetModuleFileName failed: %u (FormatMessage failed: %u)",
536                 error, GetLastError());
537         }
538         msg = utf_16to8(msg_w);
539         LocalFree(msg_w);
540         /*
541          * "FormatMessage()" "helpfully" sticks CR/LF at the
542          * end of the message.  Get rid of it.
543          */
544         msglen = strlen(msg);
545         if (msglen >= 2) {
546             msg[msglen - 1] = '\0';
547             msg[msglen - 2] = '\0';
548         }
549         return g_strdup_printf("GetModuleFileName failed: %s (%u)",
550             msg, error);
551     }
552 #else
553 #ifdef HAVE_DLADDR
554     Dl_info info;
555 #endif
556     const char *execname;
557     char *prog_pathname;
558     char *curdir;
559     long path_max;
560     char *pathstr;
561     char *path_start, *path_end;
562     size_t path_component_len, path_len;
563     char *retstr;
564     char *path;
565     char *dir_end;
566
567     /*
568      * Check whether WIRESHARK_RUN_FROM_BUILD_DIRECTORY is set in the
569      * environment; if so, set running_in_build_directory_flag if we
570      * weren't started with special privileges.  (If we were started
571      * with special privileges, it's not safe to allow the user to point
572      * us to some other directory; running_in_build_directory_flag, when
573      * set, causes us to look for plugins and the like in the build
574      * directory.)
575      */
576     if (getenv("WIRESHARK_RUN_FROM_BUILD_DIRECTORY") != NULL
577         && !started_with_special_privs())
578         running_in_build_directory_flag = TRUE;
579
580     execname = get_executable_path();
581 #ifdef HAVE_DLADDR
582     if (main_addr != NULL && execname == NULL) {
583         /*
584          * Try to use dladdr() to find the pathname of the executable.
585          * dladdr() is not guaranteed to give you anything better than
586          * argv[0] (i.e., it might not contain a / at all, much less
587          * being an absolute path), and doesn't appear to do so on
588          * Linux, but on other platforms it could give you an absolute
589          * path and obviate the need for us to determine the absolute
590          * path.
591          */
592         if (dladdr((void *)main_addr, &info))
593             execname = info.dli_fname;
594     }
595 #endif
596     if (execname == NULL) {
597         /*
598          * OK, guess based on argv[0].
599          */
600         execname = arg0;
601     }
602
603     /*
604      * Try to figure out the directory in which the currently running
605      * program resides, given something purporting to be the executable
606      * name (from dladdr() or from the argv[0] it was started with.
607      * That might be the absolute path of the program, or a path relative
608      * to the current directory of the process that started it, or
609      * just a name for the program if it was started from the command
610      * line and was searched for in $PATH.  It's not guaranteed to be
611      * any of those, however, so there are no guarantees....
612      */
613     if (execname[0] == '/') {
614         /*
615          * It's an absolute path.
616          */
617         prog_pathname = g_strdup(execname);
618     } else if (strchr(execname, '/') != NULL) {
619         /*
620          * It's a relative path, with a directory in it.
621          * Get the current directory, and combine it
622          * with that directory.
623          */
624         path_max = pathconf(".", _PC_PATH_MAX);
625         if (path_max == -1) {
626             /*
627              * We have no idea how big a buffer to
628              * allocate for the current directory.
629              */
630             return g_strdup_printf("pathconf failed: %s\n",
631                 g_strerror(errno));
632         }
633         curdir = (char *)g_malloc(path_max);
634         if (getcwd(curdir, path_max) == NULL) {
635             /*
636              * It failed - give up, and just stick
637              * with DATAFILE_DIR.
638              */
639             g_free(curdir);
640             return g_strdup_printf("getcwd failed: %s\n",
641                 g_strerror(errno));
642         }
643         path = g_strdup_printf("%s/%s", curdir, execname);
644         g_free(curdir);
645         prog_pathname = path;
646     } else {
647         /*
648          * It's just a file name.
649          * Search the path for a file with that name
650          * that's executable.
651          */
652         prog_pathname = NULL;   /* haven't found it yet */
653         pathstr = getenv("PATH");
654         path_start = pathstr;
655         if (path_start != NULL) {
656             while (*path_start != '\0') {
657                 path_end = strchr(path_start, ':');
658                 if (path_end == NULL)
659                     path_end = path_start + strlen(path_start);
660                 path_component_len = path_end - path_start;
661                 path_len = path_component_len + 1
662                     + strlen(execname) + 1;
663                 path = (char *)g_malloc(path_len);
664                 memcpy(path, path_start, path_component_len);
665                 path[path_component_len] = '\0';
666                 g_strlcat(path, "/", path_len);
667                 g_strlcat(path, execname, path_len);
668                 if (access(path, X_OK) == 0) {
669                     /*
670                      * Found it!
671                      */
672                     prog_pathname = path;
673                     break;
674                 }
675
676                 /*
677                  * That's not it.  If there are more
678                  * path components to test, try them.
679                  */
680                 if (*path_end == '\0') {
681                     /*
682                      * There's nothing more to try.
683                      */
684                     break;
685                 }
686                 if (*path_end == ':')
687                     path_end++;
688                 path_start = path_end;
689                 g_free(path);
690             }
691             if (prog_pathname == NULL) {
692                 /*
693                  * Program not found in path.
694                  */
695                 return g_strdup_printf("\"%s\" not found in \"%s\"",
696                     execname, pathstr);
697             }
698         } else {
699             /*
700              * PATH isn't set.
701              * XXX - should we pick a default?
702              */
703             return g_strdup("PATH isn't set");
704         }
705     }
706
707     /*
708      * OK, we have what we think is the pathname
709      * of the program.
710      *
711      * First, find the last "/" in the directory,
712      * as that marks the end of the directory pathname.
713      */
714     dir_end = strrchr(prog_pathname, '/');
715     if (dir_end != NULL) {
716         /*
717          * Found it.  Strip off the last component,
718          * as that's the path of the program.
719          */
720         *dir_end = '\0';
721
722         /*
723          * Is there a "/.libs" at the end?
724          */
725         dir_end = strrchr(prog_pathname, '/');
726         if (dir_end != NULL) {
727             if (strcmp(dir_end, "/.libs") == 0) {
728                 /*
729                  * Yup, it's ".libs".
730                  * Strip that off; it's an
731                  * artifact of libtool.
732                  */
733                 *dir_end = '\0';
734
735                 /*
736                  * This presumably means we're run from
737                  * the libtool wrapper, which probably
738                  * means we're being run from the build
739                  * directory.  If we weren't started
740                  * with special privileges, set
741                  * running_in_build_directory_flag.
742                  *
743                  * XXX - should we check whether what
744                  * follows ".libs/" begins with "lt-"?
745                  */
746                 if (!started_with_special_privs())
747                     running_in_build_directory_flag = TRUE;
748             }
749 #ifdef __APPLE__
750             else {
751                 if (!started_with_special_privs()) {
752                     /*
753                      * Scan up the path looking for a component
754                      * named "Contents".  If we find it, we assume
755                      * we're in a bundle, and that the top-level
756                      * directory of the bundle is the one containing
757                      * "Contents".
758                      *
759                      * Not all executables are in the Contents/MacOS
760                      * directory, so we can't just check for those
761                      * in the path and strip them off.
762                      *
763                      * XXX - should we assume that it's either
764                      * Contents/MacOS or Resources/bin?
765                      */
766                     char *component_end, *p;
767
768                     component_end = strchr(prog_pathname, '\0');
769                     p = component_end;
770                     for (;;) {
771                         while (p >= prog_pathname && *p != '/')
772                             p--;
773                         if (p == prog_pathname) {
774                             /*
775                              * We're looking at the first component of
776                              * the pathname now, so we're definitely
777                              * not in a bundle, even if we're in
778                              * "/Contents".
779                              */
780                             break;
781                         }
782                         if (strncmp(p, "/Contents", component_end - p) == 0) {
783                             /* Found it. */
784                             appbundle_dir = (char *)g_malloc(p - prog_pathname + 1);
785                             memcpy(appbundle_dir, prog_pathname, p - prog_pathname);
786                             appbundle_dir[p - prog_pathname] = '\0';
787                             break;
788                         }
789                         component_end = p;
790                         p--;
791                     }
792                 }
793             }
794 #endif
795         }
796
797         /*
798          * OK, we have the path we want.
799          */
800         progfile_dir = prog_pathname;
801         return NULL;
802     } else {
803         /*
804          * This "shouldn't happen"; we apparently
805          * have no "/" in the pathname.
806          * Just free up prog_pathname.
807          */
808         retstr = g_strdup_printf("No / found in \"%s\"", prog_pathname);
809         g_free(prog_pathname);
810         return retstr;
811     }
812 #endif
813 }
814
815 /*
816  * Get the directory in which the program resides.
817  */
818 const char *
819 get_progfile_dir(void)
820 {
821     return progfile_dir;
822 }
823
824 /*
825  * Get the directory in which the global configuration and data files are
826  * stored.
827  *
828  * On Windows, we use the directory in which the executable for this
829  * process resides.
830  *
831  * On UN*X, we use the DATAFILE_DIR value supplied by the configure
832  * script, unless we think we're being run from the build directory,
833  * in which case we use the directory in which the executable for this
834  * process resides.
835  *
836  * XXX - if we ever make libwireshark a real library, used by multiple
837  * applications (more than just TShark and versions of Wireshark with
838  * various UIs), should the configuration files belong to the library
839  * (and be shared by all those applications) or to the applications?
840  *
841  * If they belong to the library, that could be done on UNIX by the
842  * configure script, but it's trickier on Windows, as you can't just
843  * use the pathname of the executable.
844  *
845  * If they belong to the application, that could be done on Windows
846  * by using the pathname of the executable, but we'd have to have it
847  * passed in as an argument, in some call, on UNIX.
848  *
849  * Note that some of those configuration files might be used by code in
850  * libwireshark, some of them might be used by dissectors (would they
851  * belong to libwireshark, the application, or a separate library?),
852  * and some of them might be used by other code (the Wireshark preferences
853  * file includes resolver preferences that control the behavior of code
854  * in libwireshark, dissector preferences, and UI preferences, for
855  * example).
856  */
857 const char *
858 get_datafile_dir(void)
859 {
860 #ifdef _WIN32
861     char *u3deviceexecpath;
862 #endif
863     static const char *datafile_dir = NULL;
864
865     if (datafile_dir != NULL)
866         return datafile_dir;
867
868 #ifdef _WIN32
869     /*
870      * See if we are running in a U3 environment.
871      */
872     u3deviceexecpath = getenv_utf8("U3_DEVICE_EXEC_PATH");
873
874     if (u3deviceexecpath != NULL) {
875         /*
876          * We are; use the U3 device executable path.
877          */
878         datafile_dir = u3deviceexecpath;
879     } else {
880         /*
881          * Do we have the pathname of the program?  If so, assume we're
882          * running an installed version of the program.  If we fail,
883          * we don't change "datafile_dir", and thus end up using the
884          * default.
885          *
886          * XXX - does NSIS put the installation directory into
887          * "\HKEY_LOCAL_MACHINE\SOFTWARE\Wireshark\InstallDir"?
888          * If so, perhaps we should read that from the registry,
889          * instead.
890          */
891         if (progfile_dir != NULL) {
892             /*
893              * Yes, we do; use that.
894              */
895             datafile_dir = progfile_dir;
896         } else {
897             /*
898              * No, we don't.
899              * Fall back on the default installation directory.
900              */
901             datafile_dir = "C:\\Program Files\\Wireshark\\";
902         }
903     }
904 #else
905
906     if (running_in_build_directory_flag) {
907         /*
908          * We're (probably) being run from the build directory and
909          * weren't started with special privileges.
910          *
911          * (running_in_build_directory_flag is never set to TRUE
912          * if we're started with special privileges, so we need
913          * only check it; we don't need to call started_with_special_privs().)
914          *
915          * Use the top-level source directory as the datafile directory
916          * because most of our data files (radius/, COPYING) are there.
917          */
918         datafile_dir = g_strdup(TOP_SRCDIR);
919         return datafile_dir;
920     } else {
921         if (getenv("WIRESHARK_DATA_DIR") && !started_with_special_privs()) {
922             /*
923              * The user specified a different directory for data files
924              * and we aren't running with special privileges.
925              * XXX - We might be able to dispense with the priv check
926              */
927             datafile_dir = g_strdup(getenv("WIRESHARK_DATA_DIR"));
928         }
929 #ifdef __APPLE__
930         /*
931          * If we're running from an app bundle and weren't started
932          * with special privileges, use the Contents/Resources/share/wireshark
933          * subdirectory of the app bundle.
934          *
935          * (appbundle_dir is not set to a non-null value if we're
936          * started with special privileges, so we need only check
937          * it; we don't need to call started_with_special_privs().)
938          */
939         else if (appbundle_dir != NULL) {
940             datafile_dir = g_strdup_printf("%s/Contents/Resources/share/wireshark",
941                                            appbundle_dir);
942         }
943 #endif
944         else {
945             datafile_dir = DATAFILE_DIR;
946         }
947     }
948
949 #endif
950     return datafile_dir;
951 }
952
953 #if defined(HAVE_PLUGINS) || defined(HAVE_LUA)
954 /*
955  * Find the directory where the plugins are stored.
956  *
957  * On Windows, we use the "plugin" subdirectory of the datafile directory.
958  *
959  * On UN*X, we use the PLUGIN_INSTALL_DIR value supplied by the configure
960  * script, unless we think we're being run from the build directory,
961  * in which case we use the "plugin" subdirectory of the datafile directory.
962  *
963  * In both cases, we then use the subdirectory of that directory whose
964  * name is the version number.
965  *
966  * XXX - if we think we're being run from the build directory, perhaps we
967  * should have the plugin code not look in the version subdirectory
968  * of the plugin directory, but look in all of the subdirectories
969  * of the plugin directory, so it can just fetch the plugins built
970  * as part of the build process.
971  */
972 static const char *plugin_dir = NULL;
973
974 static void
975 init_plugin_dir(void)
976 {
977 #ifdef _WIN32
978     /*
979      * On Windows, the data file directory is the installation
980      * directory; the plugins are stored under it.
981      *
982      * Assume we're running the installed version of Wireshark;
983      * on Windows, the data file directory is the directory
984      * in which the Wireshark binary resides.
985      */
986     plugin_dir = g_strdup_printf("%s\\plugins\\%s", get_datafile_dir(),
987                      VERSION);
988
989     /*
990      * Make sure that pathname refers to a directory.
991      */
992     if (test_for_directory(plugin_dir) != EISDIR) {
993         /*
994          * Either it doesn't refer to a directory or it
995          * refers to something that doesn't exist.
996          *
997          * Assume that means we're running a version of
998          * Wireshark we've built in a build directory,
999          * in which case {datafile dir}\plugins is the
1000          * top-level plugins source directory, and use
1001          * that directory and set the "we're running in
1002          * a build directory" flag, so the plugin
1003          * scanner will check all subdirectories of that
1004          * directory for plugins.
1005          */
1006         g_free( (gpointer) plugin_dir);
1007         plugin_dir = g_strdup_printf("%s\\plugins", get_datafile_dir());
1008         running_in_build_directory_flag = TRUE;
1009     }
1010 #else
1011     if (running_in_build_directory_flag) {
1012         /*
1013          * We're (probably) being run from the build directory and
1014          * weren't started with special privileges, so we'll use
1015          * the "plugins" subdirectory of the directory where the program
1016          * we're running is (that's the build directory).
1017          */
1018         plugin_dir = g_strdup_printf("%s/plugins", get_progfile_dir());
1019     } else {
1020         if (getenv("WIRESHARK_PLUGIN_DIR") && !started_with_special_privs()) {
1021             /*
1022              * The user specified a different directory for plugins
1023              * and we aren't running with special privileges.
1024              */
1025             plugin_dir = g_strdup(getenv("WIRESHARK_PLUGIN_DIR"));
1026         }
1027 #ifdef __APPLE__
1028         /*
1029          * If we're running from an app bundle and weren't started
1030          * with special privileges, use the Contents/PlugIns/wireshark
1031          * subdirectory of the app bundle.
1032          *
1033          * (appbundle_dir is not set to a non-null value if we're
1034          * started with special privileges, so we need only check
1035          * it; we don't need to call started_with_special_privs().)
1036          */
1037         else if (appbundle_dir != NULL) {
1038             plugin_dir = g_strdup_printf("%s/Contents/PlugIns/wireshark",
1039                                          appbundle_dir);
1040         }
1041 #endif
1042         else {
1043             plugin_dir = PLUGIN_INSTALL_DIR;
1044         }
1045     }
1046 #endif
1047 }
1048 #endif /* HAVE_PLUGINS || HAVE_LUA */
1049
1050 /*
1051  * Get the directory in which the plugins are stored.
1052  */
1053 const char *
1054 get_plugin_dir(void)
1055 {
1056 #if defined(HAVE_PLUGINS) || defined(HAVE_LUA)
1057     if (!plugin_dir) init_plugin_dir();
1058     return plugin_dir;
1059 #else
1060     return NULL;
1061 #endif
1062 }
1063
1064 #if defined(HAVE_EXTCAP)
1065 /*
1066  * Find the directory where the extcap hooks are stored.
1067  *
1068  * On Windows, we use the "extcap" subdirectory of the datafile directory.
1069  *
1070  * On UN*X, we use the EXTCAP_DIR value supplied by the configure
1071  * script, unless we think we're being run from the build directory,
1072  * in which case we use the "extcap" subdirectory of the datafile directory.
1073  *
1074  * In both cases, we then use the subdirectory of that directory whose
1075  * name is the version number.
1076  *
1077  * XXX - if we think we're being run from the build directory, perhaps we
1078  * should have the extcap code not look in the version subdirectory
1079  * of the extcap directory, but look in all of the subdirectories
1080  * of the extcap directory, so it can just fetch the extcap hooks built
1081  * as part of the build process.
1082  */
1083 static const char *extcap_dir = NULL;
1084
1085 static void init_extcap_dir(void) {
1086 #ifdef _WIN32
1087     /*
1088      * On Windows, the data file directory is the installation
1089      * directory; the extcap hooks are stored under it.
1090      *
1091      * Assume we're running the installed version of Wireshark;
1092      * on Windows, the data file directory is the directory
1093      * in which the Wireshark binary resides.
1094      */
1095     extcap_dir = g_strdup_printf("%s\\extcap\\%s", get_datafile_dir(),
1096                                  VERSION);
1097
1098     /*
1099      * Make sure that pathname refers to a directory.
1100      */
1101     if (test_for_directory(extcap_dir) != EISDIR) {
1102         /*
1103          * Either it doesn't refer to a directory or it
1104          * refers to something that doesn't exist.
1105          *
1106          * Assume that means we're running a version of
1107          * Wireshark we've built in a build directory,
1108          * in which case {datafile dir}\plugins is the
1109          * top-level extcap hooks source directory, and use
1110          * that directory and set the "we're running in
1111          * a build directory" flag, so the plugin
1112          * scanner will check all subdirectories of that
1113          * directory for extcap hooks.
1114          */
1115         g_free( (gpointer) extcap_dir);
1116         extcap_dir = g_strdup_printf("%s\\extcap", get_datafile_dir());
1117         running_in_build_directory_flag = TRUE;
1118     }
1119 #else
1120     if (running_in_build_directory_flag) {
1121         /*
1122          * We're (probably) being run from the build directory and
1123          * weren't started with special privileges, so we'll use
1124          * the "extcap hooks" subdirectory of the directory where the program
1125          * we're running is (that's the build directory).
1126          */
1127         extcap_dir = g_strdup_printf("%s/extcap", get_progfile_dir());
1128     } else {
1129         if (getenv("WIRESHARK_EXTCAP_DIR") && !started_with_special_privs()) {
1130             /*
1131              * The user specified a different directory for extcap hooks
1132              * and we aren't running with special privileges.
1133              */
1134             extcap_dir = g_strdup(getenv("WIRESHARK_EXTCAP_DIR"));
1135         }
1136 #ifdef __APPLE__
1137         /*
1138          * If we're running from an app bundle and weren't started
1139          * with special privileges, use the Contents/Resources/lib/wireshark/extcap
1140          * subdirectory of the app bundle.
1141          *
1142          * (appbundle_dir is not set to a non-null value if we're
1143          * started with special privileges, so we need only check
1144          * it; we don't need to call started_with_special_privs().)
1145          */
1146         else if (appbundle_dir != NULL) {
1147             extcap_dir = g_strdup_printf("%s/Contents/Resources/lib/wireshark/extcap",
1148                                          appbundle_dir);
1149         }
1150 #endif
1151         else {
1152             extcap_dir = EXTCAP_DIR;
1153         }
1154     }
1155 #endif
1156 }
1157 #endif /* HAVE_EXTCAP */
1158
1159 /*
1160  * Get the directory in which the extcap hooks are stored.
1161  *
1162  * XXX - A fix instead of HAVE_EXTCAP must be found
1163  */
1164 const char *
1165 get_extcap_dir(void) {
1166 #if defined(HAVE_EXTCAP)
1167     if (!extcap_dir)
1168         init_extcap_dir();
1169     return extcap_dir;
1170 #else
1171     return NULL;
1172 #endif
1173 }
1174
1175 /*
1176  * Get the flag indicating whether we're running from a build
1177  * directory.
1178  */
1179 gboolean
1180 running_in_build_directory(void)
1181 {
1182     return running_in_build_directory_flag;
1183 }
1184
1185 /*
1186  * Get the directory in which files that, at least on UNIX, are
1187  * system files (such as "/etc/ethers") are stored; on Windows,
1188  * there's no "/etc" directory, so we get them from the global
1189  * configuration and data file directory.
1190  */
1191 const char *
1192 get_systemfile_dir(void)
1193 {
1194 #ifdef _WIN32
1195     return get_datafile_dir();
1196 #else
1197     return "/etc";
1198 #endif
1199 }
1200
1201 /*
1202  * Name of directory, under the user's home directory, in which
1203  * personal configuration files are stored.
1204  */
1205 #ifdef _WIN32
1206 #define PF_DIR "Wireshark"
1207 #else
1208 /*
1209  * XXX - should this be ".libepan"? For backwards-compatibility, I'll keep
1210  * it ".wireshark" for now.
1211  */
1212 #define PF_DIR ".wireshark"
1213 #endif
1214
1215 void
1216 set_profile_name(const gchar *profilename)
1217 {
1218     g_free (persconfprofile);
1219
1220     if (profilename && strlen(profilename) > 0 &&
1221         strcmp(profilename, DEFAULT_PROFILE) != 0) {
1222         persconfprofile = g_strdup (profilename);
1223     } else {
1224         /* Default Profile */
1225         persconfprofile = NULL;
1226     }
1227 }
1228
1229 const char *
1230 get_profile_name(void)
1231 {
1232     if (persconfprofile) {
1233         return persconfprofile;
1234     } else {
1235         return DEFAULT_PROFILE;
1236     }
1237 }
1238
1239 gboolean
1240 is_default_profile(void)
1241 {
1242     return (!persconfprofile || strcmp(persconfprofile, DEFAULT_PROFILE) == 0) ? TRUE : FALSE;
1243 }
1244
1245 gboolean
1246 has_global_profiles(void)
1247 {
1248     WS_DIR *dir;
1249     WS_DIRENT *file;
1250     const gchar *global_dir = get_global_profiles_dir();
1251     gchar *filename;
1252     gboolean has_global = FALSE;
1253
1254     if ((test_for_directory(global_dir) == EISDIR) &&
1255         ((dir = ws_dir_open(global_dir, 0, NULL)) != NULL))
1256     {
1257         while ((file = ws_dir_read_name(dir)) != NULL) {
1258             filename = g_strdup_printf ("%s%s%s", global_dir, G_DIR_SEPARATOR_S,
1259                             ws_dir_get_name(file));
1260             if (test_for_directory(filename) == EISDIR) {
1261                 has_global = TRUE;
1262                 g_free (filename);
1263                 break;
1264             }
1265             g_free (filename);
1266         }
1267         ws_dir_close(dir);
1268     }
1269
1270     return has_global;
1271 }
1272
1273 void
1274 profile_store_persconffiles(gboolean store)
1275 {
1276     if (store) {
1277         profile_files = g_hash_table_new (g_str_hash, g_str_equal);
1278     }
1279     do_store_persconffiles = store;
1280 }
1281
1282 /*
1283  * Get the directory in which personal configuration files reside;
1284  * in UNIX-compatible systems, it's ".wireshark", under the user's home
1285  * directory, and on Windows systems, it's "Wireshark", under %APPDATA%
1286  * or, if %APPDATA% isn't set, it's "%USERPROFILE%\Application Data"
1287  * (which is what %APPDATA% normally is on Windows 2000).
1288  */
1289 static const char *
1290 get_persconffile_dir_no_profile(void)
1291 {
1292 #ifdef _WIN32
1293     char *appdatadir;
1294     char *userprofiledir;
1295     char *altappdatapath;
1296 #else
1297     const char *homedir;
1298     struct passwd *pwd;
1299 #endif
1300
1301     /* Return the cached value, if available */
1302     if (persconffile_dir != NULL)
1303         return persconffile_dir;
1304
1305 #ifdef _WIN32
1306     /*
1307      * See if the user has selected an alternate environment.
1308      */
1309     altappdatapath = getenv_utf8("WIRESHARK_APPDATA");
1310     if (altappdatapath != NULL) {
1311         persconffile_dir = altappdatapath;
1312         return persconffile_dir;
1313     }
1314
1315     /*
1316      * See if we are running in a U3 environment.
1317      */
1318     altappdatapath = getenv_utf8("U3_APP_DATA_PATH");
1319     if (altappdatapath != NULL) {
1320         /*
1321          * We are; use the U3 application data path.
1322          */
1323         persconffile_dir = altappdatapath;
1324     } else {
1325         /*
1326          * Use %APPDATA% or %USERPROFILE%, so that configuration
1327          * files are stored in the user profile, rather than in
1328          * the home directory.  The Windows convention is to store
1329          * configuration information in the user profile, and doing
1330          * so means you can use Wireshark even if the home directory
1331          * is an inaccessible network drive.
1332          */
1333         appdatadir = getenv_utf8("APPDATA");
1334         if (appdatadir != NULL) {
1335             /*
1336              * Concatenate %APPDATA% with "\Wireshark".
1337              */
1338             persconffile_dir = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1339                                appdatadir, PF_DIR);
1340         } else {
1341             /*
1342              * OK, %APPDATA% wasn't set, so use
1343              * %USERPROFILE%\Application Data.
1344              */
1345             userprofiledir = getenv_utf8("USERPROFILE");
1346             if (userprofiledir != NULL) {
1347                 persconffile_dir = g_strdup_printf(
1348                     "%s" G_DIR_SEPARATOR_S "Application Data" G_DIR_SEPARATOR_S "%s",
1349                     userprofiledir, PF_DIR);
1350             } else {
1351                 /*
1352                  * Give up and use "C:".
1353                  */
1354                 persconffile_dir = g_strdup_printf("C:" G_DIR_SEPARATOR_S "%s", PF_DIR);
1355             }
1356         }
1357     }
1358 #else
1359     /*
1360      * If $HOME is set, use that.
1361      */
1362     homedir = getenv("HOME");
1363     if (homedir == NULL) {
1364         /*
1365          * Get their home directory from the password file.
1366          * If we can't even find a password file entry for them,
1367          * use "/tmp".
1368          */
1369         pwd = getpwuid(getuid());
1370         if (pwd != NULL) {
1371             homedir = pwd->pw_dir;
1372         } else {
1373             homedir = "/tmp";
1374         }
1375     }
1376     persconffile_dir = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", homedir, PF_DIR);
1377 #endif
1378
1379     return persconffile_dir;
1380 }
1381
1382 void
1383 set_persconffile_dir(const char *p)
1384 {
1385     g_free(persconffile_dir);
1386     persconffile_dir = g_strdup(p);
1387 }
1388
1389 const char *
1390 get_profiles_dir(void)
1391 {
1392     static char *profiles_dir = NULL;
1393
1394     g_free (profiles_dir);
1395     profiles_dir = g_strdup_printf ("%s%s%s", get_persconffile_dir_no_profile (),
1396                     G_DIR_SEPARATOR_S, PROFILES_DIR);
1397
1398     return profiles_dir;
1399 }
1400
1401 const char *
1402 get_global_profiles_dir(void)
1403 {
1404     static char *global_profiles_dir = NULL;
1405
1406     if (!global_profiles_dir) {
1407         global_profiles_dir = g_strdup_printf ("%s%s%s", get_datafile_dir(),
1408                                G_DIR_SEPARATOR_S, PROFILES_DIR);
1409     }
1410
1411     return global_profiles_dir;
1412 }
1413
1414 static const char *
1415 get_persconffile_dir(const gchar *profilename)
1416 {
1417     static char *persconffile_profile_dir = NULL;
1418
1419     g_free (persconffile_profile_dir);
1420
1421     if (profilename && strlen(profilename) > 0 &&
1422         strcmp(profilename, DEFAULT_PROFILE) != 0) {
1423       persconffile_profile_dir = g_strdup_printf ("%s%s%s", get_profiles_dir (),
1424                               G_DIR_SEPARATOR_S, profilename);
1425     } else {
1426       persconffile_profile_dir = g_strdup (get_persconffile_dir_no_profile ());
1427     }
1428
1429     return persconffile_profile_dir;
1430 }
1431
1432 gboolean
1433 profile_exists(const gchar *profilename, gboolean global)
1434 {
1435     if (global) {
1436         gchar *path = g_strdup_printf ("%s%s%s", get_global_profiles_dir(),
1437                            G_DIR_SEPARATOR_S, profilename);
1438         if (test_for_directory (path) == EISDIR) {
1439             g_free (path);
1440             return TRUE;
1441         }
1442         g_free (path);
1443     } else {
1444         if (test_for_directory (get_persconffile_dir (profilename)) == EISDIR) {
1445             return TRUE;
1446         }
1447     }
1448
1449     return FALSE;
1450 }
1451
1452 static int
1453 delete_directory (const char *directory, char **pf_dir_path_return)
1454 {
1455     WS_DIR *dir;
1456     WS_DIRENT *file;
1457     gchar *filename;
1458     int ret = 0;
1459
1460     if ((dir = ws_dir_open(directory, 0, NULL)) != NULL) {
1461         while ((file = ws_dir_read_name(dir)) != NULL) {
1462             filename = g_strdup_printf ("%s%s%s", directory, G_DIR_SEPARATOR_S,
1463                             ws_dir_get_name(file));
1464             if (test_for_directory(filename) != EISDIR) {
1465                 ret = ws_remove(filename);
1466 #if 0
1467             } else {
1468                 /* The user has manually created a directory in the profile directory */
1469                 /* I do not want to delete the directory recursively yet */
1470                 ret = delete_directory (filename, pf_dir_path_return);
1471 #endif
1472             }
1473             if (ret != 0) {
1474                 *pf_dir_path_return = filename;
1475                 break;
1476             }
1477             g_free (filename);
1478         }
1479         ws_dir_close(dir);
1480     }
1481
1482     if (ret == 0 && (ret = ws_remove(directory)) != 0) {
1483         *pf_dir_path_return = g_strdup (directory);
1484     }
1485
1486     return ret;
1487 }
1488
1489 int
1490 delete_persconffile_profile(const char *profilename, char **pf_dir_path_return)
1491 {
1492     const char *profile_dir = get_persconffile_dir(profilename);
1493     int ret = 0;
1494
1495     if (test_for_directory (profile_dir) == EISDIR) {
1496         ret = delete_directory (profile_dir, pf_dir_path_return);
1497     }
1498
1499     return ret;
1500 }
1501
1502 int
1503 rename_persconffile_profile(const char *fromname, const char *toname,
1504                 char **pf_from_dir_path_return, char **pf_to_dir_path_return)
1505 {
1506     char *from_dir = g_strdup (get_persconffile_dir(fromname));
1507     char *to_dir = g_strdup (get_persconffile_dir(toname));
1508     int ret = 0;
1509
1510     ret = ws_rename (from_dir, to_dir);
1511     if (ret != 0) {
1512         *pf_from_dir_path_return = g_strdup (from_dir);
1513         *pf_to_dir_path_return = g_strdup (to_dir);
1514     }
1515
1516     g_free (from_dir);
1517     g_free (to_dir);
1518
1519     return ret;
1520 }
1521
1522 /*
1523  * Create the directory that holds personal configuration files, if
1524  * necessary.  If we attempted to create it, and failed, return -1 and
1525  * set "*pf_dir_path_return" to the pathname of the directory we failed
1526  * to create (it's g_mallocated, so our caller should free it); otherwise,
1527  * return 0.
1528  */
1529 int
1530 create_persconffile_profile(const char *profilename, char **pf_dir_path_return)
1531 {
1532     const char *pf_dir_path;
1533 #ifdef _WIN32
1534     char *pf_dir_path_copy, *pf_dir_parent_path;
1535     size_t pf_dir_parent_path_len;
1536 #endif
1537     ws_statb64 s_buf;
1538     int ret;
1539
1540     if (profilename) {
1541         /*
1542          * Create the "Default" personal configuration files directory, if necessary.
1543          */
1544         if (create_persconffile_profile (NULL, pf_dir_path_return) == -1) {
1545             return -1;
1546         }
1547
1548         /*
1549          * Check if profiles directory exists.
1550          * If not then create it.
1551          */
1552         pf_dir_path = get_profiles_dir ();
1553         if (ws_stat64(pf_dir_path, &s_buf) != 0 && errno == ENOENT) {
1554             ret = ws_mkdir(pf_dir_path, 0755);
1555             if (ret == -1) {
1556                 *pf_dir_path_return = g_strdup(pf_dir_path);
1557                 return ret;
1558             }
1559         }
1560     }
1561
1562     pf_dir_path = get_persconffile_dir(profilename);
1563     if (ws_stat64(pf_dir_path, &s_buf) != 0 && errno == ENOENT) {
1564 #ifdef _WIN32
1565         /*
1566          * Does the parent directory of that directory
1567          * exist?  %APPDATA% may not exist even though
1568          * %USERPROFILE% does.
1569          *
1570          * We check for the existence of the directory
1571          * by first checking whether the parent directory
1572          * is just a drive letter and, if it's not, by
1573          * doing a "stat()" on it.  If it's a drive letter,
1574          * or if the "stat()" succeeds, we assume it exists.
1575          */
1576         pf_dir_path_copy = g_strdup(pf_dir_path);
1577         pf_dir_parent_path = get_dirname(pf_dir_path_copy);
1578         pf_dir_parent_path_len = strlen(pf_dir_parent_path);
1579         if (pf_dir_parent_path_len > 0
1580             && pf_dir_parent_path[pf_dir_parent_path_len - 1] != ':'
1581             && ws_stat64(pf_dir_parent_path, &s_buf) != 0) {
1582             /*
1583              * No, it doesn't exist - make it first.
1584              */
1585             ret = ws_mkdir(pf_dir_parent_path, 0755);
1586             if (ret == -1) {
1587                 *pf_dir_path_return = pf_dir_parent_path;
1588                 return -1;
1589             }
1590         }
1591         g_free(pf_dir_path_copy);
1592         ret = ws_mkdir(pf_dir_path, 0755);
1593 #else
1594         ret = ws_mkdir(pf_dir_path, 0755);
1595 #endif
1596     } else {
1597         /*
1598          * Something with that pathname exists; if it's not
1599          * a directory, we'll get an error if we try to put
1600          * something in it, so we don't fail here, we wait
1601          * for that attempt fo fail.
1602          */
1603         ret = 0;
1604     }
1605     if (ret == -1)
1606         *pf_dir_path_return = g_strdup(pf_dir_path);
1607     return ret;
1608 }
1609
1610 int
1611 create_persconffile_dir(char **pf_dir_path_return)
1612 {
1613   return create_persconffile_profile(persconfprofile, pf_dir_path_return);
1614 }
1615
1616 int
1617 copy_persconffile_profile(const char *toname, const char *fromname, gboolean from_global,
1618               char **pf_filename_return, char **pf_to_dir_path_return, char **pf_from_dir_path_return)
1619 {
1620     gchar *from_dir;
1621     gchar *to_dir = g_strdup (get_persconffile_dir(toname));
1622     gchar *filename, *from_file, *to_file;
1623     GList *files, *file;
1624
1625     if (from_global) {
1626         if (strcmp(fromname, DEFAULT_PROFILE) == 0) {
1627             from_dir = g_strdup (get_global_profiles_dir());
1628         } else {
1629             from_dir = g_strdup_printf ("%s%s%s", get_global_profiles_dir(), G_DIR_SEPARATOR_S, fromname);
1630         }
1631     } else {
1632         from_dir = g_strdup (get_persconffile_dir(fromname));
1633     }
1634
1635     files = g_hash_table_get_keys(profile_files);
1636     file = g_list_first(files);
1637     while (file) {
1638         filename = (gchar *)file->data;
1639         from_file = g_strdup_printf ("%s%s%s", from_dir, G_DIR_SEPARATOR_S, filename);
1640         to_file =  g_strdup_printf ("%s%s%s", to_dir, G_DIR_SEPARATOR_S, filename);
1641
1642         if (file_exists(from_file) && !copy_file_binary_mode(from_file, to_file)) {
1643             *pf_filename_return = g_strdup(filename);
1644             *pf_to_dir_path_return = to_dir;
1645             *pf_from_dir_path_return = from_dir;
1646             g_free (from_file);
1647             g_free (to_file);
1648             return -1;
1649         }
1650
1651         g_free (from_file);
1652         g_free (to_file);
1653
1654         file = g_list_next(file);
1655     }
1656
1657     g_list_free (files);
1658     g_free (from_dir);
1659     g_free (to_dir);
1660
1661     return 0;
1662 }
1663
1664 /*
1665  * Get the (default) directory in which personal data is stored.
1666  *
1667  * On Win32, this is the "My Documents" folder in the personal profile,
1668  * except that, if we're running from a U3 device, this is the
1669  * "$U3_DEVICE_DOCUMENT_PATH\My Captures" folder.
1670  * On UNIX this is simply the current directory.
1671  */
1672 /* XXX - should this and the get_home_dir() be merged? */
1673 extern const char *
1674 get_persdatafile_dir(void)
1675 {
1676 #ifdef _WIN32
1677     char *u3devicedocumentpath;
1678     TCHAR tszPath[MAX_PATH];
1679
1680     /* Return the cached value, if available */
1681     if (persdatafile_dir != NULL)
1682         return persdatafile_dir;
1683
1684     /*
1685      * See if we are running in a U3 environment.
1686      */
1687     u3devicedocumentpath = getenv_utf8("U3_DEVICE_DOCUMENT_PATH");
1688
1689     if (u3devicedocumentpath != NULL) {
1690         /* the "My Captures" sub-directory is created (if it doesn't
1691            exist) by u3util.exe when the U3 Wireshark is first run */
1692
1693         persdatafile_dir = g_strdup_printf("%s%s", u3devicedocumentpath, U3_MY_CAPTURES);
1694         return persdatafile_dir;
1695     } else {
1696         /*
1697          * Hint: SHGetFolderPath is not available on MSVC 6 - without
1698          * Platform SDK
1699          */
1700         if (SHGetSpecialFolderPath(NULL, tszPath, CSIDL_PERSONAL, FALSE)) {
1701             persdatafile_dir = g_utf16_to_utf8(tszPath, -1, NULL, NULL, NULL);
1702             return persdatafile_dir;
1703         } else {
1704             return "";
1705         }
1706     }
1707 #else
1708     return "";
1709 #endif
1710 }
1711
1712 void
1713 set_persdatafile_dir(const char *p)
1714 {
1715     g_free(persdatafile_dir);
1716     persdatafile_dir = g_strdup(p);
1717 }
1718
1719 #ifdef _WIN32
1720 /*
1721  * Returns the user's home directory on Win32.
1722  */
1723 static const char *
1724 get_home_dir(void)
1725 {
1726     static const char *home = NULL;
1727     char *homedrive, *homepath;
1728     char *homestring;
1729     char *lastsep;
1730
1731     /* Return the cached value, if available */
1732     if (home)
1733         return home;
1734
1735     /*
1736      * XXX - should we use USERPROFILE anywhere in this process?
1737      * Is there a chance that it might be set but one or more of
1738      * HOMEDRIVE or HOMEPATH isn't set?
1739      */
1740     homedrive = getenv_utf8("HOMEDRIVE");
1741     if (homedrive != NULL) {
1742         homepath = getenv_utf8("HOMEPATH");
1743         if (homepath != NULL) {
1744             /*
1745              * This is cached, so we don't need to worry about
1746              * allocating multiple ones of them.
1747              */
1748             homestring = g_strdup_printf("%s%s", homedrive, homepath);
1749
1750             /*
1751              * Trim off any trailing slash or backslash.
1752              */
1753             lastsep = find_last_pathname_separator(homestring);
1754             if (lastsep != NULL && *(lastsep + 1) == '\0') {
1755                 /*
1756                  * Last separator is the last character
1757                  * in the string.  Nuke it.
1758                  */
1759                 *lastsep = '\0';
1760             }
1761             home = homestring;
1762         } else
1763             home = homedrive;
1764     } else {
1765         /*
1766          * Give up and use C:.
1767          */
1768         home = "C:";
1769     }
1770
1771     return home;
1772 }
1773 #endif
1774
1775 /*
1776  * Construct the path name of a personal configuration file, given the
1777  * file name.
1778  *
1779  * On Win32, if "for_writing" is FALSE, we check whether the file exists
1780  * and, if not, construct a path name relative to the ".wireshark"
1781  * subdirectory of the user's home directory, and check whether that
1782  * exists; if it does, we return that, so that configuration files
1783  * from earlier versions can be read.
1784  *
1785  * The returned file name was g_malloc()'d so it must be g_free()d when the
1786  * caller is done with it.
1787  */
1788 char *
1789 get_persconffile_path(const char *filename, gboolean from_profile)
1790 {
1791     char *path;
1792     if (do_store_persconffiles && from_profile && !g_hash_table_lookup (profile_files, filename)) {
1793         /* Store filenames so we know which filenames belongs to a configuration profile */
1794         g_hash_table_insert (profile_files, g_strdup(filename), g_strdup(filename));
1795     }
1796
1797     if (from_profile) {
1798       path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1799                  get_persconffile_dir(persconfprofile), filename);
1800     } else {
1801       path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1802                  get_persconffile_dir(NULL), filename);
1803     }
1804
1805     return path;
1806 }
1807
1808 /*
1809  * Construct the path name of a global configuration file, given the
1810  * file name.
1811  *
1812  * The returned file name was g_malloc()'d so it must be g_free()d when the
1813  * caller is done with it.
1814  */
1815 char *
1816 get_datafile_path(const char *filename)
1817 {
1818     if (running_in_build_directory_flag &&
1819         (!strcmp(filename, "AUTHORS-SHORT") ||
1820          !strcmp(filename, "hosts"))) {
1821         /* We're running in the build directory and the requested file is a
1822          * generated (or a test) file.  Return the file name in the build
1823          * directory (not in the source/data directory).
1824          * (Oh the things we do to keep the source directory pristine...)
1825          */
1826         return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", get_progfile_dir(), filename);
1827     } else {
1828         return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", get_datafile_dir(), filename);
1829     }
1830 }
1831
1832 /* Get the personal plugin dir */
1833 /* Return value is malloced so the caller should g_free() it. */
1834 char *
1835 get_plugins_pers_dir(void)
1836 {
1837     return get_persconffile_path(PLUGINS_DIR_NAME, FALSE);
1838 }
1839
1840 /*
1841  * Return an error message for UNIX-style errno indications on open or
1842  * create operations.
1843  */
1844 const char *
1845 file_open_error_message(int err, gboolean for_writing)
1846 {
1847     const char *errmsg;
1848     static char errmsg_errno[1024+1];
1849
1850     switch (err) {
1851
1852     case ENOENT:
1853         if (for_writing)
1854             errmsg = "The path to the file \"%s\" doesn't exist.";
1855         else
1856             errmsg = "The file \"%s\" doesn't exist.";
1857         break;
1858
1859     case EACCES:
1860         if (for_writing)
1861             errmsg = "You don't have permission to create or write to the file \"%s\".";
1862         else
1863             errmsg = "You don't have permission to read the file \"%s\".";
1864         break;
1865
1866     case EISDIR:
1867         errmsg = "\"%s\" is a directory (folder), not a file.";
1868         break;
1869
1870     case ENOSPC:
1871         errmsg = "The file \"%s\" could not be created because there is no space left on the file system.";
1872         break;
1873
1874 #ifdef EDQUOT
1875     case EDQUOT:
1876         errmsg = "The file \"%s\" could not be created because you are too close to, or over, your disk quota.";
1877         break;
1878 #endif
1879
1880     case EINVAL:
1881         errmsg = "The file \"%s\" could not be created because an invalid filename was specified.";
1882         break;
1883
1884     case ENOMEM:
1885         /*
1886          * The problem probably has nothing to do with how much RAM the
1887          * user has on their machine, so don't confuse them by saying
1888          * "memory".  The problem is probably either virtual address
1889          * space or swap space.
1890          */
1891 #if GLIB_SIZEOF_VOID_P == 4
1892         /*
1893          * ILP32; we probably ran out of virtual address space.
1894          */
1895 #define ENOMEM_REASON "it can't be handled by a 32-bit application"
1896 #else
1897         /*
1898          * LP64 or LLP64; we probably ran out of swap space.
1899          */
1900 #if defined(_WIN32)
1901         /*
1902          * You need to make the pagefile bigger.
1903          */
1904 #define ENOMEM_REASON "the pagefile is too small"
1905 #elif defined(__APPLE__)
1906         /*
1907          * dynamic_pager couldn't, or wouldn't, create more swap files.
1908          */
1909 #define ENOMEM_REASON "your system ran out of swap file space"
1910 #else
1911         /*
1912          * Either you have a fixed swap partition or a fixed swap file,
1913          * and it needs to be made bigger.
1914          *
1915          * This is UN*X, but it's not OS X, so we assume the user is
1916          * *somewhat* nerdy.
1917          */
1918 #define ENOMEM_REASON "your system is out of swap space"
1919 #endif
1920 #endif /* GLIB_SIZEOF_VOID_P == 4 */
1921         if (for_writing)
1922             errmsg = "The file \"%s\" could not be created because " ENOMEM_REASON ".";
1923         else
1924             errmsg = "The file \"%s\" could not be opened because " ENOMEM_REASON ".";
1925         break;
1926
1927     default:
1928         g_snprintf(errmsg_errno, sizeof(errmsg_errno),
1929                "The file \"%%s\" could not be %s: %s.",
1930                for_writing ? "created" : "opened",
1931                g_strerror(err));
1932         errmsg = errmsg_errno;
1933         break;
1934     }
1935     return errmsg;
1936 }
1937
1938 /*
1939  * Return an error message for UNIX-style errno indications on write
1940  * operations.
1941  */
1942 const char *
1943 file_write_error_message(int err)
1944 {
1945     const char *errmsg;
1946     static char errmsg_errno[1024+1];
1947
1948     switch (err) {
1949
1950     case ENOSPC:
1951         errmsg = "The file \"%s\" could not be saved because there is no space left on the file system.";
1952         break;
1953
1954 #ifdef EDQUOT
1955     case EDQUOT:
1956         errmsg = "The file \"%s\" could not be saved because you are too close to, or over, your disk quota.";
1957         break;
1958 #endif
1959
1960     default:
1961         g_snprintf(errmsg_errno, sizeof(errmsg_errno),
1962                "An error occurred while writing to the file \"%%s\": %s.",
1963                g_strerror(err));
1964         errmsg = errmsg_errno;
1965         break;
1966     }
1967     return errmsg;
1968 }
1969
1970
1971 gboolean
1972 file_exists(const char *fname)
1973 {
1974     ws_statb64 file_stat;
1975
1976     if (!fname) {
1977         return FALSE;
1978     }
1979
1980 #ifdef _WIN32
1981     /*
1982      * This is a bit tricky on win32. The st_ino field is documented as:
1983      * "The inode, and therefore st_ino, has no meaning in the FAT, ..."
1984      * but it *is* set to zero if stat() returns without an error,
1985      * so this is working, but maybe not quite the way expected. ULFL
1986      */
1987     file_stat.st_ino = 1;   /* this will make things work if an error occurred */
1988     ws_stat64(fname, &file_stat);
1989     if (file_stat.st_ino == 0) {
1990         return TRUE;
1991     } else {
1992         return FALSE;
1993     }
1994 #else
1995     if (ws_stat64(fname, &file_stat) != 0 && errno == ENOENT) {
1996         return FALSE;
1997     } else {
1998         return TRUE;
1999     }
2000 #endif
2001 }
2002
2003 /*
2004  * Check that the from file is not the same as to file
2005  * We do it here so we catch all cases ...
2006  * Unfortunately, the file requester gives us an absolute file
2007  * name and the read file name may be relative (if supplied on
2008  * the command line), so we can't just compare paths. From Joerg Mayer.
2009  */
2010 gboolean
2011 files_identical(const char *fname1, const char *fname2)
2012 {
2013     /* Two different implementations, because:
2014      *
2015      * - _fullpath is not available on UN*X, so we can't get full
2016      *   paths and compare them (which wouldn't work with hard links
2017      *   in any case);
2018      *
2019      * - st_ino isn't filled in with a meaningful value on Windows.
2020      */
2021 #ifdef _WIN32
2022     char full1[MAX_PATH], full2[MAX_PATH];
2023
2024     /*
2025      * Get the absolute full paths of the file and compare them.
2026      * That won't work if you have hard links, but those aren't
2027      * much used on Windows, even though NTFS supports them.
2028      *
2029      * XXX - will _fullpath work with UNC?
2030      */
2031     if( _fullpath( full1, fname1, MAX_PATH ) == NULL ) {
2032         return FALSE;
2033     }
2034
2035     if( _fullpath( full2, fname2, MAX_PATH ) == NULL ) {
2036         return FALSE;
2037     }
2038
2039     if(strcmp(full1, full2) == 0) {
2040         return TRUE;
2041     } else {
2042         return FALSE;
2043     }
2044 #else
2045     ws_statb64 filestat1, filestat2;
2046
2047     /*
2048      * Compare st_dev and st_ino.
2049      */
2050     if (ws_stat64(fname1, &filestat1) == -1)
2051         return FALSE;   /* can't get info about the first file */
2052     if (ws_stat64(fname2, &filestat2) == -1)
2053         return FALSE;   /* can't get info about the second file */
2054     return (filestat1.st_dev == filestat2.st_dev &&
2055         filestat1.st_ino == filestat2.st_ino);
2056 #endif
2057 }
2058
2059 /*
2060  * Copy a file in binary mode, for those operating systems that care about
2061  * such things.  This should be OK for all files, even text files, as
2062  * we'll copy the raw bytes, and we don't look at the bytes as we copy
2063  * them.
2064  *
2065  * Returns TRUE on success, FALSE on failure. If a failure, it also
2066  * displays a simple dialog window with the error message.
2067  */
2068 gboolean
2069 copy_file_binary_mode(const char *from_filename, const char *to_filename)
2070 {
2071     int           from_fd, to_fd, err;
2072     ssize_t       nread, nwritten;
2073     guint8        *pd = NULL;
2074
2075     /* Copy the raw bytes of the file. */
2076     from_fd = ws_open(from_filename, O_RDONLY | O_BINARY, 0000 /* no creation so don't matter */);
2077     if (from_fd < 0) {
2078         report_open_failure(from_filename, errno, FALSE);
2079         goto done;
2080     }
2081
2082     /* Use open() instead of creat() so that we can pass the O_BINARY
2083        flag, which is relevant on Win32; it appears that "creat()"
2084        may open the file in text mode, not binary mode, but we want
2085        to copy the raw bytes of the file, so we need the output file
2086        to be open in binary mode. */
2087     to_fd = ws_open(to_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
2088     if (to_fd < 0) {
2089         report_open_failure(to_filename, errno, TRUE);
2090         ws_close(from_fd);
2091         goto done;
2092     }
2093
2094 #define FS_READ_SIZE 65536
2095     pd = (guint8 *)g_malloc(FS_READ_SIZE);
2096     while ((nread = ws_read(from_fd, pd, FS_READ_SIZE)) > 0) {
2097         nwritten = ws_write(to_fd, pd, nread);
2098         if (nwritten < nread) {
2099             if (nwritten < 0)
2100                 err = errno;
2101             else
2102                 err = WTAP_ERR_SHORT_WRITE;
2103             report_write_failure(to_filename, err);
2104             ws_close(from_fd);
2105             ws_close(to_fd);
2106             goto done;
2107         }
2108     }
2109     if (nread < 0) {
2110         err = errno;
2111         report_read_failure(from_filename, err);
2112         ws_close(from_fd);
2113         ws_close(to_fd);
2114         goto done;
2115     }
2116     ws_close(from_fd);
2117     if (ws_close(to_fd) < 0) {
2118         report_write_failure(to_filename, errno);
2119         goto done;
2120     }
2121
2122     g_free(pd);
2123     pd = NULL;
2124     return TRUE;
2125
2126 done:
2127     g_free(pd);
2128     return FALSE;
2129 }
2130
2131 /*
2132  * Editor modelines
2133  *
2134  * Local Variables:
2135  * c-basic-offset: 4
2136  * tab-width: 8
2137  * indent-tabs-mode: nil
2138  * End:
2139  *
2140  * ex: set shiftwidth=4 tabstop=8 expandtab:
2141  * :indentSize=4:tabSize=8:noTabs=true:
2142  */