Ups, fix a typo from last checkin.
[obnox/wireshark/wip.git] / epan / filesystem.c
1 /* filesystem.c
2  * Filesystem utility routines
3  *
4  * $Id$
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #ifdef HAVE_DIRENT_H
30 #include <dirent.h>
31 #endif
32
33 #include <stdio.h>
34 #include <ctype.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <errno.h>
38
39 #include <glib.h>
40
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44
45 #ifdef HAVE_SYS_STAT_H
46 #include <sys/stat.h>
47 #endif
48
49 #ifdef _WIN32
50 #include <windows.h>
51 #include <tchar.h>
52 #include <shlobj.h>
53 #include "epan/unicode-utils.h"
54 #else
55 #include <pwd.h>
56 #endif
57
58 #include "filesystem.h"
59 #include "privileges.h"
60 #include <wiretap/file_util.h>
61
62 #define PROFILES_DIR    "profiles"
63 #define U3_MY_CAPTURES  "\\My Captures"
64
65 char *persconffile_dir = NULL;
66 char *persdatafile_dir = NULL;
67 char *persconfprofile = NULL;
68
69 /*
70  * Given a pathname, return a pointer to the last pathname separator
71  * character in the pathname, or NULL if the pathname contains no
72  * separators.
73  */
74 static char *
75 find_last_pathname_separator(const char *path)
76 {
77         char *separator;
78
79 #ifdef _WIN32
80         char c;
81
82         /*
83          * We have to scan for '\' or '/'.
84          * Get to the end of the string.
85          */
86         separator = strchr(path, '\0');         /* points to ending '\0' */
87         while (separator > path) {
88                 c = *--separator;
89                 if (c == '\\' || c == '/')
90                         return separator;       /* found it */
91         }
92
93         /*
94          * OK, we didn't find any, so no directories - but there might
95          * be a drive letter....
96          */
97         return strchr(path, ':');
98 #else
99         separator = strrchr(path, '/');
100 #endif
101         return separator;
102 }
103
104 /*
105  * Given a pathname, return the last component.
106  */
107 const char *
108 get_basename(const char *path)
109 {
110         const char *filename;
111
112         g_assert(path != NULL);
113         filename = find_last_pathname_separator(path);
114         if (filename == NULL) {
115                 /*
116                  * There're no directories, drive letters, etc. in the
117                  * name; the pathname *is* the file name.
118                  */
119                 filename = path;
120         } else {
121                 /*
122                  * Skip past the pathname or drive letter separator.
123                  */
124                 filename++;
125         }
126         return filename;
127 }
128
129 /*
130  * Given a pathname, return a string containing everything but the
131  * last component.  NOTE: this overwrites the pathname handed into
132  * it....
133  */
134 char *
135 get_dirname(char *path)
136 {
137         char *separator;
138
139         g_assert(path != NULL);
140         separator = find_last_pathname_separator(path);
141         if (separator == NULL) {
142                 /*
143                  * There're no directories, drive letters, etc. in the
144                  * name; there is no directory path to return.
145                  */
146                 return NULL;
147         }
148
149         /*
150          * Get rid of the last pathname separator and the final file
151          * name following it.
152          */
153         *separator = '\0';
154
155         /*
156          * "path" now contains the pathname of the directory containing
157          * the file/directory to which it referred.
158          */
159         return path;
160 }
161
162 /*
163  * Given a pathname, return:
164  *
165  *      the errno, if an attempt to "stat()" the file fails;
166  *
167  *      EISDIR, if the attempt succeeded and the file turned out
168  *      to be a directory;
169  *
170  *      0, if the attempt succeeded and the file turned out not
171  *      to be a directory.
172  */
173
174 /*
175  * Visual C++ on Win32 systems doesn't define these.  (Old UNIX systems don't
176  * define them either.)
177  *
178  * Visual C++ on Win32 systems doesn't define S_IFIFO, it defines _S_IFIFO.
179  */
180 #ifndef S_ISREG
181 #define S_ISREG(mode)   (((mode) & S_IFMT) == S_IFREG)
182 #endif
183 #ifndef S_IFIFO
184 #define S_IFIFO _S_IFIFO
185 #endif
186 #ifndef S_ISFIFO
187 #define S_ISFIFO(mode)  (((mode) & S_IFMT) == S_IFIFO)
188 #endif
189 #ifndef S_ISDIR
190 #define S_ISDIR(mode)   (((mode) & S_IFMT) == S_IFDIR)
191 #endif
192
193 int
194 test_for_directory(const char *path)
195 {
196         struct stat statb;
197
198         if (eth_stat(path, &statb) < 0)
199                 return errno;
200
201         if (S_ISDIR(statb.st_mode))
202                 return EISDIR;
203         else
204                 return 0;
205 }
206
207 int
208 test_for_fifo(const char *path)
209 {
210         struct stat statb;
211
212         if (eth_stat(path, &statb) < 0)
213                 return errno;
214
215         if (S_ISFIFO(statb.st_mode))
216                 return ESPIPE;
217         else
218                 return 0;
219 }
220
221 /*
222  * Directory from which the executable came.
223  */
224 static char *progfile_dir;
225
226 /*
227  * TRUE if we're running from the build directory.
228  */
229 static gboolean running_in_build_directory_flag = FALSE;
230
231 /*
232  * Get the pathname of the directory from which the executable came,
233  * and save it for future use.  Returns NULL on success, and a
234  * g_mallocated string containing an error on failure.
235  */
236 char *
237 init_progfile_dir(const char *arg0
238 #ifdef _WIN32
239         _U_
240 #endif
241 )
242 {
243         char *dir_end;
244         char *path;
245 #ifdef _WIN32
246         TCHAR prog_pathname_w[_MAX_PATH+2];
247         size_t progfile_dir_len;
248         char *prog_pathname;
249         DWORD error;
250         TCHAR *msg_w;
251         guchar *msg;
252         size_t msglen;
253
254         /*
255          * Attempt to get the full pathname of the currently running
256          * program.
257          */
258         if (GetModuleFileName(NULL, prog_pathname_w, sizeof prog_pathname_w) != 0) {
259                 /*
260                  * XXX - Should we use g_utf16_to_utf8(), as in
261                  * getenv_utf8()?
262                  */
263                 prog_pathname = utf_16to8(prog_pathname_w);
264                 /*
265                  * We got it; strip off the last component, which would be
266                  * the file name of the executable, giving us the pathname
267                  * of the directory where the executable resies
268                  *
269                  * First, find the last "\" in the directory, as that
270                  * marks the end of the directory pathname.
271                  *
272                  * XXX - Can the pathname be something such as
273                  * "C:wireshark.exe"?  Or is it always a full pathname
274                  * beginning with "\" after the drive letter?
275                  */
276                 dir_end = strrchr(prog_pathname, '\\');
277                 if (dir_end != NULL) {
278                         /*
279                          * Found it - now figure out how long the program
280                          * directory pathname will be.
281                          */
282                         progfile_dir_len = (dir_end - prog_pathname);
283
284                         /*
285                          * Allocate a buffer for the program directory
286                          * pathname, and construct it.
287                          */
288                         path = g_malloc(progfile_dir_len + 1);
289                         strncpy(path, prog_pathname, progfile_dir_len);
290                         path[progfile_dir_len] = '\0';
291                         progfile_dir = path;
292
293                         return NULL;    /* we succeeded */
294                 } else {
295                         /*
296                          * OK, no \ - what do we do now?
297                          */
298                         return g_strdup_printf("No \\ in executable pathname \"%s\"",
299                             prog_pathname);
300                 }
301         } else {
302                 /*
303                  * Oh, well.  Return an indication of the error.
304                  */
305                 error = GetLastError();
306                 if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
307                     NULL, error, 0, (LPTSTR) &msg_w, 0, NULL) == 0) {
308                         /*
309                          * Gak.  We can't format the message.
310                          */
311                         return g_strdup_printf("GetModuleFileName failed: %u (FormatMessage failed: %u)",
312                             error, GetLastError());
313                 }
314                 msg = utf_16to8(msg_w);
315                 LocalFree(msg_w);
316                 /*
317                  * "FormatMessage()" "helpfully" sticks CR/LF at the
318                  * end of the message.  Get rid of it.
319                  */
320                 msglen = strlen(msg);
321                 if (msglen >= 2) {
322                         msg[msglen - 1] = '\0';
323                         msg[msglen - 2] = '\0';
324                 }
325                 return g_strdup_printf("GetModuleFileName failed: %s (%u)",
326                     msg, error);
327         }
328 #else
329         char *prog_pathname;
330         char *curdir;
331         long path_max;
332         char *pathstr;
333         char *path_start, *path_end;
334         size_t path_component_len;
335         char *retstr;
336
337         /*
338          * Check whether WIRESHARK_RUN_FROM_BUILD_DIRECTORY is set in the
339          * environment; if so, set running_in_build_directory_flag if we
340          * weren't started with special privileges.  (If we were started
341          * with special privileges, it's not safe to allow the user to point
342          * us to some other directory; running_in_build_directory_flag, when
343          * set, causes us to look for plugins and the like in the build
344          * directory.)
345          */
346         if (getenv("WIRESHARK_RUN_FROM_BUILD_DIRECTORY") != NULL
347             && !started_with_special_privs())
348                 running_in_build_directory_flag = TRUE;
349
350         /*
351          * Try to figure out the directory in which the currently running
352          * program resides, given the argv[0] it was started with.  That
353          * might be the absolute path of the program, or a path relative
354          * to the current directory of the process that started it, or
355          * just a name for the program if it was started from the command
356          * line and was searched for in $PATH.  It's not guaranteed to be
357          * any of those, however, so there are no guarantees....
358          */
359         if (arg0[0] == '/') {
360                 /*
361                  * It's an absolute path.
362                  */
363                 prog_pathname = g_strdup(arg0);
364         } else if (strchr(arg0, '/') != NULL) {
365                 /*
366                  * It's a relative path, with a directory in it.
367                  * Get the current directory, and combine it
368                  * with that directory.
369                  */
370                 path_max = pathconf(".", _PC_PATH_MAX);
371                 if (path_max == -1) {
372                         /*
373                          * We have no idea how big a buffer to
374                          * allocate for the current directory.
375                          */
376                         return g_strdup_printf("pathconf failed: %s\n",
377                             strerror(errno));
378                 }
379                 curdir = g_malloc(path_max);
380                 if (getcwd(curdir, path_max) == NULL) {
381                         /*
382                          * It failed - give up, and just stick
383                          * with DATAFILE_DIR.
384                          */
385                         g_free(curdir);
386                         return g_strdup_printf("getcwd failed: %s\n",
387                             strerror(errno));
388                 }
389                 path = g_strdup_printf("%s/%s", curdir, arg0);
390                 g_free(curdir);
391                 prog_pathname = path;
392         } else {
393                 /*
394                  * It's just a file name.
395                  * Search the path for a file with that name
396                  * that's executable.
397                  */
398                 prog_pathname = NULL;   /* haven't found it yet */
399                 pathstr = getenv("PATH");
400                 path_start = pathstr;
401                 if (path_start != NULL) {
402                         while (*path_start != '\0') {
403                                 path_end = strchr(path_start, ':');
404                                 if (path_end == NULL)
405                                         path_end = path_start + strlen(path_start);
406                                 path_component_len = path_end - path_start;
407                                 path = g_malloc(path_component_len + 1
408                                     + strlen(arg0) + 1);
409                                 memcpy(path, path_start, path_component_len);
410                                 path[path_component_len] = '\0';
411                                 strncat(path, "/", 2);
412                                 strncat(path, arg0, strlen(arg0) + 1);
413                                 if (access(path, X_OK) == 0) {
414                                         /*
415                                          * Found it!
416                                          */
417                                         prog_pathname = path;
418                                         break;
419                                 }
420
421                                 /*
422                                  * That's not it.  If there are more
423                                  * path components to test, try them.
424                                  */
425                                 if (*path_end == '\0') {
426                                         /*
427                                          * There's nothing more to try.
428                                          */
429                                         break;
430                                 }
431                                 if (*path_end == ':')
432                                         path_end++;
433                                 path_start = path_end;
434                                 g_free(path);
435                         }
436                         if (prog_pathname == NULL) {
437                                 /*
438                                  * Program not found in path.
439                                  */
440                                 return g_strdup_printf("\"%s\" not found in \"%s\"",
441                                     arg0, pathstr);
442                         }
443                 } else {
444                         /*
445                          * PATH isn't set.
446                          * XXX - should we pick a default?
447                          */
448                         return g_strdup("PATH isn't set");
449                 }
450         }
451
452         /*
453          * OK, we have what we think is the pathname
454          * of the program.
455          *
456          * First, find the last "/" in the directory,
457          * as that marks the end of the directory pathname.
458          */
459         dir_end = strrchr(prog_pathname, '/');
460         if (dir_end != NULL) {
461                 /*
462                  * Found it.  Strip off the last component,
463                  * as that's the path of the program.
464                  */
465                 *dir_end = '\0';
466
467                 /*
468                  * Is there a "/.libs" at the end?
469                  */
470                 dir_end = strrchr(prog_pathname, '/');
471                 if (dir_end != NULL) {
472                         if (strcmp(dir_end, "/.libs") == 0) {
473                                 /*
474                                  * Yup, it's ".libs".
475                                  * Strip that off; it's an
476                                  * artifact of libtool.
477                                  */
478                                 *dir_end = '\0';
479
480                                 /*
481                                  * This presumably means we're run from
482                                  * the libtool wrapper, which probably
483                                  * means we're being run from the build
484                                  * directory.  If we weren't started
485                                  * with special privileges, set
486                                  * running_in_build_directory_flag.
487                                  *
488                                  * XXX - should we check whether what
489                                  * follows ".libs/" begins with "lt-"?
490                                  */
491                                 if (!started_with_special_privs())
492                                         running_in_build_directory_flag = TRUE;
493                         }
494                 }
495
496                 /*
497                  * OK, we have the path we want.
498                  */
499                 progfile_dir = prog_pathname;
500                 return NULL;
501         } else {
502                 /*
503                  * This "shouldn't happen"; we apparently
504                  * have no "/" in the pathname.
505                  * Just free up prog_pathname.
506                  */
507                 retstr = g_strdup_printf("No / found in \"%s\"", prog_pathname);
508                 g_free(prog_pathname);
509                 return retstr;
510         }
511 #endif
512 }
513
514 /*
515  * Get the directory in which the program resides.
516  */
517 const char *
518 get_progfile_dir(void)
519 {
520         return progfile_dir;
521 }
522
523 /*
524  * Get the directory in which the global configuration and data files are
525  * stored.
526  *
527  * On Windows, we use the directory in which the executable for this
528  * process resides.
529  *
530  * On UN*X, we use the DATAFILE_DIR value supplied by the configure
531  * script, unless we think we're being run from the build directory,
532  * in which case we use the directory in which the executable for this
533  * process resides.
534  *
535  * XXX - if we ever make libwireshark a real library, used by multiple
536  * applications (more than just TShark and versions of Wireshark with
537  * various UIs), should the configuration files belong to the library
538  * (and be shared by all those applications) or to the applications?
539  *
540  * If they belong to the library, that could be done on UNIX by the
541  * configure script, but it's trickier on Windows, as you can't just
542  * use the pathname of the executable.
543  *
544  * If they belong to the application, that could be done on Windows
545  * by using the pathname of the executable, but we'd have to have it
546  * passed in as an argument, in some call, on UNIX.
547  *
548  * Note that some of those configuration files might be used by code in
549  * libwireshark, some of them might be used by dissectors (would they
550  * belong to libwireshark, the application, or a separate library?),
551  * and some of them might be used by other code (the Wireshark preferences
552  * file includes resolver preferences that control the behavior of code
553  * in libwireshark, dissector preferences, and UI preferences, for
554  * example).
555  */
556 const char *
557 get_datafile_dir(void)
558 {
559 #ifdef _WIN32
560         char *u3deviceexecpath;
561 #endif
562         static char *datafile_dir = NULL;
563
564         if (datafile_dir != NULL)
565                 return datafile_dir;
566
567 #ifdef _WIN32
568         /*
569          * See if we are running in a U3 environment.
570          */
571         u3deviceexecpath = getenv_utf8("U3_DEVICE_EXEC_PATH");
572
573         if (u3deviceexecpath != NULL) {
574                 /*
575                  * We are; use the U3 device executable path.
576                  */
577                 datafile_dir = u3deviceexecpath;
578         } else {
579                 /*
580                  * Do we have the pathname of the program?  If so, assume we're
581                  * running an installed version of the program.  If we fail,
582                  * we don't change "datafile_dir", and thus end up using the
583                  * default.
584                  *
585                  * XXX - does NSIS put the installation directory into
586                  * "\HKEY_LOCAL_MACHINE\SOFTWARE\Wireshark\InstallDir"?
587                  * If so, perhaps we should read that from the registry,
588                  * instead.
589                  */
590                 if (progfile_dir != NULL) {
591                         /*
592                          * Yes, we do; use that.
593                          */
594                         datafile_dir = progfile_dir;
595                 } else {
596                         /*
597                          * No, we don't.
598                          * Fall back on the default installation directory.
599                          */
600                         datafile_dir = "C:\\Program Files\\Wireshark\\";
601                 }
602         }
603 #else
604         if (running_in_build_directory_flag && progfile_dir != NULL) {
605                 /*
606                  * We're (probably) being run from the build directory and
607                  * weren't started with special privileges, and we were
608                  * able to determine the directory in which the program
609                  * was found, so use that.
610                  */
611                 datafile_dir = progfile_dir;
612         } else {
613                 /*
614                  * Return the directory specified when the build
615                  * was configured.
616                  */
617                 datafile_dir = DATAFILE_DIR;
618         }
619
620 #endif
621         return datafile_dir;
622 }
623
624 #ifdef HAVE_PLUGINS
625 /*
626  * Find the directory where the plugins are stored.
627  *
628  * On Windows, we use the "plugin" subdirectory of the datafile directory.
629  *
630  * On UN*X, we use the PLUGIN_DIR value supplied by the configure
631  * script, unless we think we're being run from the build directory,
632  * in which case we use the "plugin" subdirectory of the datafile directory.
633  *
634  * In both cases, we then use the subdirectory of that directory whose
635  * name is the version number.
636  *
637  * XXX - if we think we're being run from the build directory, perhaps we
638  * should have the plugin code not look in the version subdirectory
639  * of the plugin directory, but look in all of the subdirectories
640  * of the plugin directory, so it can just fetch the plugins built
641  * as part of the build process.
642  */
643 static const char *plugin_dir = NULL;
644
645 static void
646 init_plugin_dir(void)
647 {
648 #ifdef _WIN32
649         /*
650          * On Windows, the data file directory is the installation
651          * directory; the plugins are stored under it.
652          *
653          * Assume we're running the installed version of Wireshark;
654          * on Windows, the data file directory is the directory
655          * in which the Wireshark binary resides.
656          */
657         plugin_dir = g_strdup_printf("%s\\plugins\\%s", get_datafile_dir(),
658             VERSION);
659
660         /*
661          * Make sure that pathname refers to a directory.
662          */
663         if (test_for_directory(plugin_dir) != EISDIR) {
664                 /*
665                  * Either it doesn't refer to a directory or it
666                  * refers to something that doesn't exist.
667                  *
668                  * Assume that means we're running a version of
669                  * Wireshark we've built in a build directory,
670                  * in which case {datafile dir}\plugins is the
671                  * top-level plugins source directory, and use
672                  * that directory and set the "we're running in
673                  * a build directory" flag, so the plugin
674                  * scanner will check all subdirectories of that
675                  * directory for plugins.
676                  */
677                 g_free( (gpointer) plugin_dir);
678                 plugin_dir = g_strdup_printf("%s\\plugins", get_datafile_dir());
679                 running_in_build_directory_flag = TRUE;
680         }
681 #else
682         if (running_in_build_directory_flag) {
683                 /*
684                  * We're (probably) being run from the build directory and
685                  * weren't started with special privileges, so we'll use
686                  * the "plugins" subdirectory of the datafile directory
687                  * (the datafile directory is the build directory).
688                  */
689                 plugin_dir = g_strdup_printf("%s/plugins", get_datafile_dir());
690         } else
691                 plugin_dir = PLUGIN_DIR;
692 #endif
693 }
694 #endif /* HAVE_PLUGINS */
695
696 /*
697  * Get the directory in which the plugins are stored.
698  */
699 const char *
700 get_plugin_dir(void)
701 {
702 #ifdef HAVE_PLUGINS
703         if (!plugin_dir) init_plugin_dir();
704         return plugin_dir;
705 #else
706         return NULL;
707 #endif
708 }
709
710 /*
711  * Get the flag indicating whether we're running from a build
712  * directory.
713  */
714 gboolean
715 running_in_build_directory(void)
716 {
717         return running_in_build_directory_flag;
718 }
719
720 /*
721  * Get the directory in which files that, at least on UNIX, are
722  * system files (such as "/etc/ethers") are stored; on Windows,
723  * there's no "/etc" directory, so we get them from the global
724  * configuration and data file directory.
725  */
726 const char *
727 get_systemfile_dir(void)
728 {
729 #ifdef _WIN32
730         return get_datafile_dir();
731 #else
732         return "/etc";
733 #endif
734 }
735
736 /*
737  * Name of directory, under the user's home directory, in which
738  * personal configuration files are stored.
739  */
740 #ifdef _WIN32
741 #define PF_DIR "Wireshark"
742 #else
743 /*
744  * XXX - should this be ".libepan"? For backwards-compatibility, I'll keep
745  * it ".wireshark" for now.
746  */
747 #define PF_DIR ".wireshark"
748 #endif
749
750 #ifdef _WIN32
751 /* utf8 version of getenv, needed to get win32 filename paths */
752 char *getenv_utf8(const char *varname)
753 {
754         char *envvar;
755         wchar_t *envvarw;
756         wchar_t *varnamew;
757
758         envvar = getenv(varname);
759
760         /* since GLib 2.6 we need an utf8 version of the filename */
761 #if (GLIB_MAJOR_VERSION > 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION >= 6))
762         /* using the wide char version of getenv should work under all circumstances */
763
764         /* convert given varname to utf16, needed by _wgetenv */
765         varnamew = g_utf8_to_utf16(varname, -1, NULL, NULL, NULL);
766         if (varnamew == NULL) {
767                 return envvar;
768         }
769
770         /* use wide char version of getenv */
771         envvarw = _wgetenv(varnamew);
772         g_free(varnamew);
773         if (envvarw == NULL) {
774                 return envvar;
775         }
776
777         /* convert value to utf8 */
778         envvar = g_utf16_to_utf8(envvarw, -1, NULL, NULL, NULL);
779         /* XXX - memleak */
780 #endif
781
782         return envvar;
783 }
784 #endif
785
786 void
787 set_profile_name(const gchar *profilename)
788 {
789         if (persconfprofile) {
790                 g_free (persconfprofile);
791         }
792
793         if (profilename && strlen(profilename) > 0 && 
794             strcmp(profilename, DEFAULT_PROFILE) != 0) {
795                 persconfprofile = g_strdup (profilename);
796         } else {
797                 /* Default Profile */
798                 persconfprofile = NULL;
799         }
800 }
801
802 const char *
803 get_profile_name(void)
804 {
805         if (persconfprofile) {
806                 return persconfprofile;
807         } else {
808                 return DEFAULT_PROFILE;
809         }
810 }
811
812 /*
813  * Get the directory in which personal configuration files reside;
814  * in UNIX-compatible systems, it's ".wireshark", under the user's home
815  * directory, and on Windows systems, it's "Wireshark", under %APPDATA%
816  * or, if %APPDATA% isn't set, it's "%USERPROFILE%\Application Data"
817  * (which is what %APPDATA% normally is on Windows 2000).
818  */
819 static const char *
820 get_persconffile_dir_no_profile(void)
821 {
822 #ifdef _WIN32
823         char *appdatadir;
824         char *userprofiledir;
825         char *u3appdatapath;
826 #else
827         const char *homedir;
828         struct passwd *pwd;
829 #endif
830
831         /* Return the cached value, if available */
832         if (persconffile_dir != NULL)
833                 return persconffile_dir;
834
835 #ifdef _WIN32
836         /*
837          * See if we are running in a U3 environment.
838          */
839         u3appdatapath = getenv_utf8("U3_APP_DATA_PATH");
840         if (u3appdatapath != NULL) {
841                 /*
842                  * We are; use the U3 application data path.
843                  */
844                 persconffile_dir = u3appdatapath;
845         } else {
846                 /*
847                  * Use %APPDATA% or %USERPROFILE%, so that configuration
848                  * files are stored in the user profile, rather than in
849                  * the home directory.  The Windows convention is to store
850                  * configuration information in the user profile, and doing
851                  * so means you can use Wireshark even if the home directory
852                  * is an inaccessible network drive.
853                  */
854                 appdatadir = getenv_utf8("APPDATA");
855                 if (appdatadir != NULL) {
856                         /*
857                          * Concatenate %APPDATA% with "\Wireshark".
858                          */
859                         persconffile_dir = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
860                                                            appdatadir, PF_DIR);
861                 } else {
862                         /*
863                          * OK, %APPDATA% wasn't set, so use
864                          * %USERPROFILE%\Application Data.
865                          */
866                         userprofiledir = getenv_utf8("USERPROFILE");
867                         if (userprofiledir != NULL) {
868                                 persconffile_dir = g_strdup_printf(
869                                     "%s" G_DIR_SEPARATOR_S "Application Data" G_DIR_SEPARATOR_S "%s",
870                                     userprofiledir, PF_DIR);
871                         } else {
872                                 /*
873                                  * Give up and use "C:".
874                                  */
875                                 persconffile_dir = g_strdup_printf("C:" G_DIR_SEPARATOR_S "%s", PF_DIR);
876                         }
877                 }
878         }
879 #else
880         /*
881          * If $HOME is set, use that.
882          */
883         homedir = getenv("HOME");
884         if (homedir == NULL) {
885                 /*
886                  * Get their home directory from the password file.
887                  * If we can't even find a password file entry for them,
888                  * use "/tmp".
889                  */
890                 pwd = getpwuid(getuid());
891                 if (pwd != NULL) {
892                         /*
893                          * This is cached, so we don't need to worry
894                          * about allocating multiple ones of them.
895                          */
896                         homedir = g_strdup(pwd->pw_dir);
897                 } else
898                         homedir = "/tmp";
899         }
900         persconffile_dir = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", homedir, PF_DIR);
901 #endif
902
903         return persconffile_dir;
904 }
905
906 const char *
907 get_profiles_dir(void)
908 {
909         static char *profiles_dir = NULL;
910
911         if (profiles_dir) {
912                 g_free (profiles_dir);
913         }
914
915         profiles_dir = g_strdup_printf ("%s%s%s", get_persconffile_dir_no_profile (),
916                                         G_DIR_SEPARATOR_S, PROFILES_DIR);
917
918         return profiles_dir;
919 }
920
921 static const char *
922 get_persconffile_dir(const gchar *profilename)
923 {
924         static char *persconffile_profile_dir = NULL;
925
926         if (persconffile_profile_dir) {
927                 g_free (persconffile_profile_dir);
928         }
929
930         if (profilename && strlen(profilename) > 0 &&
931             strcmp(profilename, DEFAULT_PROFILE) != 0) {
932           persconffile_profile_dir = g_strdup_printf ("%s%s%s", get_profiles_dir (), 
933                                                       G_DIR_SEPARATOR_S, profilename);
934         } else {
935           persconffile_profile_dir = g_strdup_printf (get_persconffile_dir_no_profile ());
936         }
937
938         return persconffile_profile_dir;
939 }
940
941 gboolean
942 profile_exists(const gchar *profilename)
943 {
944         if (test_for_directory (get_persconffile_dir (profilename)) == EISDIR) {
945                 return TRUE;
946         }
947
948         return FALSE;
949 }
950
951 static int
952 delete_directory (const char *directory, char **pf_dir_path_return)
953 {
954         ETH_DIR *dir;
955         ETH_DIRENT *file;
956         gchar *filename;
957         int ret = 0;
958
959         if ((dir = eth_dir_open(directory, 0, NULL)) != NULL) {
960                 while ((file = eth_dir_read_name(dir)) != NULL) {
961                         filename = g_strdup_printf ("%s%s%s", directory, G_DIR_SEPARATOR_S, 
962                                                     eth_dir_get_name(file));
963                         if (test_for_directory(filename) != EISDIR) {
964                                 ret = eth_remove(filename);
965 #if 0
966                         } else {
967                                 /* The user has manually created a directory in the profile directory */
968                                 /* I do not want to delete the directory recursively yet */
969                                 ret = delete_directory (filename, pf_dir_path_return);
970 #endif
971                         }
972                         if (ret != 0) {
973                                 *pf_dir_path_return = filename;
974                                 break;
975                         }
976                         g_free (filename);
977                 }
978                 eth_dir_close(dir);
979         }
980
981         if (ret == 0 && (ret = eth_remove(directory)) != 0) {
982                 *pf_dir_path_return = g_strdup (directory);
983         }
984
985         return ret;
986 }
987
988 int
989 delete_persconffile_profile(const char *profilename, char **pf_dir_path_return)
990 {
991         const char *profile_dir = get_persconffile_dir(profilename);
992         int ret = 0;
993
994         if (test_for_directory (profile_dir) == EISDIR) {
995                 ret = delete_directory (profile_dir, pf_dir_path_return);
996         }
997
998         return ret;
999 }
1000
1001 int
1002 rename_persconffile_profile(const char *fromname, const char *toname,
1003                             char **pf_from_dir_path_return, char **pf_to_dir_path_return)
1004 {
1005   char *from_dir = g_strdup (get_persconffile_dir(fromname));
1006   char *to_dir = g_strdup (get_persconffile_dir(toname));
1007   int ret = 0;
1008
1009   ret = eth_rename (from_dir, to_dir);
1010   if (ret != 0) {
1011     *pf_from_dir_path_return = g_strdup (from_dir);
1012     *pf_to_dir_path_return = g_strdup (to_dir);
1013   }
1014
1015   g_free (from_dir);
1016   g_free (to_dir);
1017
1018   return ret;
1019 }
1020
1021 /*
1022  * Create the directory that holds personal configuration files, if
1023  * necessary.  If we attempted to create it, and failed, return -1 and
1024  * set "*pf_dir_path_return" to the pathname of the directory we failed
1025  * to create (it's g_mallocated, so our caller should free it); otherwise,
1026  * return 0.
1027  */
1028 int
1029 create_persconffile_profile(const char *profilename, char **pf_dir_path_return)
1030 {
1031         const char *pf_dir_path;
1032 #ifdef _WIN32
1033         char *pf_dir_path_copy, *pf_dir_parent_path;
1034         size_t pf_dir_parent_path_len;
1035 #endif
1036         struct stat s_buf;
1037         int ret;
1038
1039         if (profilename) {
1040                 /*
1041                  * Check if profiles directory exists.
1042                  * If not then create it.
1043                  */
1044                 pf_dir_path = get_profiles_dir ();
1045                 if (eth_stat(pf_dir_path, &s_buf) != 0 && errno == ENOENT) {
1046                         ret = eth_mkdir(pf_dir_path, 0755);
1047                         if (ret == -1) {
1048                                 *pf_dir_path_return = g_strdup(pf_dir_path);
1049                                 return ret;
1050                         }
1051                 }
1052         }
1053
1054         pf_dir_path = get_persconffile_dir(profilename);
1055         if (eth_stat(pf_dir_path, &s_buf) != 0 && errno == ENOENT) {
1056 #ifdef _WIN32
1057                 /*
1058                  * Does the parent directory of that directory
1059                  * exist?  %APPDATA% may not exist even though
1060                  * %USERPROFILE% does.
1061                  *
1062                  * We check for the existence of the directory
1063                  * by first checking whether the parent directory
1064                  * is just a drive letter and, if it's not, by
1065                  * doing a "stat()" on it.  If it's a drive letter,
1066                  * or if the "stat()" succeeds, we assume it exists.
1067                  */
1068                 pf_dir_path_copy = g_strdup(pf_dir_path);
1069                 pf_dir_parent_path = get_dirname(pf_dir_path_copy);
1070                 pf_dir_parent_path_len = strlen(pf_dir_parent_path);
1071                 if (pf_dir_parent_path_len > 0
1072                     && pf_dir_parent_path[pf_dir_parent_path_len - 1] != ':'
1073                     && eth_stat(pf_dir_parent_path, &s_buf) != 0) {
1074                         /*
1075                          * No, it doesn't exist - make it first.
1076                          */
1077                         ret = eth_mkdir(pf_dir_parent_path, 0755);
1078                         if (ret == -1) {
1079                                 *pf_dir_path_return = pf_dir_parent_path;
1080                                 return -1;
1081                         }
1082                 }
1083                 g_free(pf_dir_path_copy);
1084                 ret = eth_mkdir(pf_dir_path, 0755);
1085 #else
1086                 ret = eth_mkdir(pf_dir_path, 0755);
1087 #endif
1088         } else {
1089                 /*
1090                  * Something with that pathname exists; if it's not
1091                  * a directory, we'll get an error if we try to put
1092                  * something in it, so we don't fail here, we wait
1093                  * for that attempt fo fail.
1094                  */
1095                 ret = 0;
1096         }
1097         if (ret == -1)
1098                 *pf_dir_path_return = g_strdup(pf_dir_path);
1099         return ret;
1100 }
1101
1102 int
1103 create_persconffile_dir(char **pf_dir_path_return)
1104 {
1105   return create_persconffile_profile(persconfprofile, pf_dir_path_return);
1106 }
1107
1108 /*
1109  * Get the (default) directory in which personal data is stored.
1110  *
1111  * On Win32, this is the "My Documents" folder in the personal profile.
1112  * On UNIX this is simply the current directory.
1113  * On a U3 device this is "$U3_DEVICE_DOCUMENT_PATH\My Captures" folder.
1114  */
1115 /* XXX - should this and the get_home_dir() be merged? */
1116 extern char *
1117 get_persdatafile_dir(void)
1118 {
1119 #ifdef _WIN32
1120     char *u3devicedocumentpath;
1121     TCHAR tszPath[MAX_PATH];
1122         char *szPath;
1123         BOOL bRet;
1124
1125
1126         /* Return the cached value, if available */
1127         if (persdatafile_dir != NULL)
1128                 return persdatafile_dir;
1129
1130         /*
1131          * See if we are running in a U3 environment.
1132          */
1133         u3devicedocumentpath = getenv_utf8("U3_DEVICE_DOCUMENT_PATH");
1134
1135         if (u3devicedocumentpath != NULL) {
1136
1137           /* the "My Captures" sub-directory is created (if it doesn't exist)
1138              by u3util.exe when the U3 Wireshark is first run */
1139
1140           szPath = g_strdup_printf("%s%s", u3devicedocumentpath, U3_MY_CAPTURES);
1141
1142           persdatafile_dir = szPath;
1143           return szPath;
1144
1145         } else {
1146         /* Hint: SHGetFolderPath is not available on MSVC 6 - without Platform SDK */
1147         bRet = SHGetSpecialFolderPath(NULL, tszPath, CSIDL_PERSONAL, FALSE);
1148         if(bRet == TRUE) {
1149                 szPath = utf_16to8(tszPath);
1150                 persdatafile_dir = szPath;
1151                 return szPath;
1152         } else {
1153                 return "";
1154         }
1155  }
1156 #else
1157   return "";
1158 #endif
1159 }
1160
1161 #ifdef _WIN32
1162 /*
1163  * Returns the user's home directory on Win32.
1164  */
1165 static const char *
1166 get_home_dir(void)
1167 {
1168         static const char *home = NULL;
1169         char *homedrive, *homepath;
1170         char *homestring;
1171         char *lastsep;
1172
1173         /* Return the cached value, if available */
1174         if (home)
1175                 return home;
1176
1177         /*
1178          * XXX - should we use USERPROFILE anywhere in this process?
1179          * Is there a chance that it might be set but one or more of
1180          * HOMEDRIVE or HOMEPATH isn't set?
1181          */
1182         homedrive = getenv_utf8("HOMEDRIVE");
1183         if (homedrive != NULL) {
1184                 homepath = getenv_utf8("HOMEPATH");
1185                 if (homepath != NULL) {
1186                         /*
1187                          * This is cached, so we don't need to worry about
1188                          * allocating multiple ones of them.
1189                          */
1190                         homestring = g_strdup_printf("%s%s", homedrive, homepath);
1191
1192                         /*
1193                          * Trim off any trailing slash or backslash.
1194                          */
1195                         lastsep = find_last_pathname_separator(homestring);
1196                         if (lastsep != NULL && *(lastsep + 1) == '\0') {
1197                                 /*
1198                                  * Last separator is the last character
1199                                  * in the string.  Nuke it.
1200                                  */
1201                                 *lastsep = '\0';
1202                         }
1203                         home = homestring;
1204                 } else
1205                         home = homedrive;
1206         } else {
1207                 /*
1208                  * Give up and use C:.
1209                  */
1210                 home = "C:";
1211         }
1212
1213         return home;
1214 }
1215 #endif
1216
1217 /*
1218  * Construct the path name of a personal configuration file, given the
1219  * file name.
1220  *
1221  * On Win32, if "for_writing" is FALSE, we check whether the file exists
1222  * and, if not, construct a path name relative to the ".wireshark"
1223  * subdirectory of the user's home directory, and check whether that
1224  * exists; if it does, we return that, so that configuration files
1225  * from earlier versions can be read.
1226  */
1227 char *
1228 get_persconffile_path(const char *filename, gboolean from_profile, gboolean for_writing
1229 #ifndef _WIN32
1230         _U_
1231 #endif
1232 )
1233 {
1234         char *path;
1235 #ifdef _WIN32
1236         struct stat s_buf;
1237         char *old_path;
1238 #endif
1239
1240         if (from_profile) {
1241           path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1242                                  get_persconffile_dir(persconfprofile), filename);
1243         } else {
1244           path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1245                                  get_persconffile_dir(NULL), filename);
1246         }
1247 #ifdef _WIN32
1248         if (!for_writing) {
1249                 if (eth_stat(path, &s_buf) != 0 && errno == ENOENT) {
1250                         /*
1251                          * OK, it's not in the personal configuration file
1252                          * directory; is it in the ".wireshark" subdirectory
1253                          * of their home directory?
1254                          */
1255                         old_path = g_strdup_printf(
1256                             "%s" G_DIR_SEPARATOR_S ".wireshark" G_DIR_SEPARATOR_S "%s",
1257                             get_home_dir(), filename);
1258                         if (eth_stat(old_path, &s_buf) == 0) {
1259                                 /*
1260                                  * OK, it exists; return it instead.
1261                                  */
1262                                 g_free(path);
1263                                 path = old_path;
1264                         }
1265                 }
1266         }
1267 #endif
1268
1269         return path;
1270 }
1271
1272 /*
1273  * process command line option belonging to the filesystem settings
1274  * (move this e.g. to main.c and have set_persconffile_dir() instead in this file?)
1275  */
1276 int
1277 filesystem_opt(int opt _U_, const char *optarg)
1278 {
1279   gchar *p, *colonp;
1280
1281   colonp = strchr(optarg, ':');
1282   if (colonp == NULL) {
1283     return 1;
1284   }
1285
1286   p = colonp;
1287   *p++ = '\0';
1288
1289   /*
1290    * Skip over any white space (there probably won't be any, but
1291    * as we allow it in the preferences file, we might as well
1292    * allow it here).
1293    */
1294   while (isspace((guchar)*p))
1295     p++;
1296   if (*p == '\0') {
1297     /*
1298      * Put the colon back, so if our caller uses, in an
1299      * error message, the string they passed us, the message
1300      * looks correct.
1301      */
1302     *colonp = ':';
1303     return 1;
1304   }
1305
1306   /* directory should be existing */
1307   /* XXX - is this a requirement? */
1308   if(test_for_directory(p) != EISDIR) {
1309     /*
1310      * Put the colon back, so if our caller uses, in an
1311      * error message, the string they passed us, the message
1312      * looks correct.
1313      */
1314     *colonp = ':';
1315     return 1;
1316   }
1317
1318   if (strcmp(optarg,"persconf") == 0) {
1319     persconffile_dir = p;
1320   } else if (strcmp(optarg,"persdata") == 0) {
1321     persdatafile_dir = p;
1322   /* XXX - might need to add the temp file path */
1323   } else {
1324     return 1;
1325   }
1326   *colonp = ':'; /* put the colon back */
1327   return 0;
1328 }
1329
1330 /*
1331  * Construct the path name of a global configuration file, given the
1332  * file name.
1333  */
1334 char *
1335 get_datafile_path(const char *filename)
1336 {
1337
1338         return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", get_datafile_dir(),
1339             filename);
1340 }
1341
1342 /* Delete a file */
1343 gboolean
1344 deletefile(const char *path)
1345 {
1346         return eth_unlink(path) == 0;
1347 }
1348
1349 /*
1350  * Construct and return the path name of a file in the
1351  * appropriate temporary file directory.
1352  */
1353 char *get_tempfile_path(const char *filename)
1354 {
1355
1356         return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", g_get_tmp_dir(), filename);
1357 }
1358
1359 /*
1360  * Return an error message for UNIX-style errno indications on open or
1361  * create operations.
1362  */
1363 const char *
1364 file_open_error_message(int err, gboolean for_writing)
1365 {
1366         const char *errmsg;
1367         static char errmsg_errno[1024+1];
1368
1369         switch (err) {
1370
1371         case ENOENT:
1372                 if (for_writing)
1373                         errmsg = "The path to the file \"%s\" doesn't exist.";
1374                 else
1375                         errmsg = "The file \"%s\" doesn't exist.";
1376                 break;
1377
1378         case EACCES:
1379                 if (for_writing)
1380                         errmsg = "You don't have permission to create or write to the file \"%s\".";
1381                 else
1382                         errmsg = "You don't have permission to read the file \"%s\".";
1383                 break;
1384
1385         case EISDIR:
1386                 errmsg = "\"%s\" is a directory (folder), not a file.";
1387                 break;
1388
1389         case ENOSPC:
1390                 errmsg = "The file \"%s\" could not be created because there is no space left on the file system.";
1391                 break;
1392
1393 #ifdef EDQUOT
1394         case EDQUOT:
1395                 errmsg = "The file \"%s\" could not be created because you are too close to, or over, your disk quota.";
1396                 break;
1397 #endif
1398
1399         case EINVAL:
1400                 errmsg = "The file \"%s\" could not be created because an invalid filename was specified.";
1401                 break;
1402
1403         default:
1404                 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
1405                                 "The file \"%%s\" could not be %s: %s.",
1406                                 for_writing ? "created" : "opened",
1407                                 strerror(err));
1408                 errmsg = errmsg_errno;
1409                 break;
1410         }
1411         return errmsg;
1412 }
1413
1414 /*
1415  * Return an error message for UNIX-style errno indications on write
1416  * operations.
1417  */
1418 const char *
1419 file_write_error_message(int err)
1420 {
1421         const char *errmsg;
1422         static char errmsg_errno[1024+1];
1423
1424         switch (err) {
1425
1426         case ENOSPC:
1427                 errmsg = "The file \"%s\" could not be saved because there is no space left on the file system.";
1428                 break;
1429
1430 #ifdef EDQUOT
1431         case EDQUOT:
1432                 errmsg = "The file \"%s\" could not be saved because you are too close to, or over, your disk quota.";
1433                 break;
1434 #endif
1435
1436         default:
1437                 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
1438                     "An error occurred while writing to the file \"%%s\": %s.",
1439                     strerror(err));
1440                 errmsg = errmsg_errno;
1441                 break;
1442         }
1443         return errmsg;
1444 }
1445
1446
1447 gboolean
1448 file_exists(const char *fname)
1449 {
1450   struct stat   file_stat;
1451
1452
1453 #ifdef _WIN32
1454   /*
1455    * This is a bit tricky on win32. The st_ino field is documented as:
1456    * "The inode, and therefore st_ino, has no meaning in the FAT, ..."
1457    * but it *is* set to zero if stat() returns without an error,
1458    * so this is working, but maybe not quite the way expected. ULFL
1459    */
1460    file_stat.st_ino = 1;   /* this will make things work if an error occured */
1461    eth_stat(fname, &file_stat);
1462    if (file_stat.st_ino == 0) {
1463        return TRUE;
1464    } else {
1465        return FALSE;
1466    }
1467 #else
1468    if (eth_stat(fname, &file_stat) != 0 && errno == ENOENT) {
1469        return FALSE;
1470    } else {
1471        return TRUE;
1472    }
1473 #endif
1474
1475 }
1476
1477 /*
1478  * Check that the from file is not the same as to file
1479  * We do it here so we catch all cases ...
1480  * Unfortunately, the file requester gives us an absolute file
1481  * name and the read file name may be relative (if supplied on
1482  * the command line), so we can't just compare paths. From Joerg Mayer.
1483  */
1484 gboolean
1485 files_identical(const char *fname1, const char *fname2)
1486 {
1487     /* Two different implementations, because:
1488      *
1489      * - _fullpath is not available on UN*X, so we can't get full
1490      *   paths and compare them (which wouldn't work with hard links
1491      *   in any case);
1492      *
1493      * - st_ino isn't filled in with a meaningful value on Windows.
1494      */
1495 #ifdef _WIN32
1496     char full1[MAX_PATH], full2[MAX_PATH];
1497
1498     /*
1499      * Get the absolute full paths of the file and compare them.
1500      * That won't work if you have hard links, but those aren't
1501      * much used on Windows, even though NTFS supports them.
1502      *
1503      * XXX - will _fullpath work with UNC?
1504      */
1505     if( _fullpath( full1, fname1, MAX_PATH ) == NULL ) {
1506         return FALSE;
1507     }
1508
1509     if( _fullpath( full2, fname2, MAX_PATH ) == NULL ) {
1510         return FALSE;
1511     }
1512
1513     if(strcmp(full1, full2) == 0) {
1514         return TRUE;
1515     } else {
1516         return FALSE;
1517     }
1518 #else
1519   struct stat   filestat1, filestat2;
1520
1521    /*
1522     * Compare st_dev and st_ino.
1523     */
1524    if (eth_stat(fname1, &filestat1) == -1)
1525        return FALSE;    /* can't get info about the first file */
1526    if (eth_stat(fname2, &filestat2) == -1)
1527        return FALSE;    /* can't get info about the second file */
1528    return (filestat1.st_dev == filestat2.st_dev &&
1529            filestat1.st_ino == filestat2.st_ino);
1530 #endif
1531 }
1532