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')
149 home = xstrdup (pwd->pw_dir);
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 fn_search_path (const char *base_name, const char *path_)
183 struct substring dir_;
184 struct string file = DS_EMPTY_INITIALIZER;
187 if (fn_is_absolute (base_name))
188 return fn_tilde_expand (base_name);
190 /* Interpolate environment variables. */
191 ds_init_cstr (&path, path_);
192 fn_interp_vars (ds_ss (&path), fn_getenv, &path);
194 verbose_msg (2, _("searching for \"%s\" in path \"%s\""),
195 base_name, ds_cstr (&path));
196 while (ds_separate (&path, ss_cstr (":"), &save_idx, &dir_))
200 /* Do tilde expansion. */
201 ds_init_substring (&dir, dir_);
202 if (ds_first (&dir) == '~')
204 char *tmp_str = fn_tilde_expand (ds_cstr (&dir));
205 ds_assign_cstr (&dir, tmp_str);
209 /* Construct file name. */
211 ds_put_cstr (&file, ds_cstr (&dir));
212 if (!ds_is_empty (&file) && ds_last (&file) != '/')
213 ds_put_char (&file, '/');
214 ds_put_cstr (&file, base_name);
217 /* Check whether file exists. */
218 if (fn_exists (ds_cstr (&file)))
220 verbose_msg (2, _("...found \"%s\""), ds_cstr (&file));
222 return ds_cstr (&file);
227 verbose_msg (2, _("...not found"));
233 /* fn_normalize(): This very OS-dependent routine canonicalizes
234 file name FN1. The file name should not need to be the name of an
235 existing file. Returns a malloc()'d copy of the canonical name.
236 This function must always succeed; if it needs to bail out then it
237 should return xstrdup(FN1). */
240 fn_normalize (const char *file_name)
243 char *fn1, *fn2, *dest;
246 if (fn_is_special (file_name))
247 return xstrdup (file_name);
249 fn1 = fn_tilde_expand (file_name);
251 /* Follow symbolic links. */
255 fn1 = fn_readlink (fn1);
264 maxlen = strlen (fn1) * 2;
267 dest = fn2 = xmalloc (maxlen + 1);
275 while (getcwd (dest, maxlen - (dest - fn2)) == NULL && errno == ERANGE)
278 dest = fn2 = xrealloc (fn2, maxlen + 1);
287 dest = strchr (fn2, '\0');
288 if (dest - fn2 >= maxlen)
290 int ofs = dest - fn2;
292 fn2 = xrealloc (fn2, maxlen + 1);
306 if (c == '/' || c == 0)
308 /* remove `./', `../' from directory */
309 if (dest[-1] == '.' && dest[-2] == '/')
311 else if (dest[-1] == '.' && dest[-2] == '.' && dest[-3] == '/')
316 while (dest[-1] != '/')
319 else if (dest[-1] != '/') /* remove extra slashes */
324 if (dest[-1] == '/' && dest > fn2 + 1)
329 return xrealloc (fn2, strlen (fn2) + 1);
337 if (dest - fn2 >= maxlen)
339 int ofs = dest - fn2;
341 fn2 = xrealloc (fn2, maxlen + 1);
348 #elif defined (__WIN32__)
350 fn_normalize (const char *fn1)
356 /* Don't change special file names. */
357 if (is_special_file_name (file_name))
358 return xstrdup (file_name);
360 /* First find the required buffer length. */
361 len = GetFullPathName (fn1, 0, NULL, NULL);
368 /* Then make a buffer that big. */
370 success = GetFullPathName (fn1, len, fn2, NULL);
371 if (success >= len || success == 0)
381 fn_normalize (const char *fn1)
383 char *fn2 = _fullpath (NULL, fn1, 0);
387 for (cp = fn2; *cp; cp++)
388 *cp = toupper ((unsigned char) (*cp));
391 return xstrdup (fn1);
395 fn_normalize (const char *fn1)
397 char *fn2 = xmalloc (1024);
399 fn2 = xrealloc (fn2, strlen (fn2) + 1);
402 #else /* not Lose32, Unix, or DJGPP */
404 fn_normalize (const char *fn)
408 #endif /* not Lose32, Unix, or DJGPP */
410 /* Returns the directory part of FILE_NAME, as a malloc()'d
413 fn_dir_name (const char *file_name)
419 len = strlen (file_name);
420 if (len == 1 && file_name[0] == '/')
422 else if (len && file_name[len - 1] == '/')
423 p = buf_find_reverse (file_name, len - 1, file_name + len - 1, 1);
425 p = strrchr (file_name, '/');
429 s = xmalloc (p - file_name + 1);
430 memcpy (s, file_name, p - file_name);
431 s[p - file_name] = 0;
436 /* Returns the extension part of FILE_NAME as a malloc()'d string.
437 If FILE_NAME does not have an extension, returns an empty
440 fn_extension (const char *file_name)
442 const char *extension = strrchr (file_name, '.');
443 if (extension == NULL)
445 return xstrdup (extension);
449 /* Returns the current working directory, as a malloc()'d string.
455 char *buffer = xmalloc (size);
459 char *value = getcwd (buffer, size);
465 buffer = xmalloc (size);
473 char *buffer = xmalloc (size);
485 /* Find out information about files. */
487 /* Returns true iff NAME specifies an absolute file name. */
489 fn_is_absolute (const char *name)
493 || !strncmp (name, "./", 2)
494 || !strncmp (name, "../", 3)
497 #elif defined (__MSDOS__)
499 || !strncmp (name, ".\\", 2)
500 || !strncmp (name, "..\\", 3)
501 || (name[0] && name[1] == ':'))
508 /* Returns true if FILE_NAME is a virtual file that doesn't
509 really exist on disk, false if it's a real file name. */
511 fn_is_special (const char *file_name)
513 if (!strcmp (file_name, "-") || !strcmp (file_name, "stdin")
514 || !strcmp (file_name, "stdout") || !strcmp (file_name, "stderr")
516 || file_name[0] == '|'
517 || (*file_name && file_name[strlen (file_name) - 1] == '|')
525 /* Returns true if file with name NAME exists. */
527 fn_exists (const char *name)
532 return stat (name, &temp) == 0;
534 FILE *f = fopen (name, "r");
542 /* Returns the symbolic link value for FILE_NAME as a dynamically
543 allocated buffer, or a null pointer on failure. */
545 fn_readlink (const char *file_name)
547 return xreadlink (file_name, 32);
550 /* Environment variables. */
552 /* Simulates $VER and $ARCH environment variables. */
554 fn_getenv (const char *s)
556 if (!strcmp (s, "VER"))
557 return fn_getenv_default ("STAT_VER", bare_version);
558 else if (!strcmp (s, "ARCH"))
559 return fn_getenv_default ("STAT_ARCH", host_system);
564 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
566 fn_getenv_default (const char *key, const char *def)
568 const char *value = getenv (key);
569 return value ? value : def;
572 /* Basic file handling. */
574 /* Used for giving an error message on a set_safer security
577 safety_violation (const char *fn)
579 msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
584 /* As a general comment on the following routines, a `sensible value'
585 for errno includes 0 if there is no associated system error. The
586 routines will only set errno to 0 if there is an error in a
587 callback that sets errno to 0; they themselves won't. */
589 /* File open routine that understands `-' as stdin/stdout and `|cmd'
590 as a pipe to command `cmd'. Returns resultant FILE on success,
591 NULL on failure. If NULL is returned then errno is set to a
594 fn_open (const char *fn, const char *mode)
596 assert (mode[0] == 'r' || mode[0] == 'w');
598 if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
600 else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
602 else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
608 if (get_safer_mode ())
609 return safety_violation (fn);
611 return popen (&fn[1], mode);
613 else if (*fn && fn[strlen (fn) - 1] == '|')
618 if (get_safer_mode ())
619 return safety_violation (fn);
621 s = local_alloc (strlen (fn));
622 memcpy (s, fn, strlen (fn) - 1);
623 s[strlen (fn) - 1] = 0;
634 FILE *f = fopen (fn, mode);
636 if (f && mode[0] == 'w')
637 setvbuf (f, NULL, _IOLBF, 0);
643 /* Counterpart to fn_open that closes file F with name FN; returns 0
644 on success, EOF on failure. If EOF is returned, errno is set to a
647 fn_close (const char *fn, FILE *f)
649 if (!strcmp (fn, "-"))
652 else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
663 /* A file's identity. */
666 dev_t device; /* Device number. */
667 ino_t inode; /* Inode number. */
670 /* Returns a pointer to a dynamically allocated structure whose
671 value can be used to tell whether two files are actually the
672 same file. Returns a null pointer if no information about the
673 file is available, perhaps because it does not exist. The
674 caller is responsible for freeing the structure with
675 fn_free_identity() when finished. */
676 struct file_identity *
677 fn_get_identity (const char *file_name)
681 if (stat (file_name, &s) == 0)
683 struct file_identity *identity = xmalloc (sizeof *identity);
684 identity->device = s.st_dev;
685 identity->inode = s.st_ino;
692 /* Frees IDENTITY obtained from fn_get_identity(). */
694 fn_free_identity (struct file_identity *identity)
699 /* Compares A and B, returning a strcmp()-type result. */
701 fn_compare_file_identities (const struct file_identity *a,
702 const struct file_identity *b)
706 if (a->device != b->device)
707 return a->device < b->device ? -1 : 1;
709 return a->inode < b->inode ? -1 : a->inode > b->inode;
712 /* A file's identity. */
715 char *normalized_file_name; /* File's normalized name. */
718 /* Returns a pointer to a dynamically allocated structure whose
719 value can be used to tell whether two files are actually the
720 same file. Returns a null pointer if no information about the
721 file is available, perhaps because it does not exist. The
722 caller is responsible for freeing the structure with
723 fn_free_identity() when finished. */
724 struct file_identity *
725 fn_get_identity (const char *file_name)
727 struct file_identity *identity = xmalloc (sizeof *identity);
728 identity->normalized_file_name = fn_normalize (file_name);
732 /* Frees IDENTITY obtained from fn_get_identity(). */
734 fn_free_identity (struct file_identity *identity)
736 if (identity != NULL)
738 free (identity->normalized_file_name);
743 /* Compares A and B, returning a strcmp()-type result. */
745 fn_compare_file_identities (const struct file_identity *a,
746 const struct file_identity *b)
748 return strcmp (a->normalized_file_name, b->normalized_file_name);
750 #endif /* not unix */