1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000, 2006 Free Software Foundation, Inc.
3 Written by Ben Pfaff <blp@gnu.org>.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 #include "file-name.h"
32 #include "xreadlink.h"
34 #include <libpspp/alloc.h>
35 #include <libpspp/message.h>
36 #include <libpspp/message.h>
37 #include <libpspp/str.h>
38 #include <libpspp/verbose-msg.h>
39 #include <libpspp/version.h>
42 #define _(msgid) gettext (msgid)
44 /* PORTME: Everything in this file is system dependent. */
50 #include "stat-macros.h"
57 #include <win32/windows.h>
66 const char *config_path;
71 config_path = fn_getenv_default ("STAT_CONFIG_PATH", default_config_path);
74 /* Functions for performing operations on file names. */
77 /* Substitutes $variables in SRC, putting the result in DST,
78 properly handling the case where SRC is a substring of DST.
79 Variables are as defined by GETENV. Supports $var and ${var}
80 syntaxes; $$ substitutes as $. */
82 fn_interp_vars (struct substring src, const char *(*getenv) (const char *),
85 struct string dst = DS_EMPTY_INITIALIZER;
88 while ((c = ss_get_char (&src)) != EOF)
90 ds_put_char (&dst, c);
93 if (ss_match_char (&src, '$') || ss_is_empty (src))
94 ds_put_char (&dst, '$');
97 struct substring var_name;
101 if (ss_match_char (&src, '('))
102 ss_get_until (&src, ')', &var_name);
103 else if (ss_match_char (&src, '{'))
104 ss_get_until (&src, '}', &var_name);
106 ss_get_chars (&src, MIN (1, ss_span (src, ss_cstr (CC_ALNUM))),
109 start = ds_length (&dst);
110 ds_put_substring (&dst, var_name);
111 value = getenv (ds_cstr (&dst) + start);
112 ds_truncate (&dst, start);
114 ds_put_cstr (&dst, value);
118 ds_swap (&dst, dst_);
123 /* Expands csh tilde notation from the path INPUT into a malloc()'d
126 fn_tilde_expand (const char *input)
128 struct string output = DS_EMPTY_INITIALIZER;
131 const char *home = NULL;
132 const char *remainder = NULL;
133 if (input[1] == '/' || input[1] == '\0')
135 home = fn_getenv ("HOME");
136 remainder = input + 1;
140 struct string user_name = DS_EMPTY_INITIALIZER;
143 ds_assign_substring (&user_name,
144 ss_buffer (input + 1,
145 strcspn (input + 1, "/")));
146 pwd = getpwnam (ds_cstr (&user_name));
147 if (pwd != NULL && pwd->pw_dir[0] != '\0')
150 remainder = input + 1 + ds_length (&user_name);
152 ds_destroy (&user_name);
157 ds_put_cstr (&output, home);
158 if (*remainder != '\0')
159 ds_put_cstr (&output, remainder);
162 if (ds_is_empty (&output))
163 ds_put_cstr (&output, input);
164 return ds_cstr (&output);
168 fn_tilde_expand (const char *input)
170 return xstrdup (input);
174 /* Searches for a configuration file with name NAME in the path
175 given by PATH, which is tilde- and environment-interpolated.
176 Directories in PATH are delimited by ':'. Returns the
177 malloc'd full name of the first file found, or NULL if none is
180 If PREFIX is non-NULL, then it is prefixed to each file name;
181 i.e., it looks like PREFIX/PATH_COMPONENT/NAME. This is not
182 done with absolute directories in the path. */
184 fn_search_path (const char *base_name, const char *path_, const char *prefix)
187 struct substring dir_;
188 struct string file = DS_EMPTY_INITIALIZER;
191 if (fn_is_absolute (base_name))
192 return fn_tilde_expand (base_name);
194 /* Interpolate environment variables. */
195 ds_init_cstr (&path, path_);
196 fn_interp_vars (ds_ss (&path), fn_getenv, &path);
198 verbose_msg (2, _("searching for \"%s\" in path \"%s\""),
199 base_name, ds_cstr (&path));
200 while (ds_separate (&path, ss_cstr (":"), &save_idx, &dir_))
204 /* Do tilde expansion. */
205 ds_init_substring (&dir, dir_);
206 if (ds_first (&dir) == '~')
208 char *tmp_str = fn_tilde_expand (ds_cstr (&dir));
209 ds_assign_cstr (&dir, tmp_str);
213 /* Construct file name. */
215 if (prefix != NULL && !fn_is_absolute (ds_cstr (&dir)))
217 ds_put_cstr (&file, prefix);
218 ds_put_char (&file, '/');
220 ds_put_cstr (&file, ds_cstr (&dir));
221 if (!ds_is_empty (&file) && ds_last (&file) != '/')
222 ds_put_char (&file, '/');
223 ds_put_cstr (&file, base_name);
226 /* Check whether file exists. */
227 if (fn_exists (ds_cstr (&file)))
229 verbose_msg (2, _("...found \"%s\""), ds_cstr (&file));
231 return ds_cstr (&file);
236 verbose_msg (2, _("...not found"));
242 /* fn_normalize(): This very OS-dependent routine canonicalizes
243 file name FN1. The file name should not need to be the name of an
244 existing file. Returns a malloc()'d copy of the canonical name.
245 This function must always succeed; if it needs to bail out then it
246 should return xstrdup(FN1). */
249 fn_normalize (const char *file_name)
252 char *fn1, *fn2, *dest;
255 if (fn_is_special (file_name))
256 return xstrdup (file_name);
258 fn1 = fn_tilde_expand (file_name);
260 /* Follow symbolic links. */
264 fn1 = fn_readlink (fn1);
273 maxlen = strlen (fn1) * 2;
276 dest = fn2 = xmalloc (maxlen + 1);
284 while (getcwd (dest, maxlen - (dest - fn2)) == NULL && errno == ERANGE)
287 dest = fn2 = xrealloc (fn2, maxlen + 1);
296 dest = strchr (fn2, '\0');
297 if (dest - fn2 >= maxlen)
299 int ofs = dest - fn2;
301 fn2 = xrealloc (fn2, maxlen + 1);
315 if (c == '/' || c == 0)
317 /* remove `./', `../' from directory */
318 if (dest[-1] == '.' && dest[-2] == '/')
320 else if (dest[-1] == '.' && dest[-2] == '.' && dest[-3] == '/')
325 while (dest[-1] != '/')
328 else if (dest[-1] != '/') /* remove extra slashes */
333 if (dest[-1] == '/' && dest > fn2 + 1)
338 return xrealloc (fn2, strlen (fn2) + 1);
346 if (dest - fn2 >= maxlen)
348 int ofs = dest - fn2;
350 fn2 = xrealloc (fn2, maxlen + 1);
357 #elif defined (__WIN32__)
359 fn_normalize (const char *fn1)
365 /* Don't change special file names. */
366 if (is_special_file_name (file_name))
367 return xstrdup (file_name);
369 /* First find the required buffer length. */
370 len = GetFullPathName (fn1, 0, NULL, NULL);
377 /* Then make a buffer that big. */
379 success = GetFullPathName (fn1, len, fn2, NULL);
380 if (success >= len || success == 0)
390 fn_normalize (const char *fn1)
392 char *fn2 = _fullpath (NULL, fn1, 0);
396 for (cp = fn2; *cp; cp++)
397 *cp = toupper ((unsigned char) (*cp));
400 return xstrdup (fn1);
404 fn_normalize (const char *fn1)
406 char *fn2 = xmalloc (1024);
408 fn2 = xrealloc (fn2, strlen (fn2) + 1);
411 #else /* not Lose32, Unix, or DJGPP */
413 fn_normalize (const char *fn)
417 #endif /* not Lose32, Unix, or DJGPP */
419 /* Returns the directory part of FILE_NAME, as a malloc()'d
422 fn_dir_name (const char *file_name)
428 len = strlen (file_name);
429 if (len == 1 && file_name[0] == '/')
431 else if (len && file_name[len - 1] == '/')
432 p = buf_find_reverse (file_name, len - 1, file_name + len - 1, 1);
434 p = strrchr (file_name, '/');
438 s = xmalloc (p - file_name + 1);
439 memcpy (s, file_name, p - file_name);
440 s[p - file_name] = 0;
445 /* Returns the extension part of FILE_NAME as a malloc()'d string.
446 If FILE_NAME does not have an extension, returns an empty
449 fn_extension (const char *file_name)
451 const char *extension = strrchr (file_name, '.');
452 if (extension == NULL)
454 return xstrdup (extension);
458 /* Returns the current working directory, as a malloc()'d string.
464 char *buffer = xmalloc (size);
468 char *value = getcwd (buffer, size);
474 buffer = xmalloc (size);
482 char *buffer = xmalloc (size);
494 /* Find out information about files. */
496 /* Returns nonzero iff NAME specifies an absolute file name. */
498 fn_is_absolute (const char *name)
502 || !strncmp (name, "./", 2)
503 || !strncmp (name, "../", 3)
506 #elif defined (__MSDOS__)
508 || !strncmp (name, ".\\", 2)
509 || !strncmp (name, "..\\", 3)
510 || (name[0] && name[1] == ':'))
517 /* Returns 1 if FILE_NAME is a virtual file that doesn't
518 really exist on disk, 0 if it's a real file name. */
520 fn_is_special (const char *file_name)
522 if (!strcmp (file_name, "-") || !strcmp (file_name, "stdin")
523 || !strcmp (file_name, "stdout") || !strcmp (file_name, "stderr")
525 || file_name[0] == '|'
526 || (*file_name && file_name[strlen (file_name) - 1] == '|')
534 /* Returns nonzero if file with name NAME exists. */
536 fn_exists (const char *name)
541 return stat (name, &temp) == 0;
543 FILE *f = fopen (name, "r");
551 /* Returns the symbolic link value for FILE_NAME as a dynamically
552 allocated buffer, or a null pointer on failure. */
554 fn_readlink (const char *file_name)
556 return xreadlink (file_name, 32);
559 /* Environment variables. */
561 /* Simulates $VER and $ARCH environment variables. */
563 fn_getenv (const char *s)
565 if (!strcmp (s, "VER"))
566 return fn_getenv_default ("STAT_VER", bare_version);
567 else if (!strcmp (s, "ARCH"))
568 return fn_getenv_default ("STAT_ARCH", host_system);
573 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
575 fn_getenv_default (const char *key, const char *def)
577 const char *value = getenv (key);
578 return value ? value : def;
581 /* Basic file handling. */
583 /* Used for giving an error message on a set_safer security
586 safety_violation (const char *fn)
588 msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
593 /* As a general comment on the following routines, a `sensible value'
594 for errno includes 0 if there is no associated system error. The
595 routines will only set errno to 0 if there is an error in a
596 callback that sets errno to 0; they themselves won't. */
598 /* File open routine that understands `-' as stdin/stdout and `|cmd'
599 as a pipe to command `cmd'. Returns resultant FILE on success,
600 NULL on failure. If NULL is returned then errno is set to a
603 fn_open (const char *fn, const char *mode)
605 assert (mode[0] == 'r' || mode[0] == 'w');
607 if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
609 else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
611 else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
617 if (get_safer_mode ())
618 return safety_violation (fn);
620 return popen (&fn[1], mode);
622 else if (*fn && fn[strlen (fn) - 1] == '|')
627 if (get_safer_mode ())
628 return safety_violation (fn);
630 s = local_alloc (strlen (fn));
631 memcpy (s, fn, strlen (fn) - 1);
632 s[strlen (fn) - 1] = 0;
643 FILE *f = fopen (fn, mode);
645 if (f && mode[0] == 'w')
646 setvbuf (f, NULL, _IOLBF, 0);
652 /* Counterpart to fn_open that closes file F with name FN; returns 0
653 on success, EOF on failure. If EOF is returned, errno is set to a
656 fn_close (const char *fn, FILE *f)
658 if (!strcmp (fn, "-"))
661 else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
672 /* A file's identity. */
675 dev_t device; /* Device number. */
676 ino_t inode; /* Inode number. */
679 /* Returns a pointer to a dynamically allocated structure whose
680 value can be used to tell whether two files are actually the
681 same file. Returns a null pointer if no information about the
682 file is available, perhaps because it does not exist. The
683 caller is responsible for freeing the structure with
684 fn_free_identity() when finished. */
685 struct file_identity *
686 fn_get_identity (const char *file_name)
690 if (stat (file_name, &s) == 0)
692 struct file_identity *identity = xmalloc (sizeof *identity);
693 identity->device = s.st_dev;
694 identity->inode = s.st_ino;
701 /* Frees IDENTITY obtained from fn_get_identity(). */
703 fn_free_identity (struct file_identity *identity)
708 /* Compares A and B, returning a strcmp()-type result. */
710 fn_compare_file_identities (const struct file_identity *a,
711 const struct file_identity *b)
715 if (a->device != b->device)
716 return a->device < b->device ? -1 : 1;
718 return a->inode < b->inode ? -1 : a->inode > b->inode;
721 /* A file's identity. */
724 char *normalized_file_name; /* File's normalized name. */
727 /* Returns a pointer to a dynamically allocated structure whose
728 value can be used to tell whether two files are actually the
729 same file. Returns a null pointer if no information about the
730 file is available, perhaps because it does not exist. The
731 caller is responsible for freeing the structure with
732 fn_free_identity() when finished. */
733 struct file_identity *
734 fn_get_identity (const char *file_name)
736 struct file_identity *identity = xmalloc (sizeof *identity);
737 identity->normalized_file_name = fn_normalize (file_name);
741 /* Frees IDENTITY obtained from fn_get_identity(). */
743 fn_free_identity (struct file_identity *identity)
745 if (identity != NULL)
747 free (identity->normalized_file_name);
752 /* Compares A and B, returning a strcmp()-type result. */
754 fn_compare_file_identities (const struct file_identity *a,
755 const struct file_identity *b)
757 return strcmp (a->normalized_file_name, b->normalized_file_name);
759 #endif /* not unix */