1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2006, 2007 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include <data/file-name.h>
33 #include <data/settings.h>
34 #include <libpspp/hash.h>
35 #include <libpspp/message.h>
36 #include <libpspp/str.h>
37 #include <libpspp/verbose-msg.h>
38 #include <libpspp/version.h>
43 #define _(msgid) gettext (msgid)
48 #if defined _WIN32 || defined __WIN32__
49 #define WIN32_LEAN_AND_MEAN /* avoid including junk */
55 const char *config_path;
60 config_path = fn_getenv_default ("STAT_CONFIG_PATH", default_config_path);
63 /* Functions for performing operations on file names. */
66 /* Substitutes $variables in SRC, putting the result in DST,
67 properly handling the case where SRC is a substring of DST.
68 Variables are as defined by GETENV. Supports $var and ${var}
69 syntaxes; $$ substitutes as $. */
71 fn_interp_vars (struct substring src, const char *(*getenv) (const char *),
74 struct string dst = DS_EMPTY_INITIALIZER;
77 while ((c = ss_get_char (&src)) != EOF)
79 ds_put_char (&dst, c);
82 if (ss_match_char (&src, '$') || ss_is_empty (src))
83 ds_put_char (&dst, '$');
86 struct substring var_name;
90 if (ss_match_char (&src, '('))
91 ss_get_until (&src, ')', &var_name);
92 else if (ss_match_char (&src, '{'))
93 ss_get_until (&src, '}', &var_name);
95 ss_get_chars (&src, MAX (1, ss_span (src, ss_cstr (CC_ALNUM))),
98 start = ds_length (&dst);
99 ds_put_substring (&dst, var_name);
100 value = getenv (ds_cstr (&dst) + start);
101 ds_truncate (&dst, start);
103 ds_put_cstr (&dst, value);
107 ds_swap (&dst, dst_);
111 /* Searches for a configuration file with name NAME in the path
112 given by PATH, which is environment-interpolated.
113 Directories in PATH are delimited by ':'. Returns the
114 malloc'd full name of the first file found, or NULL if none is
117 fn_search_path (const char *base_name, const char *path_)
120 struct substring dir;
121 struct string file = DS_EMPTY_INITIALIZER;
124 if (fn_is_absolute (base_name))
125 return xstrdup (base_name);
127 /* Interpolate environment variables. */
128 ds_init_cstr (&path, path_);
129 fn_interp_vars (ds_ss (&path), fn_getenv, &path);
131 verbose_msg (2, _("searching for \"%s\" in path \"%s\""),
132 base_name, ds_cstr (&path));
133 while (ds_separate (&path, ss_cstr (":"), &save_idx, &dir))
135 /* Construct file name. */
137 ds_put_substring (&file, dir);
138 if (!ds_is_empty (&file) && !ISSLASH (ds_last (&file)))
139 ds_put_char (&file, '/');
140 ds_put_cstr (&file, base_name);
143 /* Check whether file exists. */
144 if (fn_exists (ds_cstr (&file)))
146 verbose_msg (2, _("...found \"%s\""), ds_cstr (&file));
148 return ds_cstr (&file);
153 verbose_msg (2, _("...not found"));
159 /* Returns the directory part of FILE_NAME, as a malloc()'d
162 fn_dir_name (const char *file_name)
164 return dir_name (file_name);
167 /* Returns the extension part of FILE_NAME as a malloc()'d string.
168 If FILE_NAME does not have an extension, returns an empty
171 fn_extension (const char *file_name)
173 const char *extension = strrchr (file_name, '.');
174 if (extension == NULL)
176 return xstrdup (extension);
179 /* Find out information about files. */
181 /* Returns true iff NAME specifies an absolute file name. */
183 fn_is_absolute (const char *name)
185 return IS_ABSOLUTE_FILE_NAME (name);
188 /* Returns true if FILE_NAME is a virtual file that doesn't
189 really exist on disk, false if it's a real file name. */
191 fn_is_special (const char *file_name)
193 if (!strcmp (file_name, "-") || !strcmp (file_name, "stdin")
194 || !strcmp (file_name, "stdout") || !strcmp (file_name, "stderr")
196 || file_name[0] == '|'
197 || (*file_name && file_name[strlen (file_name) - 1] == '|')
205 /* Returns true if file with name NAME exists. */
207 fn_exists (const char *name)
210 return stat (name, &temp) == 0;
213 /* Environment variables. */
215 /* Simulates $VER and $ARCH environment variables. */
217 fn_getenv (const char *s)
219 if (!strcmp (s, "VER"))
220 return fn_getenv_default ("STAT_VER", bare_version);
221 else if (!strcmp (s, "ARCH"))
222 return fn_getenv_default ("STAT_ARCH", host_system);
227 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
229 fn_getenv_default (const char *key, const char *def)
231 const char *value = getenv (key);
232 return value ? value : def;
235 /* Basic file handling. */
238 /* Used for giving an error message on a set_safer security
241 safety_violation (const char *fn)
243 msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
249 /* As a general comment on the following routines, a `sensible value'
250 for errno includes 0 if there is no associated system error. The
251 routines will only set errno to 0 if there is an error in a
252 callback that sets errno to 0; they themselves won't. */
254 /* File open routine that understands `-' as stdin/stdout and `|cmd'
255 as a pipe to command `cmd'. Returns resultant FILE on success,
256 NULL on failure. If NULL is returned then errno is set to a
259 fn_open (const char *fn, const char *mode)
261 assert (mode[0] == 'r' || mode[0] == 'w' || mode[0] == 'a');
263 if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
265 else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
267 else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
273 if (settings_get_safer_mode ())
274 return safety_violation (fn);
276 return popen (&fn[1], mode[0] == 'r' ? "r" : "w");
278 else if (*fn && fn[strlen (fn) - 1] == '|')
283 if (settings_get_safer_mode ())
284 return safety_violation (fn);
286 s = xmalloca (strlen (fn));
287 memcpy (s, fn, strlen (fn) - 1);
288 s[strlen (fn) - 1] = 0;
290 f = popen (s, mode[0] == 'r' ? "r" : "w");
299 FILE *f = fopen (fn, mode);
301 if (f && mode[0] == 'w')
302 setvbuf (f, NULL, _IOLBF, 0);
308 /* Counterpart to fn_open that closes file F with name FN; returns 0
309 on success, EOF on failure. If EOF is returned, errno is set to a
312 fn_close (const char *fn, FILE *f)
314 if (fileno (f) == STDIN_FILENO
315 || fileno (f) == STDOUT_FILENO
316 || fileno (f) == STDERR_FILENO)
319 else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
329 /* Creates a new file named FN with the given PERMISSIONS bits,
330 and returns a stream for it or a null pointer on failure.
331 MODE should be "w" or "wb". */
333 create_stream (const char *fn, const char *mode, mode_t permissions)
338 fd = open (fn, O_WRONLY | O_CREAT | O_TRUNC, permissions);
342 stream = fdopen (fd, mode);
345 int save_errno = errno;
353 /* A file's identity:
355 - For a file that exists, this is its device and inode.
357 - For a file that does not exist, but which has a directory
358 name that exists, this is the device and inode of the
359 directory, plus the file's base name.
361 - For a file that does not exist and has a nonexistent
362 directory, this is the file name.
364 Windows doesn't have inode numbers, so we just use the name
368 dev_t device; /* Device number. */
369 ino_t inode; /* Inode number. */
370 char *name; /* File name, where needed, otherwise NULL. */
373 /* Returns a pointer to a dynamically allocated structure whose
374 value can be used to tell whether two files are actually the
375 same file. Returns a null pointer if no information about the
376 file is available, perhaps because it does not exist. The
377 caller is responsible for freeing the structure with
378 fn_free_identity() when finished. */
379 struct file_identity *
380 fn_get_identity (const char *file_name)
382 struct file_identity *identity = xmalloc (sizeof *identity);
384 #if !(defined _WIN32 || defined __WIN32__)
386 if (lstat (file_name, &s) == 0)
388 identity->device = s.st_dev;
389 identity->inode = s.st_ino;
390 identity->name = NULL;
394 char *dir = dir_name (file_name);
395 if (last_component (file_name) != NULL && stat (dir, &s) == 0)
397 identity->device = s.st_dev;
398 identity->inode = s.st_ino;
399 identity->name = base_name (file_name);
403 identity->device = 0;
405 identity->name = xstrdup (file_name);
410 char cname[PATH_MAX];
411 int ok = GetFullPathName (file_name, sizeof cname, cname, NULL);
412 identity->device = 0;
414 identity->name = xstrdup (ok ? cname : file_name);
415 str_lowercase (identity->name);
421 /* Frees IDENTITY obtained from fn_get_identity(). */
423 fn_free_identity (struct file_identity *identity)
425 if (identity != NULL)
427 free (identity->name);
432 /* Compares A and B, returning a strcmp()-type result. */
434 fn_compare_file_identities (const struct file_identity *a,
435 const struct file_identity *b)
437 if (a->device != b->device)
438 return a->device < b->device ? -1 : 1;
439 else if (a->inode != b->inode)
440 return a->inode < b->inode ? -1 : 1;
441 else if (a->name != NULL)
442 return b->name != NULL ? strcmp (a->name, b->name) : 1;
444 return b->name != NULL ? -1 : 0;
447 /* Returns a hash value for IDENTITY. */
449 fn_hash_identity (const struct file_identity *identity)
451 unsigned int hash = identity->device ^ identity->inode;
452 if (identity->name != NULL)
453 hash ^= hsh_hash_string (identity->name);
461 /* Apparently windoze users like to see output dumped into their home directory,
462 not the current directory (!) */
464 default_output_path (void)
466 static const char *home_dir = NULL;
468 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference
469 to HOME, because the user can change HOME. */
470 if (home_dir == NULL)
472 const char *home_drive = getenv ("HOMEDRIVE");
473 const char *home_path = getenv ("HOMEPATH");
475 if (home_drive != NULL && home_path != NULL)
476 home_dir = xasprintf ("%s%s%c",
477 home_drive, home_path, DIRECTORY_SEPARATOR);
479 home_dir = "c:/users/default/"; /* poor default */
486 /* ... whereas the rest of the world just likes it to be
487 put "here" for easy access. */
489 default_output_path (void)
491 static char current_dir[] = "";