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