2 * Filesystem utility routines
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
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.
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.
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.
40 #ifdef HAVE_SYS_STAT_H
47 #include "epan/strutil.h"
52 #include "filesystem.h"
53 #include <wiretap/file_util.h>
56 * Given a pathname, return a pointer to the last pathname separator
57 * character in the pathname, or NULL if the pathname contains no
61 find_last_pathname_separator(const char *path)
69 * We have to scan for '\' or '/'.
70 * Get to the end of the string.
72 separator = strchr(path, '\0'); /* points to ending '\0' */
73 while (separator > path) {
75 if (c == '\\' || c == '/')
76 return separator; /* found it */
80 * OK, we didn't find any, so no directories - but there might
81 * be a drive letter....
83 return strchr(path, ':');
85 separator = strrchr(path, '/');
91 * Given a pathname, return the last component.
94 get_basename(const char *path)
98 g_assert(path != NULL);
99 filename = find_last_pathname_separator(path);
100 if (filename == NULL) {
102 * There're no directories, drive letters, etc. in the
103 * name; the pathname *is* the file name.
108 * Skip past the pathname or drive letter separator.
116 * Given a pathname, return a string containing everything but the
117 * last component. NOTE: this overwrites the pathname handed into
121 get_dirname(char *path)
125 g_assert(path != NULL);
126 separator = find_last_pathname_separator(path);
127 if (separator == NULL) {
129 * There're no directories, drive letters, etc. in the
130 * name; there is no directory path to return.
136 * Get rid of the last pathname separator and the final file
142 * "path" now contains the pathname of the directory containing
143 * the file/directory to which it referred.
149 * Given a pathname, return:
151 * the errno, if an attempt to "stat()" the file fails;
153 * EISDIR, if the attempt succeeded and the file turned out
156 * 0, if the attempt succeeded and the file turned out not
161 * Visual C++ on Win32 systems doesn't define these. (Old UNIX systems don't
162 * define them either.)
164 * Visual C++ on Win32 systems doesn't define S_IFIFO, it defines _S_IFIFO.
167 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
170 #define S_IFIFO _S_IFIFO
173 #define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)
176 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
180 test_for_directory(const char *path)
184 if (eth_stat(path, &statb) < 0)
187 if (S_ISDIR(statb.st_mode))
194 test_for_fifo(const char *path)
198 if (eth_stat(path, &statb) < 0)
201 if (S_ISFIFO(statb.st_mode))
207 static char *progfile_dir;
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.
215 init_progfile_dir(const char *arg0
224 TCHAR prog_pathname_w[_MAX_PATH+2];
225 size_t progfile_dir_len;
233 * Attempt to get the full pathname of the currently running
236 if (GetModuleFileName(NULL, prog_pathname_w, sizeof prog_pathname_w) != 0) {
238 * XXX - Should we use g_utf16_to_utf8(), as in
241 prog_pathname = utf_16to8(prog_pathname_w);
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
247 * First, find the last "\" in the directory, as that
248 * marks the end of the directory pathname.
250 * XXX - Can the pathname be something such as
251 * "C:ethereal.exe"? Or is it always a full pathname
252 * beginning with "\" after the drive letter?
254 dir_end = strrchr(prog_pathname, '\\');
255 if (dir_end != NULL) {
257 * Found it - now figure out how long the program
258 * directory pathname will be.
260 progfile_dir_len = (dir_end - prog_pathname);
263 * Allocate a buffer for the program directory
264 * pathname, and construct it.
266 path = g_malloc(progfile_dir_len + 1);
267 strncpy(path, prog_pathname, progfile_dir_len);
268 path[progfile_dir_len] = '\0';
271 return NULL; /* we succeeded */
274 * OK, no \ - what do we do now?
276 return g_strdup_printf("No \\ in executable pathname \"%s\"",
281 * Oh, well. Return an indication of the error.
283 error = GetLastError();
284 if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
285 NULL, error, 0, (LPTSTR) &msg_w, 0, NULL) == 0) {
287 * Gak. We can't format the message.
289 return g_strdup_printf("GetModuleFileName failed: %u (FormatMessage failed: %u)",
290 error, GetLastError());
292 msg = utf_16to8(msg_w);
295 * "FormatMessage()" "helpfully" sticks CR/LF at the
296 * end of the message. Get rid of it.
298 msglen = strlen(msg);
300 msg[msglen - 1] = '\0';
301 msg[msglen - 2] = '\0';
303 return g_strdup_printf("GetModuleFileName failed: %s (%u)",
311 char *path_start, *path_end;
312 size_t path_component_len;
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....
324 if (arg0[0] == '/') {
326 * It's an absolute path.
328 prog_pathname = g_strdup(arg0);
329 } else if (strchr(arg0, '/') != NULL) {
331 * It's a relative path, with a directory in it.
332 * Get the current directory, and combine it
333 * with that directory.
335 path_max = pathconf(".", _PC_PATH_MAX);
336 if (path_max == -1) {
338 * We have no idea how big a buffer to
339 * allocate for the current directory.
341 return g_strdup_printf("pathconf failed: %s\n",
344 curdir = g_malloc(path_max);
345 if (getcwd(curdir, path_max) == NULL) {
347 * It failed - give up, and just stick
351 return g_strdup_printf("getcwd failed: %s\n",
354 path = g_malloc(strlen(curdir) + 1 + strlen(arg0) + 1);
355 strcpy(path, curdir);
359 prog_pathname = path;
362 * It's just a file name.
363 * Search the path for a file with that name
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
377 memcpy(path, path_start, path_component_len);
378 path[path_component_len] = '\0';
381 if (access(path, X_OK) == 0) {
385 prog_pathname = path;
390 * That's not it. If there are more
391 * path components to test, try them.
393 if (*path_end == '\0') {
395 * There's nothing more to try.
399 if (*path_end == ':')
401 path_start = path_end;
404 if (prog_pathname == NULL) {
406 * Program not found in path.
408 return g_strdup_printf("\"%s\" not found in \"%s\"",
414 * XXX - should we pick a default?
416 return g_strdup("PATH isn't set");
421 * OK, we have what we think is the pathname
424 * First, find the last "/" in the directory,
425 * as that marks the end of the directory pathname.
427 dir_end = strrchr(prog_pathname, '/');
428 if (dir_end != NULL) {
430 * Found it. Strip off the last component,
431 * as that's the path of the program.
436 * Is there a "/.libs" at the end?
438 dir_end = strrchr(prog_pathname, '/');
439 if (dir_end != NULL) {
440 if (strcmp(dir_end, "/.libs") == 0) {
443 * Strip that off; it's an
444 * artifact of libtool.
451 * OK, we have the path we want.
453 progfile_dir = prog_pathname;
457 * This "shouldn't happen"; we apparently
458 * have no "/" in the pathname.
459 * Just free up prog_pathname.
461 retstr = g_strdup_printf("No / found in \"%s\"", prog_pathname);
462 g_free(prog_pathname);
469 * Get the directory in which the program resides.
472 get_progfile_dir(void)
478 * Get the directory in which the global configuration and data files are
481 * XXX - if we ever make libethereal a real library, used by multiple
482 * applications (more than just Tethereal 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?
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.
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.
494 * Note that some of those configuration files might be used by code in
495 * libethereal, some of them might be used by dissectors (would they
496 * belong to libethereal, the application, or a separate library?),
497 * and some of them might be used by other code (the Ethereal preferences
498 * file includes resolver preferences that control the behavior of code
499 * in libethereal, dissector preferences, and UI preferences, for
503 get_datafile_dir(void)
507 * Do we have the pathname of the program? If so, assume we're
508 * running an installed version of the program. If we fail,
509 * we don't change "datafile_dir", and thus end up using the
512 * XXX - does NSIS put the installation directory into
513 * "\HKEY_LOCAL_MACHINE\SOFTWARE\Ethereal\InstallDir"?
514 * If so, perhaps we should read that from the registry,
517 if (progfile_dir != NULL)
522 * Fall back on the default installation directory.
524 return "C:\\Program Files\\Ethereal\\";
527 * Just use DATAFILE_DIR, as that's what the configure script
535 * Get the directory in which files that, at least on UNIX, are
536 * system files (such as "/etc/ethers") are stored; on Windows,
537 * there's no "/etc" directory, so we get them from the global
538 * configuration and data file directory.
541 get_systemfile_dir(void)
544 return get_datafile_dir();
551 * Name of directory, under the user's home directory, in which
552 * personal configuration files are stored.
555 #define PF_DIR "Ethereal"
558 * XXX - should this be ".libepan"? For backwards-compatibility, I'll keep
559 * it ".ethereal" for now.
561 #define PF_DIR ".ethereal"
565 /* utf8 version of getenv, needed to get win32 filename paths */
566 char *getenv_utf8(const char *varname)
572 envvar = getenv(varname);
574 /* since GLib 2.6 we need an utf8 version of the filename */
575 #if GLIB_MAJOR_VERSION > 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION >= 6)
576 if (!G_WIN32_HAVE_WIDECHAR_API ()) {
577 /* Windows OT (9x, ME), convert from current code page to utf8 */
578 /* it's the best we can do here ... */
579 envvar = g_locale_to_utf8(envvar, -1, NULL, NULL, NULL);
584 /* Windows NT, 2000, XP, ... */
585 /* using the wide char version of getenv should work under all circumstances */
587 /* convert given varname to utf16, needed by _wgetenv */
588 varnamew = g_utf8_to_utf16(varname, -1, NULL, NULL, NULL);
589 if (varnamew == NULL) {
593 /* use wide char version of getenv */
594 envvarw = _wgetenv(varnamew);
596 if (envvarw == NULL) {
600 /* convert value to utf8 */
601 envvar = g_utf16_to_utf8(envvarw, -1, NULL, NULL, NULL);
610 * Get the directory in which personal configuration files reside;
611 * in UNIX-compatible systems, it's ".ethereal", under the user's home
612 * directory, and on Windows systems, it's "Ethereal", under %APPDATA%
613 * or, if %APPDATA% isn't set, it's "%USERPROFILE%\Application Data"
614 * (which is what %APPDATA% normally is on Windows 2000).
617 get_persconffile_dir(void)
621 char *userprofiledir;
626 static char *pf_dir = NULL;
628 /* Return the cached value, if available */
634 * Use %APPDATA% or %USERPROFILE%, so that configuration files are
635 * stored in the user profile, rather than in the home directory.
636 * The Windows convention is to store configuration information
637 * in the user profile, and doing so means you can use
638 * Ethereal even if the home directory is an inaccessible
641 appdatadir = getenv_utf8("APPDATA");
642 if (appdatadir != NULL) {
644 * Concatenate %APPDATA% with "\Ethereal".
646 pf_dir = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
650 * OK, %APPDATA% wasn't set, so use
651 * %USERPROFILE%\Application Data.
653 userprofiledir = getenv_utf8("USERPROFILE");
654 if (userprofiledir != NULL) {
655 pf_dir = g_strdup_printf(
656 "%s" G_DIR_SEPARATOR_S "Application Data" G_DIR_SEPARATOR_S "%s",
657 userprofiledir, PF_DIR);
660 * Give up and use "C:".
662 pf_dir = g_strdup_printf("C:" G_DIR_SEPARATOR_S "%s", PF_DIR);
667 * If $HOME is set, use that.
669 homedir = getenv("HOME");
670 if (homedir == NULL) {
672 * Get their home directory from the password file.
673 * If we can't even find a password file entry for them,
676 pwd = getpwuid(getuid());
679 * This is cached, so we don't need to worry
680 * about allocating multiple ones of them.
682 homedir = g_strdup(pwd->pw_dir);
686 pf_dir = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", homedir, PF_DIR);
693 * Create the directory that holds personal configuration files, if
694 * necessary. If we attempted to create it, and failed, return -1 and
695 * set "*pf_dir_path_return" to the pathname of the directory we failed
696 * to create (it's g_mallocated, so our caller should free it); otherwise,
700 create_persconffile_dir(char **pf_dir_path_return)
702 const char *pf_dir_path;
704 char *pf_dir_path_copy, *pf_dir_parent_path;
705 size_t pf_dir_parent_path_len;
710 pf_dir_path = get_persconffile_dir();
711 if (eth_stat(pf_dir_path, &s_buf) != 0 && errno == ENOENT) {
714 * Does the parent directory of that directory
715 * exist? %APPDATA% may not exist even though
716 * %USERPROFILE% does.
718 * We check for the existence of the directory
719 * by first checking whether the parent directory
720 * is just a drive letter and, if it's not, by
721 * doing a "stat()" on it. If it's a drive letter,
722 * or if the "stat()" succeeds, we assume it exists.
724 pf_dir_path_copy = g_strdup(pf_dir_path);
725 pf_dir_parent_path = get_dirname(pf_dir_path_copy);
726 pf_dir_parent_path_len = strlen(pf_dir_parent_path);
727 if (pf_dir_parent_path_len > 0
728 && pf_dir_parent_path[pf_dir_parent_path_len - 1] != ':'
729 && eth_stat(pf_dir_parent_path, &s_buf) != 0) {
731 * No, it doesn't exist - make it first.
733 ret = eth_mkdir(pf_dir_parent_path, 0755);
735 *pf_dir_path_return = pf_dir_parent_path;
739 g_free(pf_dir_path_copy);
740 ret = eth_mkdir(pf_dir_path, 0755);
742 ret = eth_mkdir(pf_dir_path, 0755);
746 * Something with that pathname exists; if it's not
747 * a directory, we'll get an error if we try to put
748 * something in it, so we don't fail here, we wait
749 * for that attempt fo fail.
754 *pf_dir_path_return = g_strdup(pf_dir_path);
760 * Returns the user's home directory on Win32.
765 static const char *home = NULL;
766 char *homedrive, *homepath;
770 /* Return the cached value, if available */
775 * XXX - should we use USERPROFILE anywhere in this process?
776 * Is there a chance that it might be set but one or more of
777 * HOMEDRIVE or HOMEPATH isn't set?
779 homedrive = getenv_utf8("HOMEDRIVE");
780 if (homedrive != NULL) {
781 homepath = getenv_utf8("HOMEPATH");
782 if (homepath != NULL) {
784 * This is cached, so we don't need to worry about
785 * allocating multiple ones of them.
788 g_malloc(strlen(homedrive) + strlen(homepath) + 1);
789 strcpy(homestring, homedrive);
790 strcat(homestring, homepath);
793 * Trim off any trailing slash or backslash.
795 lastsep = find_last_pathname_separator(homestring);
796 if (lastsep != NULL && *(lastsep + 1) == '\0') {
798 * Last separator is the last character
799 * in the string. Nuke it.
808 * Give up and use C:.
818 * Construct the path name of a personal configuration file, given the
821 * On Win32, if "for_writing" is FALSE, we check whether the file exists
822 * and, if not, construct a path name relative to the ".ethereal"
823 * subdirectory of the user's home directory, and check whether that
824 * exists; if it does, we return that, so that configuration files
825 * from earlier versions can be read.
828 get_persconffile_path(const char *filename, gboolean for_writing
840 path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", get_persconffile_dir(),
844 if (eth_stat(path, &s_buf) != 0 && errno == ENOENT) {
846 * OK, it's not in the personal configuration file
847 * directory; is it in the ".ethereal" subdirectory
848 * of their home directory?
850 old_path = g_strdup_printf(
851 "%s" G_DIR_SEPARATOR_S ".ethereal" G_DIR_SEPARATOR_S "%s",
852 get_home_dir(), filename);
853 if (eth_stat(old_path, &s_buf) == 0) {
855 * OK, it exists; return it instead.
868 * Construct the path name of a global configuration file, given the
872 get_datafile_path(const char *filename)
875 return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", get_datafile_dir(),
881 deletefile(const char *path)
883 return eth_unlink(path) == 0;
887 * Construct and return the path name of a file in the
888 * appropriate temporary file directory.
890 char *get_tempfile_path(const char *filename)
893 return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", g_get_tmp_dir(), filename);
897 * Return an error message for UNIX-style errno indications on open or
901 file_open_error_message(int err, gboolean for_writing)
904 static char errmsg_errno[1024+1];
910 errmsg = "The path to the file \"%s\" doesn't exist.";
912 errmsg = "The file \"%s\" doesn't exist.";
917 errmsg = "You don't have permission to create or write to the file \"%s\".";
919 errmsg = "You don't have permission to read the file \"%s\".";
923 errmsg = "\"%s\" is a directory (folder), not a file.";
927 errmsg = "The file \"%s\" could not be created because there is no space left on the file system.";
932 errmsg = "The file \"%s\" could not be created because you are too close to, or over, your disk quota.";
937 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
938 "The file \"%%s\" could not be %s: %s.",
939 for_writing ? "created" : "opened",
941 errmsg = errmsg_errno;
948 * Return an error message for UNIX-style errno indications on write
952 file_write_error_message(int err)
955 static char errmsg_errno[1024+1];
960 errmsg = "The file \"%s\" could not be saved because there is no space left on the file system.";
965 errmsg = "The file \"%s\" could not be saved because you are too close to, or over, your disk quota.";
970 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
971 "An error occurred while writing to the file \"%%s\": %s.",
973 errmsg = errmsg_errno;
981 file_exists(const char *fname)
983 struct stat file_stat;
988 * This is a bit tricky on win32. The st_ino field is documented as:
989 * "The inode, and therefore st_ino, has no meaning in the FAT, ..."
990 * but it *is* set to zero if stat() returns without an error,
991 * so this is working, but maybe not quite the way expected. ULFL
993 file_stat.st_ino = 1; /* this will make things work if an error occured */
994 eth_stat(fname, &file_stat);
995 if (file_stat.st_ino == 0) {
1001 if (eth_stat(fname, &file_stat) != 0 && errno == ENOENT) {
1011 * Check that the from file is not the same as to file
1012 * We do it here so we catch all cases ...
1013 * Unfortunately, the file requester gives us an absolute file
1014 * name and the read file name may be relative (if supplied on
1015 * the command line), so we can't just compare paths. From Joerg Mayer.
1018 files_identical(const char *fname1, const char *fname2)
1020 /* Two different implementations, because:
1022 * - _fullpath is not available on UN*X, so we can't get full
1023 * paths and compare them (which wouldn't work with hard links
1026 * - st_ino isn't filled in with a meaningful value on Windows.
1029 char full1[MAX_PATH], full2[MAX_PATH];
1032 * Get the absolute full paths of the file and compare them.
1033 * That won't work if you have hard links, but those aren't
1034 * much used on Windows, even though NTFS supports them.
1036 * XXX - will _fullpath work with UNC?
1038 if( _fullpath( full1, fname1, MAX_PATH ) == NULL ) {
1042 if( _fullpath( full2, fname2, MAX_PATH ) == NULL ) {
1046 if(strcmp(full1, full2) == 0) {
1052 struct stat filestat1, filestat2;
1055 * Compare st_dev and st_ino.
1057 if (eth_stat(fname1, &filestat1) == -1)
1058 return FALSE; /* can't get info about the first file */
1059 if (eth_stat(fname2, &filestat2) == -1)
1060 return FALSE; /* can't get info about the second file */
1061 return (filestat1.st_dev == filestat2.st_dev &&
1062 filestat1.st_ino == filestat2.st_ino);