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