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