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