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