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 /* 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 filenames. */
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)
164 struct string output;
166 if (NULL == strchr (input, '~'))
167 return xstrdup (input);
168 ds_init (&output, strlen (input));
172 for (ip = input; *ip; )
173 if (*ip != '~' || (ip != input && ip[-1] != PATH_DELIMITER))
174 ds_putc (&output, *ip++);
177 static const char stop_set[3] = {DIR_SEPARATOR, PATH_DELIMITER, 0};
182 cp = ip + strcspn (ip, stop_set);
189 strncpy (username, ip, cp - ip + 1);
191 pwd = getpwnam (username);
193 if (!pwd || !pwd->pw_dir)
194 ds_putc (&output, *ip++);
196 ds_puts (&output, pwd->pw_dir);
200 const char *home = fn_getenv ("HOME");
202 ds_putc (&output, *ip++);
204 ds_puts (&output, home);
210 return ds_c_str (&output);
214 fn_tilde_expand (const char *input)
216 return xstrdup (input);
220 /* Searches for a configuration file with name NAME in the path given
221 by PATH, which is tilde- and environment-interpolated. Directories
222 in PATH are delimited by PATH_DELIMITER, defined in <pref.h>.
223 Returns the malloc'd full name of the first file found, or NULL if
226 If PREPEND is non-NULL, then it is prepended to each filename;
227 i.e., it looks like PREPEND/PATH_COMPONENT/NAME. This is not done
228 with absolute directories in the path. */
229 #if defined (unix) || defined (__MSDOS__) || defined (__WIN32__)
231 fn_search_path (const char *basename, const char *path, const char *prepend)
234 struct string filename;
237 if (fn_absolute_p (basename))
238 return fn_tilde_expand (basename);
242 ds_create(&temp, path);
244 fn_interp_vars(&temp, fn_getenv);
246 bp = subst_path = fn_tilde_expand (ds_c_str(&temp));
251 msg (VM (4), _("Searching for `%s'..."), basename);
252 ds_init (&filename, 64);
259 msg (VM (4), _("Search unsuccessful!"));
260 ds_destroy (&filename);
265 for (ep = bp; *ep && *ep != PATH_DELIMITER; ep++)
268 /* Paste together PREPEND/PATH/BASENAME. */
269 ds_clear (&filename);
270 if (prepend && !fn_absolute_p (bp))
272 ds_puts (&filename, prepend);
273 ds_putc (&filename, DIR_SEPARATOR);
275 ds_concat (&filename, bp, ep - bp);
277 && ds_c_str (&filename)[ds_length (&filename) - 1] != DIR_SEPARATOR)
278 ds_putc (&filename, DIR_SEPARATOR);
279 ds_puts (&filename, basename);
281 msg (VM (5), " - %s", ds_c_str (&filename));
282 if (fn_exists_p (ds_c_str (&filename)))
284 msg (VM (4), _("Found `%s'."), ds_c_str (&filename));
286 return ds_c_str (&filename);
291 msg (VM (4), _("Search unsuccessful!"));
293 ds_destroy (&filename);
299 #else /* not unix, msdog, lose32 */
301 fn_search_path (const char *basename, const char *path, const char *prepend)
303 size_t size = strlen (path) + 1 + strlen (basename) + 1;
308 size += strlen (prepend) + 1;
309 string = xmalloc (size);
314 cp = stpcpy (cp, prepend);
315 *cp++ = DIR_SEPARATOR;
317 cp = stpcpy (cp, path);
318 *cp++ = DIR_SEPARATOR;
319 strcpy (cp, basename);
323 #endif /* not unix, msdog, lose32 */
325 /* Prepends directory DIR to filename FILE and returns a malloc()'d
328 fn_prepend_dir (const char *file, const char *dir)
333 if (fn_absolute_p (file))
334 return xstrdup (file);
336 temp = xmalloc (strlen (file) + 1 + strlen (dir) + 1);
337 cp = stpcpy (temp, dir);
338 if (cp != temp && cp[-1] != DIR_SEPARATOR)
339 *cp++ = DIR_SEPARATOR;
340 cp = stpcpy (cp, file);
345 /* fn_normalize(): This very OS-dependent routine canonicalizes
346 filename FN1. The filename should not need to be the name of an
347 existing file. Returns a malloc()'d copy of the canonical name.
348 This function must always succeed; if it needs to bail out then it
349 should return xstrdup(FN1). */
352 fn_normalize (const char *filename)
355 char *fn1, *fn2, *dest;
358 if (fn_special_p (filename))
359 return xstrdup (filename);
361 fn1 = fn_tilde_expand (filename);
363 /* Follow symbolic links. */
367 fn1 = fn_readlink (fn1);
376 maxlen = strlen (fn1) * 2;
379 dest = fn2 = xmalloc (maxlen + 1);
382 if (*src == DIR_SEPARATOR)
387 while (getcwd (dest, maxlen - (dest - fn2)) == NULL && errno == ERANGE)
390 dest = fn2 = xrealloc (fn2, maxlen + 1);
399 dest = strchr (fn2, '\0');
400 if (dest - fn2 >= maxlen)
402 int ofs = dest - fn2;
404 fn2 = xrealloc (fn2, maxlen + 1);
407 if (dest[-1] != DIR_SEPARATOR)
408 *dest++ = DIR_SEPARATOR;
418 if (c == DIR_SEPARATOR || c == 0)
420 /* remove `./', `../' from directory */
421 if (dest[-1] == '.' && dest[-2] == DIR_SEPARATOR)
423 else if (dest[-1] == '.' && dest[-2] == '.' && dest[-3] == DIR_SEPARATOR)
428 while (dest[-1] != DIR_SEPARATOR)
431 else if (dest[-1] != DIR_SEPARATOR) /* remove extra slashes */
436 if (dest[-1] == DIR_SEPARATOR && dest > fn2 + 1)
441 return xrealloc (fn2, strlen (fn2) + 1);
449 if (dest - fn2 >= maxlen)
451 int ofs = dest - fn2;
453 fn2 = xrealloc (fn2, maxlen + 1);
460 #elif defined (__WIN32__)
462 fn_normalize (const char *fn1)
468 /* Don't change special filenames. */
469 if (is_special_filename (filename))
470 return xstrdup (filename);
472 /* First find the required buffer length. */
473 len = GetFullPathName (fn1, 0, NULL, NULL);
480 /* Then make a buffer that big. */
482 success = GetFullPathName (fn1, len, fn2, NULL);
483 if (success >= len || success == 0)
493 fn_normalize (const char *fn1)
495 char *fn2 = _fullpath (NULL, fn1, 0);
499 for (cp = fn2; *cp; cp++)
500 *cp = toupper ((unsigned char) (*cp));
503 return xstrdup (fn1);
507 fn_normalize (const char *fn1)
509 char *fn2 = xmalloc (1024);
511 fn2 = xrealloc (fn2, strlen (fn2) + 1);
514 #else /* not Lose32, Unix, or DJGPP */
516 fn_normalize (const char *fn)
520 #endif /* not Lose32, Unix, or DJGPP */
522 /* Returns the directory part of FILENAME, as a malloc()'d
525 fn_dirname (const char *filename)
531 len = strlen (filename);
532 if (len == 1 && filename[0] == '/')
534 else if (len && filename[len - 1] == DIR_SEPARATOR)
535 p = buf_find_reverse (filename, len - 1, filename + len - 1, 1);
537 p = strrchr (filename, DIR_SEPARATOR);
541 s = xmalloc (p - filename + 1);
542 memcpy (s, filename, p - filename);
548 /* Returns the basename part of FILENAME as a malloc()'d string. */
551 fn_basename (const char *filename)
553 /* Not used, not implemented. */
558 /* Returns the extension part of FILENAME as a malloc()'d string.
559 If FILENAME does not have an extension, returns an empty
562 fn_extension (const char *filename)
564 const char *extension = strrchr (filename, '.');
565 if (extension == NULL)
567 return xstrdup (extension);
571 /* Returns the current working directory, as a malloc()'d string.
577 char *buffer = xmalloc (size);
581 char *value = getcwd (buffer, size);
587 buffer = xmalloc (size);
595 char *buffer = xmalloc (size);
607 /* Find out information about files. */
609 /* Returns nonzero iff NAME specifies an absolute filename. */
611 fn_absolute_p (const char *name)
615 || !strncmp (name, "./", 2)
616 || !strncmp (name, "../", 3)
619 #elif defined (__MSDOS__)
621 || !strncmp (name, ".\\", 2)
622 || !strncmp (name, "..\\", 3)
623 || (name[0] && name[1] == ':'))
630 /* Returns 1 if the filename specified is a virtual file that doesn't
631 really exist on disk, 0 if it's a real filename. */
633 fn_special_p (const char *filename)
635 if (!strcmp (filename, "-") || !strcmp (filename, "stdin")
636 || !strcmp (filename, "stdout") || !strcmp (filename, "stderr")
638 || filename[0] == '|'
639 || (*filename && filename[strlen (filename) - 1] == '|')
647 /* Returns nonzero if file with name NAME exists. */
649 fn_exists_p (const char *name)
654 return stat (name, &temp) == 0;
656 FILE *f = fopen (name, "r");
664 /* Returns the symbolic link value for FILENAME as a dynamically
665 allocated buffer, or a null pointer on failure. */
667 fn_readlink (const char *filename)
669 return xreadlink (filename, 32);
672 /* Environment variables. */
674 /* Simulates $VER and $ARCH environment variables. */
676 fn_getenv (const char *s)
678 if (!strcmp (s, "VER"))
679 return fn_getenv_default ("STAT_VER", bare_version);
680 else if (!strcmp (s, "ARCH"))
681 return fn_getenv_default ("STAT_ARCH", host_system);
686 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
688 fn_getenv_default (const char *key, const char *def)
690 const char *value = getenv (key);
691 return value ? value : def;
694 /* Basic file handling. */
696 /* Used for giving an error message on a set_safer security
699 safety_violation (const char *fn)
701 msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
706 /* As a general comment on the following routines, a `sensible value'
707 for errno includes 0 if there is no associated system error. The
708 routines will only set errno to 0 if there is an error in a
709 callback that sets errno to 0; they themselves won't. */
711 /* File open routine that understands `-' as stdin/stdout and `|cmd'
712 as a pipe to command `cmd'. Returns resultant FILE on success,
713 NULL on failure. If NULL is returned then errno is set to a
716 fn_open (const char *fn, const char *mode)
718 assert (mode[0] == 'r' || mode[0] == 'w');
720 if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
722 else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
724 else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
730 if (get_safer_mode ())
731 return safety_violation (fn);
733 return popen (&fn[1], mode);
735 else if (*fn && fn[strlen (fn) - 1] == '|')
740 if (get_safer_mode ())
741 return safety_violation (fn);
743 s = local_alloc (strlen (fn));
744 memcpy (s, fn, strlen (fn) - 1);
745 s[strlen (fn) - 1] = 0;
756 FILE *f = fopen (fn, mode);
758 if (f && mode[0] == 'w')
759 setvbuf (f, NULL, _IOLBF, 0);
765 /* Counterpart to fn_open that closes file F with name FN; returns 0
766 on success, EOF on failure. If EOF is returned, errno is set to a
769 fn_close (const char *fn, FILE *f)
771 if (!strcmp (fn, "-"))
774 else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
785 /* A file's identity. */
788 dev_t device; /* Device number. */
789 ino_t inode; /* Inode number. */
792 /* Returns a pointer to a dynamically allocated structure whose
793 value can be used to tell whether two files are actually the
794 same file. Returns a null pointer if no information about the
795 file is available, perhaps because it does not exist. The
796 caller is responsible for freeing the structure with
797 fn_free_identity() when finished. */
798 struct file_identity *
799 fn_get_identity (const char *filename)
803 if (stat (filename, &s) == 0)
805 struct file_identity *identity = xmalloc (sizeof *identity);
806 identity->device = s.st_dev;
807 identity->inode = s.st_ino;
814 /* Frees IDENTITY obtained from fn_get_identity(). */
816 fn_free_identity (struct file_identity *identity)
821 /* Compares A and B, returning a strcmp()-type result. */
823 fn_compare_file_identities (const struct file_identity *a,
824 const struct file_identity *b)
828 if (a->device != b->device)
829 return a->device < b->device ? -1 : 1;
831 return a->inode < b->inode ? -1 : a->inode > b->inode;
834 /* A file's identity. */
837 char *normalized_filename; /* File's normalized name. */
840 /* Returns a pointer to a dynamically allocated structure whose
841 value can be used to tell whether two files are actually the
842 same file. Returns a null pointer if no information about the
843 file is available, perhaps because it does not exist. The
844 caller is responsible for freeing the structure with
845 fn_free_identity() when finished. */
846 struct file_identity *
847 fn_get_identity (const char *filename)
849 struct file_identity *identity = xmalloc (sizeof *identity);
850 identity->normalized_filename = fn_normalize (filename);
854 /* Frees IDENTITY obtained from fn_get_identity(). */
856 fn_free_identity (struct file_identity *identity)
858 if (identity != NULL)
860 free (identity->normalized_filename);
865 /* Compares A and B, returning a strcmp()-type result. */
867 fn_compare_file_identities (const struct file_identity *a,
868 const struct file_identity *b)
870 return strcmp (a->normalized_filename, b->normalized_filename);
872 #endif /* not unix */