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