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"
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 as defined by GETENV into TARGET.
77 TARGET must be a string containing the text for which substitution
79 Supports $var and ${var} syntaxes;
83 fn_interp_vars (struct string *target,
84 const char *(*getenv) (const char *))
91 input = xmalloc(ds_length(target) + 1);
94 strcpy(input, ds_c_str(target));
96 if (NULL == strchr (ds_c_str(target), '$'))
113 ds_putc (target, '$');
122 start = ds_length (target);
137 while (*s && *s != stop
138 && (stop || isalpha ((unsigned char) *s)))
140 ds_putc (target, *s++);
143 value = getenv (ds_c_str (target) + start);
144 ds_truncate (target, start);
145 ds_puts (target, value);
147 if (stop && *s == stop)
153 ds_putc (target, *s++);
163 /* Expands csh tilde notation from the path INPUT into a malloc()'d
166 fn_tilde_expand (const char *input)
168 struct string output = DS_INITIALIZER;
171 const char *home = NULL;
172 const char *remainder = NULL;
173 if (input[1] == '/' || input[1] == '\0')
175 home = fn_getenv ("HOME");
176 remainder = input + 1;
180 struct string user_name = DS_INITIALIZER;
183 ds_assign_buffer (&user_name, input + 1, strcspn (input + 1, "/"));
184 pwd = getpwnam (ds_c_str (&user_name));
185 if (pwd != NULL && pwd->pw_dir[0] != '\0')
188 remainder = input + 1 + ds_length (&user_name);
190 ds_destroy (&user_name);
195 ds_puts (&output, home);
196 if (*remainder != '\0')
197 ds_puts (&output, remainder);
200 if (ds_is_empty (&output))
201 ds_puts (&output, input);
202 return ds_c_str (&output);
206 fn_tilde_expand (const char *input)
208 return xstrdup (input);
212 /* Searches for a configuration file with name NAME in the path
213 given by PATH, which is tilde- and environment-interpolated.
214 Directories in PATH are delimited by ':'. Returns the
215 malloc'd full name of the first file found, or NULL if none is
218 If PREFIX is non-NULL, then it is prefixed to each file name;
219 i.e., it looks like PREFIX/PATH_COMPONENT/NAME. This is not
220 done with absolute directories in the path. */
222 fn_search_path (const char *base_name, const char *path_, const char *prefix)
225 struct string dir = DS_INITIALIZER;
226 struct string file = DS_INITIALIZER;
229 if (fn_is_absolute (base_name))
230 return fn_tilde_expand (base_name);
232 /* Interpolate environment variables. */
233 ds_create (&path, path_);
234 fn_interp_vars (&path, fn_getenv);
236 verbose_msg (2, _("searching for \"%s\" in path \"%s\""),
237 base_name, ds_c_str (&path));
238 while (ds_separate (&path, &dir, ":", &save_idx))
240 /* Do tilde expansion. */
241 if (ds_first (&dir) == '~')
243 char *tmp_str = fn_tilde_expand (ds_c_str (&dir));
244 ds_assign_c_str (&dir, tmp_str);
248 /* Construct file name. */
250 if (prefix != NULL && !fn_is_absolute (ds_c_str (&dir)))
252 ds_puts (&file, prefix);
253 ds_putc (&file, '/');
255 ds_puts (&file, ds_c_str (&dir));
256 if (ds_length (&dir) && ds_last (&file) != '/')
257 ds_putc (&file, '/');
258 ds_puts (&file, base_name);
260 /* Check whether file exists. */
261 if (fn_exists (ds_c_str (&file)))
263 verbose_msg (2, _("...found \"%s\""), ds_c_str (&file));
266 return ds_c_str (&file);
271 verbose_msg (2, _("...not found"));
278 /* fn_normalize(): This very OS-dependent routine canonicalizes
279 file name FN1. The file name should not need to be the name of an
280 existing file. Returns a malloc()'d copy of the canonical name.
281 This function must always succeed; if it needs to bail out then it
282 should return xstrdup(FN1). */
285 fn_normalize (const char *file_name)
288 char *fn1, *fn2, *dest;
291 if (fn_is_special (file_name))
292 return xstrdup (file_name);
294 fn1 = fn_tilde_expand (file_name);
296 /* Follow symbolic links. */
300 fn1 = fn_readlink (fn1);
309 maxlen = strlen (fn1) * 2;
312 dest = fn2 = xmalloc (maxlen + 1);
320 while (getcwd (dest, maxlen - (dest - fn2)) == NULL && errno == ERANGE)
323 dest = fn2 = xrealloc (fn2, maxlen + 1);
332 dest = strchr (fn2, '\0');
333 if (dest - fn2 >= maxlen)
335 int ofs = dest - fn2;
337 fn2 = xrealloc (fn2, maxlen + 1);
351 if (c == '/' || c == 0)
353 /* remove `./', `../' from directory */
354 if (dest[-1] == '.' && dest[-2] == '/')
356 else if (dest[-1] == '.' && dest[-2] == '.' && dest[-3] == '/')
361 while (dest[-1] != '/')
364 else if (dest[-1] != '/') /* remove extra slashes */
369 if (dest[-1] == '/' && dest > fn2 + 1)
374 return xrealloc (fn2, strlen (fn2) + 1);
382 if (dest - fn2 >= maxlen)
384 int ofs = dest - fn2;
386 fn2 = xrealloc (fn2, maxlen + 1);
393 #elif defined (__WIN32__)
395 fn_normalize (const char *fn1)
401 /* Don't change special file names. */
402 if (is_special_file_name (file_name))
403 return xstrdup (file_name);
405 /* First find the required buffer length. */
406 len = GetFullPathName (fn1, 0, NULL, NULL);
413 /* Then make a buffer that big. */
415 success = GetFullPathName (fn1, len, fn2, NULL);
416 if (success >= len || success == 0)
426 fn_normalize (const char *fn1)
428 char *fn2 = _fullpath (NULL, fn1, 0);
432 for (cp = fn2; *cp; cp++)
433 *cp = toupper ((unsigned char) (*cp));
436 return xstrdup (fn1);
440 fn_normalize (const char *fn1)
442 char *fn2 = xmalloc (1024);
444 fn2 = xrealloc (fn2, strlen (fn2) + 1);
447 #else /* not Lose32, Unix, or DJGPP */
449 fn_normalize (const char *fn)
453 #endif /* not Lose32, Unix, or DJGPP */
455 /* Returns the directory part of FILE_NAME, as a malloc()'d
458 fn_dir_name (const char *file_name)
464 len = strlen (file_name);
465 if (len == 1 && file_name[0] == '/')
467 else if (len && file_name[len - 1] == '/')
468 p = buf_find_reverse (file_name, len - 1, file_name + len - 1, 1);
470 p = strrchr (file_name, '/');
474 s = xmalloc (p - file_name + 1);
475 memcpy (s, file_name, p - file_name);
476 s[p - file_name] = 0;
481 /* Returns the extension part of FILE_NAME as a malloc()'d string.
482 If FILE_NAME does not have an extension, returns an empty
485 fn_extension (const char *file_name)
487 const char *extension = strrchr (file_name, '.');
488 if (extension == NULL)
490 return xstrdup (extension);
494 /* Returns the current working directory, as a malloc()'d string.
500 char *buffer = xmalloc (size);
504 char *value = getcwd (buffer, size);
510 buffer = xmalloc (size);
518 char *buffer = xmalloc (size);
530 /* Find out information about files. */
532 /* Returns nonzero iff NAME specifies an absolute file name. */
534 fn_is_absolute (const char *name)
538 || !strncmp (name, "./", 2)
539 || !strncmp (name, "../", 3)
542 #elif defined (__MSDOS__)
544 || !strncmp (name, ".\\", 2)
545 || !strncmp (name, "..\\", 3)
546 || (name[0] && name[1] == ':'))
553 /* Returns 1 if FILE_NAME is a virtual file that doesn't
554 really exist on disk, 0 if it's a real file name. */
556 fn_is_special (const char *file_name)
558 if (!strcmp (file_name, "-") || !strcmp (file_name, "stdin")
559 || !strcmp (file_name, "stdout") || !strcmp (file_name, "stderr")
561 || file_name[0] == '|'
562 || (*file_name && file_name[strlen (file_name) - 1] == '|')
570 /* Returns nonzero if file with name NAME exists. */
572 fn_exists (const char *name)
577 return stat (name, &temp) == 0;
579 FILE *f = fopen (name, "r");
587 /* Returns the symbolic link value for FILE_NAME as a dynamically
588 allocated buffer, or a null pointer on failure. */
590 fn_readlink (const char *file_name)
592 return xreadlink (file_name, 32);
595 /* Environment variables. */
597 /* Simulates $VER and $ARCH environment variables. */
599 fn_getenv (const char *s)
601 if (!strcmp (s, "VER"))
602 return fn_getenv_default ("STAT_VER", bare_version);
603 else if (!strcmp (s, "ARCH"))
604 return fn_getenv_default ("STAT_ARCH", host_system);
609 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
611 fn_getenv_default (const char *key, const char *def)
613 const char *value = getenv (key);
614 return value ? value : def;
617 /* Basic file handling. */
619 /* Used for giving an error message on a set_safer security
622 safety_violation (const char *fn)
624 msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
629 /* As a general comment on the following routines, a `sensible value'
630 for errno includes 0 if there is no associated system error. The
631 routines will only set errno to 0 if there is an error in a
632 callback that sets errno to 0; they themselves won't. */
634 /* File open routine that understands `-' as stdin/stdout and `|cmd'
635 as a pipe to command `cmd'. Returns resultant FILE on success,
636 NULL on failure. If NULL is returned then errno is set to a
639 fn_open (const char *fn, const char *mode)
641 assert (mode[0] == 'r' || mode[0] == 'w');
643 if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
645 else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
647 else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
653 if (get_safer_mode ())
654 return safety_violation (fn);
656 return popen (&fn[1], mode);
658 else if (*fn && fn[strlen (fn) - 1] == '|')
663 if (get_safer_mode ())
664 return safety_violation (fn);
666 s = local_alloc (strlen (fn));
667 memcpy (s, fn, strlen (fn) - 1);
668 s[strlen (fn) - 1] = 0;
679 FILE *f = fopen (fn, mode);
681 if (f && mode[0] == 'w')
682 setvbuf (f, NULL, _IOLBF, 0);
688 /* Counterpart to fn_open that closes file F with name FN; returns 0
689 on success, EOF on failure. If EOF is returned, errno is set to a
692 fn_close (const char *fn, FILE *f)
694 if (!strcmp (fn, "-"))
697 else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
708 /* A file's identity. */
711 dev_t device; /* Device number. */
712 ino_t inode; /* Inode number. */
715 /* Returns a pointer to a dynamically allocated structure whose
716 value can be used to tell whether two files are actually the
717 same file. Returns a null pointer if no information about the
718 file is available, perhaps because it does not exist. The
719 caller is responsible for freeing the structure with
720 fn_free_identity() when finished. */
721 struct file_identity *
722 fn_get_identity (const char *file_name)
726 if (stat (file_name, &s) == 0)
728 struct file_identity *identity = xmalloc (sizeof *identity);
729 identity->device = s.st_dev;
730 identity->inode = s.st_ino;
737 /* Frees IDENTITY obtained from fn_get_identity(). */
739 fn_free_identity (struct file_identity *identity)
744 /* Compares A and B, returning a strcmp()-type result. */
746 fn_compare_file_identities (const struct file_identity *a,
747 const struct file_identity *b)
751 if (a->device != b->device)
752 return a->device < b->device ? -1 : 1;
754 return a->inode < b->inode ? -1 : a->inode > b->inode;
757 /* A file's identity. */
760 char *normalized_file_name; /* File's normalized name. */
763 /* Returns a pointer to a dynamically allocated structure whose
764 value can be used to tell whether two files are actually the
765 same file. Returns a null pointer if no information about the
766 file is available, perhaps because it does not exist. The
767 caller is responsible for freeing the structure with
768 fn_free_identity() when finished. */
769 struct file_identity *
770 fn_get_identity (const char *file_name)
772 struct file_identity *identity = xmalloc (sizeof *identity);
773 identity->normalized_file_name = fn_normalize (file_name);
777 /* Frees IDENTITY obtained from fn_get_identity(). */
779 fn_free_identity (struct file_identity *identity)
781 if (identity != NULL)
783 free (identity->normalized_file_name);
788 /* Compares A and B, returning a strcmp()-type result. */
790 fn_compare_file_identities (const struct file_identity *a,
791 const struct file_identity *b)
793 return strcmp (a->normalized_file_name, b->normalized_file_name);
795 #endif /* not unix */