1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000, 2006 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful, but
10 WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 #include "file-name.h"
31 #include "xreadlink.h"
33 #include <libpspp/alloc.h>
34 #include <libpspp/message.h>
35 #include <libpspp/message.h>
36 #include <libpspp/str.h>
37 #include <libpspp/verbose-msg.h>
38 #include <libpspp/version.h>
41 #define _(msgid) gettext (msgid)
43 /* PORTME: Everything in this file is system dependent. */
49 #include "stat-macros.h"
56 #include <win32/windows.h>
65 const char *config_path;
70 config_path = fn_getenv_default ("STAT_CONFIG_PATH", default_config_path);
73 /* Functions for performing operations on file names. */
76 /* Substitutes $variables in SRC, putting the result in DST,
77 properly handling the case where SRC is a substring of DST.
78 Variables are as defined by GETENV. Supports $var and ${var}
79 syntaxes; $$ substitutes as $. */
81 fn_interp_vars (struct substring src, const char *(*getenv) (const char *),
84 struct string dst = DS_EMPTY_INITIALIZER;
87 while ((c = ss_get_char (&src)) != EOF)
89 ds_put_char (&dst, c);
92 if (ss_match_char (&src, '$') || ss_is_empty (src))
93 ds_put_char (&dst, '$');
96 struct substring var_name;
100 if (ss_match_char (&src, '('))
101 ss_get_until (&src, ')', &var_name);
102 else if (ss_match_char (&src, '{'))
103 ss_get_until (&src, '}', &var_name);
105 ss_get_chars (&src, MIN (1, ss_span (src, ss_cstr (CC_ALNUM))),
108 start = ds_length (&dst);
109 ds_put_substring (&dst, var_name);
110 value = getenv (ds_cstr (&dst) + start);
111 ds_truncate (&dst, start);
113 ds_put_cstr (&dst, value);
117 ds_swap (&dst, dst_);
122 /* Expands csh tilde notation from the path INPUT into a malloc()'d
125 fn_tilde_expand (const char *input)
127 struct string output = DS_EMPTY_INITIALIZER;
130 const char *home = NULL;
131 const char *remainder = NULL;
132 if (input[1] == '/' || input[1] == '\0')
134 home = fn_getenv ("HOME");
135 remainder = input + 1;
139 struct string user_name = DS_EMPTY_INITIALIZER;
142 ds_assign_substring (&user_name,
143 ss_buffer (input + 1,
144 strcspn (input + 1, "/")));
145 pwd = getpwnam (ds_cstr (&user_name));
146 if (pwd != NULL && pwd->pw_dir[0] != '\0')
148 home = xstrdup (pwd->pw_dir);
149 remainder = input + 1 + ds_length (&user_name);
151 ds_destroy (&user_name);
156 ds_put_cstr (&output, home);
157 if (*remainder != '\0')
158 ds_put_cstr (&output, remainder);
161 if (ds_is_empty (&output))
162 ds_put_cstr (&output, input);
163 return ds_cstr (&output);
167 fn_tilde_expand (const char *input)
169 return xstrdup (input);
173 /* Searches for a configuration file with name NAME in the path
174 given by PATH, which is tilde- and environment-interpolated.
175 Directories in PATH are delimited by ':'. Returns the
176 malloc'd full name of the first file found, or NULL if none is
179 fn_search_path (const char *base_name, const char *path_)
182 struct substring dir_;
183 struct string file = DS_EMPTY_INITIALIZER;
186 if (fn_is_absolute (base_name))
187 return fn_tilde_expand (base_name);
189 /* Interpolate environment variables. */
190 ds_init_cstr (&path, path_);
191 fn_interp_vars (ds_ss (&path), fn_getenv, &path);
193 verbose_msg (2, _("searching for \"%s\" in path \"%s\""),
194 base_name, ds_cstr (&path));
195 while (ds_separate (&path, ss_cstr (":"), &save_idx, &dir_))
199 /* Do tilde expansion. */
200 ds_init_substring (&dir, dir_);
201 if (ds_first (&dir) == '~')
203 char *tmp_str = fn_tilde_expand (ds_cstr (&dir));
204 ds_assign_cstr (&dir, tmp_str);
208 /* Construct file name. */
210 ds_put_cstr (&file, ds_cstr (&dir));
211 if (!ds_is_empty (&file) && ds_last (&file) != '/')
212 ds_put_char (&file, '/');
213 ds_put_cstr (&file, base_name);
216 /* Check whether file exists. */
217 if (fn_exists (ds_cstr (&file)))
219 verbose_msg (2, _("...found \"%s\""), ds_cstr (&file));
221 return ds_cstr (&file);
226 verbose_msg (2, _("...not found"));
232 /* fn_normalize(): This very OS-dependent routine canonicalizes
233 file name FN1. The file name should not need to be the name of an
234 existing file. Returns a malloc()'d copy of the canonical name.
235 This function must always succeed; if it needs to bail out then it
236 should return xstrdup(FN1). */
239 fn_normalize (const char *file_name)
242 char *fn1, *fn2, *dest;
245 if (fn_is_special (file_name))
246 return xstrdup (file_name);
248 fn1 = fn_tilde_expand (file_name);
250 /* Follow symbolic links. */
254 fn1 = fn_readlink (fn1);
263 maxlen = strlen (fn1) * 2;
266 dest = fn2 = xmalloc (maxlen + 1);
274 while (getcwd (dest, maxlen - (dest - fn2)) == NULL && errno == ERANGE)
277 dest = fn2 = xrealloc (fn2, maxlen + 1);
286 dest = strchr (fn2, '\0');
287 if (dest - fn2 >= maxlen)
289 int ofs = dest - fn2;
291 fn2 = xrealloc (fn2, maxlen + 1);
305 if (c == '/' || c == 0)
307 /* remove `./', `../' from directory */
308 if (dest[-1] == '.' && dest[-2] == '/')
310 else if (dest[-1] == '.' && dest[-2] == '.' && dest[-3] == '/')
315 while (dest[-1] != '/')
318 else if (dest[-1] != '/') /* remove extra slashes */
323 if (dest[-1] == '/' && dest > fn2 + 1)
328 return xrealloc (fn2, strlen (fn2) + 1);
336 if (dest - fn2 >= maxlen)
338 int ofs = dest - fn2;
340 fn2 = xrealloc (fn2, maxlen + 1);
347 #elif defined (__WIN32__)
349 fn_normalize (const char *fn1)
355 /* Don't change special file names. */
356 if (is_special_file_name (file_name))
357 return xstrdup (file_name);
359 /* First find the required buffer length. */
360 len = GetFullPathName (fn1, 0, NULL, NULL);
367 /* Then make a buffer that big. */
369 success = GetFullPathName (fn1, len, fn2, NULL);
370 if (success >= len || success == 0)
380 fn_normalize (const char *fn1)
382 char *fn2 = _fullpath (NULL, fn1, 0);
386 for (cp = fn2; *cp; cp++)
387 *cp = toupper ((unsigned char) (*cp));
390 return xstrdup (fn1);
394 fn_normalize (const char *fn1)
396 char *fn2 = xmalloc (1024);
398 fn2 = xrealloc (fn2, strlen (fn2) + 1);
401 #else /* not Lose32, Unix, or DJGPP */
403 fn_normalize (const char *fn)
407 #endif /* not Lose32, Unix, or DJGPP */
409 /* Returns the directory part of FILE_NAME, as a malloc()'d
412 fn_dir_name (const char *file_name)
418 len = strlen (file_name);
419 if (len == 1 && file_name[0] == '/')
421 else if (len && file_name[len - 1] == '/')
422 p = buf_find_reverse (file_name, len - 1, file_name + len - 1, 1);
424 p = strrchr (file_name, '/');
428 s = xmalloc (p - file_name + 1);
429 memcpy (s, file_name, p - file_name);
430 s[p - file_name] = 0;
435 /* Returns the extension part of FILE_NAME as a malloc()'d string.
436 If FILE_NAME does not have an extension, returns an empty
439 fn_extension (const char *file_name)
441 const char *extension = strrchr (file_name, '.');
442 if (extension == NULL)
444 return xstrdup (extension);
448 /* Returns the current working directory, as a malloc()'d string.
454 char *buffer = xmalloc (size);
458 char *value = getcwd (buffer, size);
464 buffer = xmalloc (size);
472 char *buffer = xmalloc (size);
484 /* Find out information about files. */
486 /* Returns true iff NAME specifies an absolute file name. */
488 fn_is_absolute (const char *name)
492 || !strncmp (name, "./", 2)
493 || !strncmp (name, "../", 3)
496 #elif defined (__MSDOS__)
498 || !strncmp (name, ".\\", 2)
499 || !strncmp (name, "..\\", 3)
500 || (name[0] && name[1] == ':'))
507 /* Returns true if FILE_NAME is a virtual file that doesn't
508 really exist on disk, false if it's a real file name. */
510 fn_is_special (const char *file_name)
512 if (!strcmp (file_name, "-") || !strcmp (file_name, "stdin")
513 || !strcmp (file_name, "stdout") || !strcmp (file_name, "stderr")
515 || file_name[0] == '|'
516 || (*file_name && file_name[strlen (file_name) - 1] == '|')
524 /* Returns true if file with name NAME exists. */
526 fn_exists (const char *name)
531 return stat (name, &temp) == 0;
533 FILE *f = fopen (name, "r");
541 /* Returns the symbolic link value for FILE_NAME as a dynamically
542 allocated buffer, or a null pointer on failure. */
544 fn_readlink (const char *file_name)
546 return xreadlink (file_name, 32);
549 /* Environment variables. */
551 /* Simulates $VER and $ARCH environment variables. */
553 fn_getenv (const char *s)
555 if (!strcmp (s, "VER"))
556 return fn_getenv_default ("STAT_VER", bare_version);
557 else if (!strcmp (s, "ARCH"))
558 return fn_getenv_default ("STAT_ARCH", host_system);
563 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
565 fn_getenv_default (const char *key, const char *def)
567 const char *value = getenv (key);
568 return value ? value : def;
571 /* Basic file handling. */
573 /* Used for giving an error message on a set_safer security
576 safety_violation (const char *fn)
578 msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
583 /* As a general comment on the following routines, a `sensible value'
584 for errno includes 0 if there is no associated system error. The
585 routines will only set errno to 0 if there is an error in a
586 callback that sets errno to 0; they themselves won't. */
588 /* File open routine that understands `-' as stdin/stdout and `|cmd'
589 as a pipe to command `cmd'. Returns resultant FILE on success,
590 NULL on failure. If NULL is returned then errno is set to a
593 fn_open (const char *fn, const char *mode)
595 assert (mode[0] == 'r' || mode[0] == 'w');
597 if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
599 else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
601 else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
607 if (get_safer_mode ())
608 return safety_violation (fn);
610 return popen (&fn[1], mode);
612 else if (*fn && fn[strlen (fn) - 1] == '|')
617 if (get_safer_mode ())
618 return safety_violation (fn);
620 s = local_alloc (strlen (fn));
621 memcpy (s, fn, strlen (fn) - 1);
622 s[strlen (fn) - 1] = 0;
633 FILE *f = fopen (fn, mode);
635 if (f && mode[0] == 'w')
636 setvbuf (f, NULL, _IOLBF, 0);
642 /* Counterpart to fn_open that closes file F with name FN; returns 0
643 on success, EOF on failure. If EOF is returned, errno is set to a
646 fn_close (const char *fn, FILE *f)
648 if (!strcmp (fn, "-"))
651 else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
662 /* A file's identity. */
665 dev_t device; /* Device number. */
666 ino_t inode; /* Inode number. */
669 /* Returns a pointer to a dynamically allocated structure whose
670 value can be used to tell whether two files are actually the
671 same file. Returns a null pointer if no information about the
672 file is available, perhaps because it does not exist. The
673 caller is responsible for freeing the structure with
674 fn_free_identity() when finished. */
675 struct file_identity *
676 fn_get_identity (const char *file_name)
680 if (stat (file_name, &s) == 0)
682 struct file_identity *identity = xmalloc (sizeof *identity);
683 identity->device = s.st_dev;
684 identity->inode = s.st_ino;
691 /* Frees IDENTITY obtained from fn_get_identity(). */
693 fn_free_identity (struct file_identity *identity)
698 /* Compares A and B, returning a strcmp()-type result. */
700 fn_compare_file_identities (const struct file_identity *a,
701 const struct file_identity *b)
705 if (a->device != b->device)
706 return a->device < b->device ? -1 : 1;
708 return a->inode < b->inode ? -1 : a->inode > b->inode;
711 /* A file's identity. */
714 char *normalized_file_name; /* File's normalized name. */
717 /* Returns a pointer to a dynamically allocated structure whose
718 value can be used to tell whether two files are actually the
719 same file. Returns a null pointer if no information about the
720 file is available, perhaps because it does not exist. The
721 caller is responsible for freeing the structure with
722 fn_free_identity() when finished. */
723 struct file_identity *
724 fn_get_identity (const char *file_name)
726 struct file_identity *identity = xmalloc (sizeof *identity);
727 identity->normalized_file_name = fn_normalize (file_name);
731 /* Frees IDENTITY obtained from fn_get_identity(). */
733 fn_free_identity (struct file_identity *identity)
735 if (identity != NULL)
737 free (identity->normalized_file_name);
742 /* Compares A and B, returning a strcmp()-type result. */
744 fn_compare_file_identities (const struct file_identity *a,
745 const struct file_identity *b)
747 return strcmp (a->normalized_file_name, b->normalized_file_name);
749 #endif /* not unix */