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
21 #include <libpspp/message.h>
22 #include "file-name.h"
27 #include <libpspp/alloc.h>
29 #include <libpspp/message.h>
30 #include <libpspp/str.h>
32 #include <libpspp/version.h>
33 #include "xreadlink.h"
36 #define _(msgid) gettext (msgid)
38 /* PORTME: Everything in this file is system dependent. */
44 #include "stat-macros.h"
51 #include <win32/windows.h>
60 const char *config_path;
65 config_path = fn_getenv_default ("STAT_CONFIG_PATH", default_config_path);
68 /* Functions for performing operations on file names. */
71 /* Substitutes $variables as defined by GETENV into TARGET.
72 TARGET must be a string containing the text for which substitution
74 Supports $var and ${var} syntaxes;
78 fn_interp_vars (struct string *target,
79 const char *(*getenv) (const char *))
86 input = xmalloc(ds_length(target) + 1);
89 strcpy(input, ds_c_str(target));
91 if (NULL == strchr (ds_c_str(target), '$'))
108 ds_putc (target, '$');
117 start = ds_length (target);
132 while (*s && *s != stop
133 && (stop || isalpha ((unsigned char) *s)))
135 ds_putc (target, *s++);
138 value = getenv (ds_c_str (target) + start);
139 ds_truncate (target, start);
140 ds_puts (target, value);
142 if (stop && *s == stop)
148 ds_putc (target, *s++);
158 /* Expands csh tilde notation from the path INPUT into a malloc()'d
161 fn_tilde_expand (const char *input)
163 struct string output = DS_INITIALIZER;
166 const char *home = NULL;
167 const char *remainder = NULL;
168 if (input[1] == '/' || input[1] == '\0')
170 home = fn_getenv ("HOME");
171 remainder = input + 1;
175 struct string user_name = DS_INITIALIZER;
178 ds_assign_buffer (&user_name, input + 1, strcspn (input + 1, "/"));
179 pwd = getpwnam (ds_c_str (&user_name));
180 if (pwd != NULL && pwd->pw_dir[0] != '\0')
183 remainder = input + 1 + ds_length (&user_name);
185 ds_destroy (&user_name);
190 ds_puts (&output, home);
191 if (*remainder != '\0')
192 ds_puts (&output, remainder);
195 if (ds_is_empty (&output))
196 ds_puts (&output, input);
197 return ds_c_str (&output);
201 fn_tilde_expand (const char *input)
203 return xstrdup (input);
207 /* Searches for a configuration file with name NAME in the path
208 given by PATH, which is tilde- and environment-interpolated.
209 Directories in PATH are delimited by ':'. Returns the
210 malloc'd full name of the first file found, or NULL if none is
213 If PREFIX is non-NULL, then it is prefixed to each file name;
214 i.e., it looks like PREFIX/PATH_COMPONENT/NAME. This is not
215 done with absolute directories in the path. */
217 fn_search_path (const char *base_name, const char *path_, const char *prefix)
220 struct string dir = DS_INITIALIZER;
221 struct string file = DS_INITIALIZER;
224 if (fn_is_absolute (base_name))
225 return fn_tilde_expand (base_name);
227 /* Interpolate environment variables. */
228 ds_create (&path, path_);
229 fn_interp_vars (&path, fn_getenv);
231 verbose_msg (2, _("searching for \"%s\" in path \"%s\""),
232 base_name, ds_c_str (&path));
233 while (ds_separate (&path, &dir, ":", &save_idx))
235 /* Do tilde expansion. */
236 if (ds_first (&dir) == '~')
238 char *tmp_str = fn_tilde_expand (ds_c_str (&dir));
239 ds_assign_c_str (&dir, tmp_str);
243 /* Construct file name. */
245 if (prefix != NULL && !fn_is_absolute (ds_c_str (&dir)))
247 ds_puts (&file, prefix);
248 ds_putc (&file, '/');
250 ds_puts (&file, ds_c_str (&dir));
251 if (ds_length (&dir) && ds_last (&file) != '/')
252 ds_putc (&file, '/');
253 ds_puts (&file, base_name);
255 /* Check whether file exists. */
256 if (fn_exists (ds_c_str (&file)))
258 verbose_msg (2, _("...found \"%s\""), ds_c_str (&file));
261 return ds_c_str (&file);
266 verbose_msg (2, _("...not found"));
273 /* fn_normalize(): This very OS-dependent routine canonicalizes
274 file name FN1. The file name should not need to be the name of an
275 existing file. Returns a malloc()'d copy of the canonical name.
276 This function must always succeed; if it needs to bail out then it
277 should return xstrdup(FN1). */
280 fn_normalize (const char *file_name)
283 char *fn1, *fn2, *dest;
286 if (fn_is_special (file_name))
287 return xstrdup (file_name);
289 fn1 = fn_tilde_expand (file_name);
291 /* Follow symbolic links. */
295 fn1 = fn_readlink (fn1);
304 maxlen = strlen (fn1) * 2;
307 dest = fn2 = xmalloc (maxlen + 1);
315 while (getcwd (dest, maxlen - (dest - fn2)) == NULL && errno == ERANGE)
318 dest = fn2 = xrealloc (fn2, maxlen + 1);
327 dest = strchr (fn2, '\0');
328 if (dest - fn2 >= maxlen)
330 int ofs = dest - fn2;
332 fn2 = xrealloc (fn2, maxlen + 1);
346 if (c == '/' || c == 0)
348 /* remove `./', `../' from directory */
349 if (dest[-1] == '.' && dest[-2] == '/')
351 else if (dest[-1] == '.' && dest[-2] == '.' && dest[-3] == '/')
356 while (dest[-1] != '/')
359 else if (dest[-1] != '/') /* remove extra slashes */
364 if (dest[-1] == '/' && dest > fn2 + 1)
369 return xrealloc (fn2, strlen (fn2) + 1);
377 if (dest - fn2 >= maxlen)
379 int ofs = dest - fn2;
381 fn2 = xrealloc (fn2, maxlen + 1);
388 #elif defined (__WIN32__)
390 fn_normalize (const char *fn1)
396 /* Don't change special file names. */
397 if (is_special_file_name (file_name))
398 return xstrdup (file_name);
400 /* First find the required buffer length. */
401 len = GetFullPathName (fn1, 0, NULL, NULL);
408 /* Then make a buffer that big. */
410 success = GetFullPathName (fn1, len, fn2, NULL);
411 if (success >= len || success == 0)
421 fn_normalize (const char *fn1)
423 char *fn2 = _fullpath (NULL, fn1, 0);
427 for (cp = fn2; *cp; cp++)
428 *cp = toupper ((unsigned char) (*cp));
431 return xstrdup (fn1);
435 fn_normalize (const char *fn1)
437 char *fn2 = xmalloc (1024);
439 fn2 = xrealloc (fn2, strlen (fn2) + 1);
442 #else /* not Lose32, Unix, or DJGPP */
444 fn_normalize (const char *fn)
448 #endif /* not Lose32, Unix, or DJGPP */
450 /* Returns the directory part of FILE_NAME, as a malloc()'d
453 fn_dir_name (const char *file_name)
459 len = strlen (file_name);
460 if (len == 1 && file_name[0] == '/')
462 else if (len && file_name[len - 1] == '/')
463 p = buf_find_reverse (file_name, len - 1, file_name + len - 1, 1);
465 p = strrchr (file_name, '/');
469 s = xmalloc (p - file_name + 1);
470 memcpy (s, file_name, p - file_name);
471 s[p - file_name] = 0;
476 /* Returns the extension part of FILE_NAME as a malloc()'d string.
477 If FILE_NAME does not have an extension, returns an empty
480 fn_extension (const char *file_name)
482 const char *extension = strrchr (file_name, '.');
483 if (extension == NULL)
485 return xstrdup (extension);
489 /* Returns the current working directory, as a malloc()'d string.
495 char *buffer = xmalloc (size);
499 char *value = getcwd (buffer, size);
505 buffer = xmalloc (size);
513 char *buffer = xmalloc (size);
525 /* Find out information about files. */
527 /* Returns nonzero iff NAME specifies an absolute file name. */
529 fn_is_absolute (const char *name)
533 || !strncmp (name, "./", 2)
534 || !strncmp (name, "../", 3)
537 #elif defined (__MSDOS__)
539 || !strncmp (name, ".\\", 2)
540 || !strncmp (name, "..\\", 3)
541 || (name[0] && name[1] == ':'))
548 /* Returns 1 if FILE_NAME is a virtual file that doesn't
549 really exist on disk, 0 if it's a real file name. */
551 fn_is_special (const char *file_name)
553 if (!strcmp (file_name, "-") || !strcmp (file_name, "stdin")
554 || !strcmp (file_name, "stdout") || !strcmp (file_name, "stderr")
556 || file_name[0] == '|'
557 || (*file_name && file_name[strlen (file_name) - 1] == '|')
565 /* Returns nonzero if file with name NAME exists. */
567 fn_exists (const char *name)
572 return stat (name, &temp) == 0;
574 FILE *f = fopen (name, "r");
582 /* Returns the symbolic link value for FILE_NAME as a dynamically
583 allocated buffer, or a null pointer on failure. */
585 fn_readlink (const char *file_name)
587 return xreadlink (file_name, 32);
590 /* Environment variables. */
592 /* Simulates $VER and $ARCH environment variables. */
594 fn_getenv (const char *s)
596 if (!strcmp (s, "VER"))
597 return fn_getenv_default ("STAT_VER", bare_version);
598 else if (!strcmp (s, "ARCH"))
599 return fn_getenv_default ("STAT_ARCH", host_system);
604 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
606 fn_getenv_default (const char *key, const char *def)
608 const char *value = getenv (key);
609 return value ? value : def;
612 /* Basic file handling. */
614 /* Used for giving an error message on a set_safer security
617 safety_violation (const char *fn)
619 msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
624 /* As a general comment on the following routines, a `sensible value'
625 for errno includes 0 if there is no associated system error. The
626 routines will only set errno to 0 if there is an error in a
627 callback that sets errno to 0; they themselves won't. */
629 /* File open routine that understands `-' as stdin/stdout and `|cmd'
630 as a pipe to command `cmd'. Returns resultant FILE on success,
631 NULL on failure. If NULL is returned then errno is set to a
634 fn_open (const char *fn, const char *mode)
636 assert (mode[0] == 'r' || mode[0] == 'w');
638 if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
640 else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
642 else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
648 if (get_safer_mode ())
649 return safety_violation (fn);
651 return popen (&fn[1], mode);
653 else if (*fn && fn[strlen (fn) - 1] == '|')
658 if (get_safer_mode ())
659 return safety_violation (fn);
661 s = local_alloc (strlen (fn));
662 memcpy (s, fn, strlen (fn) - 1);
663 s[strlen (fn) - 1] = 0;
674 FILE *f = fopen (fn, mode);
676 if (f && mode[0] == 'w')
677 setvbuf (f, NULL, _IOLBF, 0);
683 /* Counterpart to fn_open that closes file F with name FN; returns 0
684 on success, EOF on failure. If EOF is returned, errno is set to a
687 fn_close (const char *fn, FILE *f)
689 if (!strcmp (fn, "-"))
692 else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
703 /* A file's identity. */
706 dev_t device; /* Device number. */
707 ino_t inode; /* Inode number. */
710 /* Returns a pointer to a dynamically allocated structure whose
711 value can be used to tell whether two files are actually the
712 same file. Returns a null pointer if no information about the
713 file is available, perhaps because it does not exist. The
714 caller is responsible for freeing the structure with
715 fn_free_identity() when finished. */
716 struct file_identity *
717 fn_get_identity (const char *file_name)
721 if (stat (file_name, &s) == 0)
723 struct file_identity *identity = xmalloc (sizeof *identity);
724 identity->device = s.st_dev;
725 identity->inode = s.st_ino;
732 /* Frees IDENTITY obtained from fn_get_identity(). */
734 fn_free_identity (struct file_identity *identity)
739 /* Compares A and B, returning a strcmp()-type result. */
741 fn_compare_file_identities (const struct file_identity *a,
742 const struct file_identity *b)
746 if (a->device != b->device)
747 return a->device < b->device ? -1 : 1;
749 return a->inode < b->inode ? -1 : a->inode > b->inode;
752 /* A file's identity. */
755 char *normalized_file_name; /* File's normalized name. */
758 /* Returns a pointer to a dynamically allocated structure whose
759 value can be used to tell whether two files are actually the
760 same file. Returns a null pointer if no information about the
761 file is available, perhaps because it does not exist. The
762 caller is responsible for freeing the structure with
763 fn_free_identity() when finished. */
764 struct file_identity *
765 fn_get_identity (const char *file_name)
767 struct file_identity *identity = xmalloc (sizeof *identity);
768 identity->normalized_file_name = fn_normalize (file_name);
772 /* Frees IDENTITY obtained from fn_get_identity(). */
774 fn_free_identity (struct file_identity *identity)
776 if (identity != NULL)
778 free (identity->normalized_file_name);
783 /* Compares A and B, returning a strcmp()-type result. */
785 fn_compare_file_identities (const struct file_identity *a,
786 const struct file_identity *b)
788 return strcmp (a->normalized_file_name, b->normalized_file_name);
790 #endif /* not unix */