1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000 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
32 #include "xreadlink.h"
35 #define _(msgid) gettext (msgid)
37 #include "debug-print.h"
39 /* PORTME: Everything in this file is system dependent. */
47 #include "stat-macros.h"
54 #include <win32/windows.h>
63 const char *config_path;
68 config_path = fn_getenv_default ("STAT_CONFIG_PATH", default_config_path);
71 /* Functions for performing operations on filenames. */
73 /* Substitutes $variables as defined by GETENV into INPUT and returns
74 a copy of the resultant string. Supports $var and ${var} syntaxes;
75 $$ substitutes as $. */
77 fn_interp_vars (const char *input, const char *(*getenv) (const char *))
81 if (NULL == strchr (input, '$'))
82 return xstrdup (input);
84 ds_init (&output, strlen (input));
90 return ds_c_str (&output);
97 ds_putc (&output, '$');
106 start = ds_length (&output);
113 else if (*input == '{')
121 while (*input && *input != stop
122 && (stop || isalpha ((unsigned char) *input)))
123 ds_putc (&output, *input++);
125 value = getenv (ds_c_str (&output) + start);
126 ds_truncate (&output, start);
127 ds_puts (&output, value);
129 if (stop && *input == stop)
134 ds_putc (&output, *input++);
139 /* Expands csh tilde notation from the path INPUT into a malloc()'d
142 fn_tilde_expand (const char *input)
145 struct string output;
147 if (NULL == strchr (input, '~'))
148 return xstrdup (input);
149 ds_init (&output, strlen (input));
153 for (ip = input; *ip; )
154 if (*ip != '~' || (ip != input && ip[-1] != PATH_DELIMITER))
155 ds_putc (&output, *ip++);
158 static const char stop_set[3] = {DIR_SEPARATOR, PATH_DELIMITER, 0};
163 cp = ip + strcspn (ip, stop_set);
170 strncpy (username, ip, cp - ip + 1);
172 pwd = getpwnam (username);
174 if (!pwd || !pwd->pw_dir)
175 ds_putc (&output, *ip++);
177 ds_puts (&output, pwd->pw_dir);
181 const char *home = fn_getenv ("HOME");
183 ds_putc (&output, *ip++);
185 ds_puts (&output, home);
191 return ds_c_str (&output);
195 fn_tilde_expand (const char *input)
197 return xstrdup (input);
201 /* Searches for a configuration file with name NAME in the path given
202 by PATH, which is tilde- and environment-interpolated. Directories
203 in PATH are delimited by PATH_DELIMITER, defined in <pref.h>.
204 Returns the malloc'd full name of the first file found, or NULL if
207 If PREPEND is non-NULL, then it is prepended to each filename;
208 i.e., it looks like PREPEND/PATH_COMPONENT/NAME. This is not done
209 with absolute directories in the path. */
210 #if defined (unix) || defined (__MSDOS__) || defined (__WIN32__)
212 fn_search_path (const char *basename, const char *path, const char *prepend)
215 struct string filename;
218 if (fn_absolute_p (basename))
219 return fn_tilde_expand (basename);
222 char *temp = fn_interp_vars (path, fn_getenv);
223 bp = subst_path = fn_tilde_expand (temp);
227 msg (VM (4), _("Searching for `%s'..."), basename);
228 ds_init (&filename, 64);
235 msg (VM (4), _("Search unsuccessful!"));
236 ds_destroy (&filename);
241 for (ep = bp; *ep && *ep != PATH_DELIMITER; ep++)
244 /* Paste together PREPEND/PATH/BASENAME. */
245 ds_clear (&filename);
246 if (prepend && !fn_absolute_p (bp))
248 ds_puts (&filename, prepend);
249 ds_putc (&filename, DIR_SEPARATOR);
251 ds_concat (&filename, bp, ep - bp);
253 && ds_c_str (&filename)[ds_length (&filename) - 1] != DIR_SEPARATOR)
254 ds_putc (&filename, DIR_SEPARATOR);
255 ds_puts (&filename, basename);
257 msg (VM (5), " - %s", ds_c_str (&filename));
258 if (fn_exists_p (ds_c_str (&filename)))
260 msg (VM (4), _("Found `%s'."), ds_c_str (&filename));
262 return ds_c_str (&filename);
267 msg (VM (4), _("Search unsuccessful!"));
269 ds_destroy (&filename);
275 #else /* not unix, msdog, lose32 */
277 fn_search_path (const char *basename, const char *path, const char *prepend)
279 size_t size = strlen (path) + 1 + strlen (basename) + 1;
284 size += strlen (prepend) + 1;
285 string = xmalloc (size);
290 cp = stpcpy (cp, prepend);
291 *cp++ = DIR_SEPARATOR;
293 cp = stpcpy (cp, path);
294 *cp++ = DIR_SEPARATOR;
295 strcpy (cp, basename);
299 #endif /* not unix, msdog, lose32 */
301 /* Prepends directory DIR to filename FILE and returns a malloc()'d
304 fn_prepend_dir (const char *file, const char *dir)
309 if (fn_absolute_p (file))
310 return xstrdup (file);
312 temp = xmalloc (strlen (file) + 1 + strlen (dir) + 1);
313 cp = stpcpy (temp, dir);
314 if (cp != temp && cp[-1] != DIR_SEPARATOR)
315 *cp++ = DIR_SEPARATOR;
316 cp = stpcpy (cp, file);
321 /* fn_normalize(): This very OS-dependent routine canonicalizes
322 filename FN1. The filename should not need to be the name of an
323 existing file. Returns a malloc()'d copy of the canonical name.
324 This function must always succeed; if it needs to bail out then it
325 should return xstrdup(FN1). */
328 fn_normalize (const char *filename)
331 char *fn1, *fn2, *dest;
334 if (fn_special_p (filename))
335 return xstrdup (filename);
337 fn1 = fn_tilde_expand (filename);
339 /* Follow symbolic links. */
343 fn1 = fn_readlink (fn1);
352 maxlen = strlen (fn1) * 2;
355 dest = fn2 = xmalloc (maxlen + 1);
358 if (*src == DIR_SEPARATOR)
363 while (getcwd (dest, maxlen - (dest - fn2)) == NULL && errno == ERANGE)
366 dest = fn2 = xrealloc (fn2, maxlen + 1);
375 dest = strchr (fn2, '\0');
376 if (dest - fn2 >= maxlen)
378 int ofs = dest - fn2;
380 fn2 = xrealloc (fn2, maxlen + 1);
383 if (dest[-1] != DIR_SEPARATOR)
384 *dest++ = DIR_SEPARATOR;
394 if (c == DIR_SEPARATOR || c == 0)
396 /* remove `./', `../' from directory */
397 if (dest[-1] == '.' && dest[-2] == DIR_SEPARATOR)
399 else if (dest[-1] == '.' && dest[-2] == '.' && dest[-3] == DIR_SEPARATOR)
404 while (dest[-1] != DIR_SEPARATOR)
407 else if (dest[-1] != DIR_SEPARATOR) /* remove extra slashes */
412 if (dest[-1] == DIR_SEPARATOR && dest > fn2 + 1)
417 return xrealloc (fn2, strlen (fn2) + 1);
425 if (dest - fn2 >= maxlen)
427 int ofs = dest - fn2;
429 fn2 = xrealloc (fn2, maxlen + 1);
436 #elif defined (__WIN32__)
438 fn_normalize (const char *fn1)
444 /* Don't change special filenames. */
445 if (is_special_filename (filename))
446 return xstrdup (filename);
448 /* First find the required buffer length. */
449 len = GetFullPathName (fn1, 0, NULL, NULL);
456 /* Then make a buffer that big. */
458 success = GetFullPathName (fn1, len, fn2, NULL);
459 if (success >= len || success == 0)
469 fn_normalize (const char *fn1)
471 char *fn2 = _fullpath (NULL, fn1, 0);
475 for (cp = fn2; *cp; cp++)
476 *cp = toupper ((unsigned char) (*cp));
479 return xstrdup (fn1);
483 fn_normalize (const char *fn1)
485 char *fn2 = xmalloc (1024);
487 fn2 = xrealloc (fn2, strlen (fn2) + 1);
490 #else /* not Lose32, Unix, or DJGPP */
492 fn_normalize (const char *fn)
496 #endif /* not Lose32, Unix, or DJGPP */
498 /* Returns the directory part of FILENAME, as a malloc()'d
501 fn_dirname (const char *filename)
507 len = strlen (filename);
508 if (len == 1 && filename[0] == '/')
510 else if (len && filename[len - 1] == DIR_SEPARATOR)
511 p = buf_find_reverse (filename, len - 1, filename + len - 1, 1);
513 p = strrchr (filename, DIR_SEPARATOR);
517 s = xmalloc (p - filename + 1);
518 memcpy (s, filename, p - filename);
524 /* Returns the basename part of FILENAME as a malloc()'d string. */
527 fn_basename (const char *filename)
529 /* Not used, not implemented. */
535 /* Returns the current working directory, as a malloc()'d string.
541 char *buffer = xmalloc (size);
545 char *value = getcwd (buffer, size);
551 buffer = xmalloc (size);
559 char *buffer = xmalloc (size);
571 /* Find out information about files. */
573 /* Returns nonzero iff NAME specifies an absolute filename. */
575 fn_absolute_p (const char *name)
579 || !strncmp (name, "./", 2)
580 || !strncmp (name, "../", 3)
583 #elif defined (__MSDOS__)
585 || !strncmp (name, ".\\", 2)
586 || !strncmp (name, "..\\", 3)
587 || (name[0] && name[1] == ':'))
594 /* Returns 1 if the filename specified is a virtual file that doesn't
595 really exist on disk, 0 if it's a real filename. */
597 fn_special_p (const char *filename)
599 if (!strcmp (filename, "-") || !strcmp (filename, "stdin")
600 || !strcmp (filename, "stdout") || !strcmp (filename, "stderr")
602 || filename[0] == '|'
603 || (*filename && filename[strlen (filename) - 1] == '|')
611 /* Returns nonzero if file with name NAME exists. */
613 fn_exists_p (const char *name)
618 return stat (name, &temp) == 0;
620 FILE *f = fopen (name, "r");
628 /* Returns the symbolic link value for FILENAME as a dynamically
629 allocated buffer, or a null pointer on failure. */
631 fn_readlink (const char *filename)
633 return xreadlink (filename, 32);
636 /* Environment variables. */
638 /* Simulates $VER and $ARCH environment variables. */
640 fn_getenv (const char *s)
642 if (!strcmp (s, "VER"))
643 return fn_getenv_default ("STAT_VER", bare_version);
644 else if (!strcmp (s, "ARCH"))
645 return fn_getenv_default ("STAT_ARCH", host_system);
650 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
652 fn_getenv_default (const char *key, const char *def)
654 const char *value = getenv (key);
655 return value ? value : def;
658 /* Basic file handling. */
660 /* Used for giving an error message on a set_safer security
663 safety_violation (const char *fn)
665 msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
670 /* As a general comment on the following routines, a `sensible value'
671 for errno includes 0 if there is no associated system error. The
672 routines will only set errno to 0 if there is an error in a
673 callback that sets errno to 0; they themselves won't. */
675 /* File open routine that understands `-' as stdin/stdout and `|cmd'
676 as a pipe to command `cmd'. Returns resultant FILE on success,
677 NULL on failure. If NULL is returned then errno is set to a
680 fn_open (const char *fn, const char *mode)
682 assert (mode[0] == 'r' || mode[0] == 'w');
684 if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
686 else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
688 else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
695 return safety_violation (fn);
697 return popen (&fn[1], mode);
699 else if (*fn && fn[strlen (fn) - 1] == '|')
705 return safety_violation (fn);
707 s = local_alloc (strlen (fn));
708 memcpy (s, fn, strlen (fn) - 1);
709 s[strlen (fn) - 1] = 0;
720 FILE *f = fopen (fn, mode);
722 if (f && mode[0] == 'w')
723 setvbuf (f, NULL, _IOLBF, 0);
729 /* Counterpart to fn_open that closes file F with name FN; returns 0
730 on success, EOF on failure. If EOF is returned, errno is set to a
733 fn_close (const char *fn, FILE *f)
735 if (!strcmp (fn, "-"))
738 else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
748 /* More extensive file handling. */
750 /* File open routine that extends fn_open(). Opens or reopens a
751 file according to the contents of file_ext F. Returns nonzero on
752 success. If 0 is returned, errno is set to a sensible value. */
754 fn_open_ext (struct file_ext *f)
758 p = strstr (f->filename, "%d");
761 char *s = local_alloc (strlen (f->filename) + INT_DIGITS - 1);
764 memcpy (s, f->filename, p - f->filename);
765 cp = spprintf (&s[p - f->filename], "%d", *f->sequence_no);
773 if (f->preclose (f) == 0)
776 if (EOF == fn_close (f->filename, f->file) || error)
790 f->file = fn_open (s, f->mode);
793 if (f->file && f->postopen)
794 if (f->postopen (f) == 0)
797 fn_close (f->filename, f->file);
803 return (f->file != NULL);
809 f->file = fn_open (f->filename, f->mode);
811 if (f->file && f->postopen)
812 if (f->postopen (f) == 0)
815 fn_close (f->filename, f->file);
821 return (f->file != NULL);
825 /* Properly closes the file associated with file_ext F, if any.
826 Return nonzero on success. If zero is returned, errno is set to a
829 fn_close_ext (struct file_ext *f)
836 if (f->preclose (f) == 0)
839 if (EOF == fn_close (f->filename, f->file) || error)
855 /* A file's identity. */
858 dev_t device; /* Device number. */
859 ino_t inode; /* Inode number. */
862 /* Returns a pointer to a dynamically allocated structure whose
863 value can be used to tell whether two files are actually the
864 same file. Returns a null pointer if no information about the
865 file is available, perhaps because it does not exist. The
866 caller is responsible for freeing the structure with
867 fn_free_identity() when finished. */
868 struct file_identity *
869 fn_get_identity (const char *filename)
873 if (stat (filename, &s) == 0)
875 struct file_identity *identity = xmalloc (sizeof *identity);
876 identity->device = s.st_dev;
877 identity->inode = s.st_ino;
884 /* Frees IDENTITY obtained from fn_get_identity(). */
886 fn_free_identity (struct file_identity *identity)
891 /* Compares A and B, returning a strcmp()-type result. */
893 fn_compare_file_identities (const struct file_identity *a,
894 const struct file_identity *b)
898 if (a->device != b->device)
899 return a->device < b->device ? -1 : 1;
901 return a->inode < b->inode ? -1 : a->inode > b->inode;
904 /* A file's identity. */
907 char *normalized_filename; /* File's normalized name. */
910 /* Returns a pointer to a dynamically allocated structure whose
911 value can be used to tell whether two files are actually the
912 same file. Returns a null pointer if no information about the
913 file is available, perhaps because it does not exist. The
914 caller is responsible for freeing the structure with
915 fn_free_identity() when finished. */
916 struct file_identity *
917 fn_get_identity (const char *filename)
919 struct file_identity *identity = xmalloc (sizeof *identity);
920 identity->normalized_filename = fn_normalize (filename);
924 /* Frees IDENTITY obtained from fn_get_identity(). */
926 fn_free_identity (struct file_identity *identity)
928 if (identity != NULL)
930 free (identity->normalized_filename);
935 /* Compares A and B, returning a strcmp()-type result. */
937 fn_compare_file_identities (const struct file_identity *a,
938 const struct file_identity *b)
940 return strcmp (a->normalized_filename, b->normalized_filename);
942 #endif /* not unix */