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>
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 #include <libpspp/debug-print.h>
40 /* PORTME: Everything in this file is system dependent. */
46 #include "stat-macros.h"
53 #include <win32/windows.h>
62 const char *config_path;
67 config_path = fn_getenv_default ("STAT_CONFIG_PATH", default_config_path);
70 /* Functions for performing operations on filenames. */
72 /* Substitutes $variables as defined by GETENV into INPUT and returns
73 a copy of the resultant string. Supports $var and ${var} syntaxes;
74 $$ substitutes as $. */
76 fn_interp_vars (const char *input, const char *(*getenv) (const char *))
80 if (NULL == strchr (input, '$'))
81 return xstrdup (input);
83 ds_init (&output, strlen (input));
89 return ds_c_str (&output);
96 ds_putc (&output, '$');
105 start = ds_length (&output);
112 else if (*input == '{')
120 while (*input && *input != stop
121 && (stop || isalpha ((unsigned char) *input)))
122 ds_putc (&output, *input++);
124 value = getenv (ds_c_str (&output) + start);
125 ds_truncate (&output, start);
126 ds_puts (&output, value);
128 if (stop && *input == stop)
133 ds_putc (&output, *input++);
138 /* Expands csh tilde notation from the path INPUT into a malloc()'d
141 fn_tilde_expand (const char *input)
144 struct string output;
146 if (NULL == strchr (input, '~'))
147 return xstrdup (input);
148 ds_init (&output, strlen (input));
152 for (ip = input; *ip; )
153 if (*ip != '~' || (ip != input && ip[-1] != PATH_DELIMITER))
154 ds_putc (&output, *ip++);
157 static const char stop_set[3] = {DIR_SEPARATOR, PATH_DELIMITER, 0};
162 cp = ip + strcspn (ip, stop_set);
169 strncpy (username, ip, cp - ip + 1);
171 pwd = getpwnam (username);
173 if (!pwd || !pwd->pw_dir)
174 ds_putc (&output, *ip++);
176 ds_puts (&output, pwd->pw_dir);
180 const char *home = fn_getenv ("HOME");
182 ds_putc (&output, *ip++);
184 ds_puts (&output, home);
190 return ds_c_str (&output);
194 fn_tilde_expand (const char *input)
196 return xstrdup (input);
200 /* Searches for a configuration file with name NAME in the path given
201 by PATH, which is tilde- and environment-interpolated. Directories
202 in PATH are delimited by PATH_DELIMITER, defined in <pref.h>.
203 Returns the malloc'd full name of the first file found, or NULL if
206 If PREPEND is non-NULL, then it is prepended to each filename;
207 i.e., it looks like PREPEND/PATH_COMPONENT/NAME. This is not done
208 with absolute directories in the path. */
209 #if defined (unix) || defined (__MSDOS__) || defined (__WIN32__)
211 fn_search_path (const char *basename, const char *path, const char *prepend)
214 struct string filename;
217 if (fn_absolute_p (basename))
218 return fn_tilde_expand (basename);
221 char *temp = fn_interp_vars (path, fn_getenv);
222 bp = subst_path = fn_tilde_expand (temp);
226 msg (VM (4), _("Searching for `%s'..."), basename);
227 ds_init (&filename, 64);
234 msg (VM (4), _("Search unsuccessful!"));
235 ds_destroy (&filename);
240 for (ep = bp; *ep && *ep != PATH_DELIMITER; ep++)
243 /* Paste together PREPEND/PATH/BASENAME. */
244 ds_clear (&filename);
245 if (prepend && !fn_absolute_p (bp))
247 ds_puts (&filename, prepend);
248 ds_putc (&filename, DIR_SEPARATOR);
250 ds_concat (&filename, bp, ep - bp);
252 && ds_c_str (&filename)[ds_length (&filename) - 1] != DIR_SEPARATOR)
253 ds_putc (&filename, DIR_SEPARATOR);
254 ds_puts (&filename, basename);
256 msg (VM (5), " - %s", ds_c_str (&filename));
257 if (fn_exists_p (ds_c_str (&filename)))
259 msg (VM (4), _("Found `%s'."), ds_c_str (&filename));
261 return ds_c_str (&filename);
266 msg (VM (4), _("Search unsuccessful!"));
268 ds_destroy (&filename);
274 #else /* not unix, msdog, lose32 */
276 fn_search_path (const char *basename, const char *path, const char *prepend)
278 size_t size = strlen (path) + 1 + strlen (basename) + 1;
283 size += strlen (prepend) + 1;
284 string = xmalloc (size);
289 cp = stpcpy (cp, prepend);
290 *cp++ = DIR_SEPARATOR;
292 cp = stpcpy (cp, path);
293 *cp++ = DIR_SEPARATOR;
294 strcpy (cp, basename);
298 #endif /* not unix, msdog, lose32 */
300 /* Prepends directory DIR to filename FILE and returns a malloc()'d
303 fn_prepend_dir (const char *file, const char *dir)
308 if (fn_absolute_p (file))
309 return xstrdup (file);
311 temp = xmalloc (strlen (file) + 1 + strlen (dir) + 1);
312 cp = stpcpy (temp, dir);
313 if (cp != temp && cp[-1] != DIR_SEPARATOR)
314 *cp++ = DIR_SEPARATOR;
315 cp = stpcpy (cp, file);
320 /* fn_normalize(): This very OS-dependent routine canonicalizes
321 filename FN1. The filename should not need to be the name of an
322 existing file. Returns a malloc()'d copy of the canonical name.
323 This function must always succeed; if it needs to bail out then it
324 should return xstrdup(FN1). */
327 fn_normalize (const char *filename)
330 char *fn1, *fn2, *dest;
333 if (fn_special_p (filename))
334 return xstrdup (filename);
336 fn1 = fn_tilde_expand (filename);
338 /* Follow symbolic links. */
342 fn1 = fn_readlink (fn1);
351 maxlen = strlen (fn1) * 2;
354 dest = fn2 = xmalloc (maxlen + 1);
357 if (*src == DIR_SEPARATOR)
362 while (getcwd (dest, maxlen - (dest - fn2)) == NULL && errno == ERANGE)
365 dest = fn2 = xrealloc (fn2, maxlen + 1);
374 dest = strchr (fn2, '\0');
375 if (dest - fn2 >= maxlen)
377 int ofs = dest - fn2;
379 fn2 = xrealloc (fn2, maxlen + 1);
382 if (dest[-1] != DIR_SEPARATOR)
383 *dest++ = DIR_SEPARATOR;
393 if (c == DIR_SEPARATOR || c == 0)
395 /* remove `./', `../' from directory */
396 if (dest[-1] == '.' && dest[-2] == DIR_SEPARATOR)
398 else if (dest[-1] == '.' && dest[-2] == '.' && dest[-3] == DIR_SEPARATOR)
403 while (dest[-1] != DIR_SEPARATOR)
406 else if (dest[-1] != DIR_SEPARATOR) /* remove extra slashes */
411 if (dest[-1] == DIR_SEPARATOR && dest > fn2 + 1)
416 return xrealloc (fn2, strlen (fn2) + 1);
424 if (dest - fn2 >= maxlen)
426 int ofs = dest - fn2;
428 fn2 = xrealloc (fn2, maxlen + 1);
435 #elif defined (__WIN32__)
437 fn_normalize (const char *fn1)
443 /* Don't change special filenames. */
444 if (is_special_filename (filename))
445 return xstrdup (filename);
447 /* First find the required buffer length. */
448 len = GetFullPathName (fn1, 0, NULL, NULL);
455 /* Then make a buffer that big. */
457 success = GetFullPathName (fn1, len, fn2, NULL);
458 if (success >= len || success == 0)
468 fn_normalize (const char *fn1)
470 char *fn2 = _fullpath (NULL, fn1, 0);
474 for (cp = fn2; *cp; cp++)
475 *cp = toupper ((unsigned char) (*cp));
478 return xstrdup (fn1);
482 fn_normalize (const char *fn1)
484 char *fn2 = xmalloc (1024);
486 fn2 = xrealloc (fn2, strlen (fn2) + 1);
489 #else /* not Lose32, Unix, or DJGPP */
491 fn_normalize (const char *fn)
495 #endif /* not Lose32, Unix, or DJGPP */
497 /* Returns the directory part of FILENAME, as a malloc()'d
500 fn_dirname (const char *filename)
506 len = strlen (filename);
507 if (len == 1 && filename[0] == '/')
509 else if (len && filename[len - 1] == DIR_SEPARATOR)
510 p = buf_find_reverse (filename, len - 1, filename + len - 1, 1);
512 p = strrchr (filename, DIR_SEPARATOR);
516 s = xmalloc (p - filename + 1);
517 memcpy (s, filename, p - filename);
523 /* Returns the basename part of FILENAME as a malloc()'d string. */
526 fn_basename (const char *filename)
528 /* Not used, not implemented. */
533 /* Returns the extension part of FILENAME as a malloc()'d string.
534 If FILENAME does not have an extension, returns an empty
537 fn_extension (const char *filename)
539 const char *extension = strrchr (filename, '.');
540 if (extension == NULL)
542 return xstrdup (extension);
546 /* Returns the current working directory, as a malloc()'d string.
552 char *buffer = xmalloc (size);
556 char *value = getcwd (buffer, size);
562 buffer = xmalloc (size);
570 char *buffer = xmalloc (size);
582 /* Find out information about files. */
584 /* Returns nonzero iff NAME specifies an absolute filename. */
586 fn_absolute_p (const char *name)
590 || !strncmp (name, "./", 2)
591 || !strncmp (name, "../", 3)
594 #elif defined (__MSDOS__)
596 || !strncmp (name, ".\\", 2)
597 || !strncmp (name, "..\\", 3)
598 || (name[0] && name[1] == ':'))
605 /* Returns 1 if the filename specified is a virtual file that doesn't
606 really exist on disk, 0 if it's a real filename. */
608 fn_special_p (const char *filename)
610 if (!strcmp (filename, "-") || !strcmp (filename, "stdin")
611 || !strcmp (filename, "stdout") || !strcmp (filename, "stderr")
613 || filename[0] == '|'
614 || (*filename && filename[strlen (filename) - 1] == '|')
622 /* Returns nonzero if file with name NAME exists. */
624 fn_exists_p (const char *name)
629 return stat (name, &temp) == 0;
631 FILE *f = fopen (name, "r");
639 /* Returns the symbolic link value for FILENAME as a dynamically
640 allocated buffer, or a null pointer on failure. */
642 fn_readlink (const char *filename)
644 return xreadlink (filename, 32);
647 /* Environment variables. */
649 /* Simulates $VER and $ARCH environment variables. */
651 fn_getenv (const char *s)
653 if (!strcmp (s, "VER"))
654 return fn_getenv_default ("STAT_VER", bare_version);
655 else if (!strcmp (s, "ARCH"))
656 return fn_getenv_default ("STAT_ARCH", host_system);
661 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
663 fn_getenv_default (const char *key, const char *def)
665 const char *value = getenv (key);
666 return value ? value : def;
669 /* Basic file handling. */
671 /* Used for giving an error message on a set_safer security
674 safety_violation (const char *fn)
676 msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
681 /* As a general comment on the following routines, a `sensible value'
682 for errno includes 0 if there is no associated system error. The
683 routines will only set errno to 0 if there is an error in a
684 callback that sets errno to 0; they themselves won't. */
686 /* File open routine that understands `-' as stdin/stdout and `|cmd'
687 as a pipe to command `cmd'. Returns resultant FILE on success,
688 NULL on failure. If NULL is returned then errno is set to a
691 fn_open (const char *fn, const char *mode)
693 assert (mode[0] == 'r' || mode[0] == 'w');
695 if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
697 else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
699 else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
705 if (get_safer_mode ())
706 return safety_violation (fn);
708 return popen (&fn[1], mode);
710 else if (*fn && fn[strlen (fn) - 1] == '|')
715 if (get_safer_mode ())
716 return safety_violation (fn);
718 s = local_alloc (strlen (fn));
719 memcpy (s, fn, strlen (fn) - 1);
720 s[strlen (fn) - 1] = 0;
731 FILE *f = fopen (fn, mode);
733 if (f && mode[0] == 'w')
734 setvbuf (f, NULL, _IOLBF, 0);
740 /* Counterpart to fn_open that closes file F with name FN; returns 0
741 on success, EOF on failure. If EOF is returned, errno is set to a
744 fn_close (const char *fn, FILE *f)
746 if (!strcmp (fn, "-"))
749 else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
759 /* More extensive file handling. */
761 /* File open routine that extends fn_open(). Opens or reopens a
762 file according to the contents of file_ext F. Returns nonzero on
763 success. If 0 is returned, errno is set to a sensible value. */
765 fn_open_ext (struct file_ext *f)
769 p = strstr (f->filename, "%d");
772 char *s = local_alloc (strlen (f->filename)
773 + INT_STRLEN_BOUND (int) - 1);
776 memcpy (s, f->filename, p - f->filename);
777 cp = spprintf (&s[p - f->filename], "%d", *f->sequence_no);
785 if (f->preclose (f) == 0)
788 if (EOF == fn_close (f->filename, f->file) || error)
802 f->file = fn_open (s, f->mode);
805 if (f->file && f->postopen)
806 if (f->postopen (f) == 0)
809 fn_close (f->filename, f->file);
815 return (f->file != NULL);
821 f->file = fn_open (f->filename, f->mode);
823 if (f->file && f->postopen)
824 if (f->postopen (f) == 0)
827 fn_close (f->filename, f->file);
833 return (f->file != NULL);
837 /* Properly closes the file associated with file_ext F, if any.
838 Return nonzero on success. If zero is returned, errno is set to a
841 fn_close_ext (struct file_ext *f)
848 if (f->preclose (f) == 0)
851 if (EOF == fn_close (f->filename, f->file) || error)
867 /* A file's identity. */
870 dev_t device; /* Device number. */
871 ino_t inode; /* Inode number. */
874 /* Returns a pointer to a dynamically allocated structure whose
875 value can be used to tell whether two files are actually the
876 same file. Returns a null pointer if no information about the
877 file is available, perhaps because it does not exist. The
878 caller is responsible for freeing the structure with
879 fn_free_identity() when finished. */
880 struct file_identity *
881 fn_get_identity (const char *filename)
885 if (stat (filename, &s) == 0)
887 struct file_identity *identity = xmalloc (sizeof *identity);
888 identity->device = s.st_dev;
889 identity->inode = s.st_ino;
896 /* Frees IDENTITY obtained from fn_get_identity(). */
898 fn_free_identity (struct file_identity *identity)
903 /* Compares A and B, returning a strcmp()-type result. */
905 fn_compare_file_identities (const struct file_identity *a,
906 const struct file_identity *b)
910 if (a->device != b->device)
911 return a->device < b->device ? -1 : 1;
913 return a->inode < b->inode ? -1 : a->inode > b->inode;
916 /* A file's identity. */
919 char *normalized_filename; /* File's normalized name. */
922 /* Returns a pointer to a dynamically allocated structure whose
923 value can be used to tell whether two files are actually the
924 same file. Returns a null pointer if no information about the
925 file is available, perhaps because it does not exist. The
926 caller is responsible for freeing the structure with
927 fn_free_identity() when finished. */
928 struct file_identity *
929 fn_get_identity (const char *filename)
931 struct file_identity *identity = xmalloc (sizeof *identity);
932 identity->normalized_filename = fn_normalize (filename);
936 /* Frees IDENTITY obtained from fn_get_identity(). */
938 fn_free_identity (struct file_identity *identity)
940 if (identity != NULL)
942 free (identity->normalized_filename);
947 /* Compares A and B, returning a strcmp()-type result. */
949 fn_compare_file_identities (const struct file_identity *a,
950 const struct file_identity *b)
952 return strcmp (a->normalized_filename, b->normalized_filename);
954 #endif /* not unix */