file-name: Generalize fn_interp_vars().
[pspp-builds.git] / src / data / file-name.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2007, 2009 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
16
17 #include <config.h>
18
19 #include <data/file-name.h>
20
21 #include <ctype.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27
28 #include "intprops.h"
29 #include "minmax.h"
30 #include "dirname.h"
31 #include "xmalloca.h"
32
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>
39
40 #include "xalloc.h"
41
42 #include "gettext.h"
43 #define _(msgid) gettext (msgid)
44
45 #include <unistd.h>
46 #include <sys/stat.h>
47
48 #if defined _WIN32 || defined __WIN32__
49 #define WIN32_LEAN_AND_MEAN  /* avoid including junk */
50 #include <windows.h>
51 #endif
52 \f
53 /* Initialization. */
54
55 const char *config_path;
56
57 void
58 fn_init (void)
59 {
60   config_path = fn_getenv_default ("STAT_CONFIG_PATH", default_config_path);
61 }
62 \f
63 /* Functions for performing operations on file names. */
64
65
66 /* Copies from SRC to DST, calling INSERT_VARIABLE to handle each
67    instance of $var or ${var} in SRC.  $$ is replaced by $. */
68 void
69 fn_interp_vars (struct substring src,
70                 void (*insert_variable) (const char *var,
71                                          struct string *dst, void *aux),
72                 void *aux, struct string *dst_)
73 {
74   struct string dst = DS_EMPTY_INITIALIZER;
75   int c;
76
77   while ((c = ss_get_char (&src)) != EOF)
78     if (c != '$')
79       ds_put_char (&dst, c);
80     else
81       {
82         if (ss_match_char (&src, '$') || ss_is_empty (src))
83           ds_put_char (&dst, '$');
84         else
85           {
86             struct substring var_name;
87             char *var;
88
89             if (ss_match_char (&src, '('))
90               ss_get_until (&src, ')', &var_name);
91             else if (ss_match_char (&src, '{'))
92               ss_get_until (&src, '}', &var_name);
93             else
94               ss_get_chars (&src, MAX (1, ss_span (src, ss_cstr (CC_ALNUM))),
95                             &var_name);
96
97             var = ss_xstrdup (var_name);
98             insert_variable (var, &dst, aux);
99             free (var);
100           }
101       }
102
103   ds_swap (&dst, dst_);
104   ds_destroy (&dst);
105 }
106
107 static void
108 insert_env_var (const char *var, struct string *dst, void *aux UNUSED)
109 {
110   const char *value = fn_getenv (var);
111   if (value != NULL)
112     ds_put_cstr (dst, value);
113 }
114
115 /* Searches for a configuration file with name NAME in the path
116    given by PATH, which is environment-interpolated.
117    Directories in PATH are delimited by ':'.  Returns the
118    malloc'd full name of the first file found, or NULL if none is
119    found. */
120 char *
121 fn_search_path (const char *base_name, const char *path_)
122 {
123   struct string path;
124   struct substring dir;
125   struct string file = DS_EMPTY_INITIALIZER;
126   size_t save_idx = 0;
127
128   if (fn_is_absolute (base_name))
129     return xstrdup (base_name);
130
131   /* Interpolate environment variables. */
132   ds_init_cstr (&path, path_);
133   fn_interp_vars (ds_ss (&path), insert_env_var, NULL, &path);
134
135   verbose_msg (2, _("searching for \"%s\" in path \"%s\""),
136                base_name, ds_cstr (&path));
137   while (ds_separate (&path, ss_cstr (":"), &save_idx, &dir))
138     {
139       /* Construct file name. */
140       ds_clear (&file);
141       ds_put_substring (&file, dir);
142       if (!ds_is_empty (&file) && !ISSLASH (ds_last (&file)))
143         ds_put_char (&file, '/');
144       ds_put_cstr (&file, base_name);
145       ds_relocate (&file);
146
147       /* Check whether file exists. */
148       if (fn_exists (ds_cstr (&file)))
149         {
150           verbose_msg (2, _("...found \"%s\""), ds_cstr (&file));
151           ds_destroy (&path);
152           return ds_cstr (&file);
153         }
154     }
155
156   /* Failure. */
157   verbose_msg (2, _("...not found"));
158   ds_destroy (&path);
159   ds_destroy (&file);
160   return NULL;
161 }
162
163 /* Returns the directory part of FILE_NAME, as a malloc()'d
164    string. */
165 char *
166 fn_dir_name (const char *file_name)
167 {
168   return dir_name (file_name);
169 }
170
171 /* Returns the extension part of FILE_NAME as a malloc()'d string.
172    If FILE_NAME does not have an extension, returns an empty
173    string. */
174 char *
175 fn_extension (const char *file_name)
176 {
177   const char *extension = strrchr (file_name, '.');
178   if (extension == NULL)
179     extension = "";
180   return xstrdup (extension);
181 }
182 \f
183 /* Find out information about files. */
184
185 /* Returns true iff NAME specifies an absolute file name. */
186 bool
187 fn_is_absolute (const char *name)
188 {
189   return IS_ABSOLUTE_FILE_NAME (name);
190 }
191
192 /* Returns true if FILE_NAME is a virtual file that doesn't
193    really exist on disk, false if it's a real file name. */
194 bool
195 fn_is_special (const char *file_name)
196 {
197   if (!strcmp (file_name, "-") || !strcmp (file_name, "stdin")
198       || !strcmp (file_name, "stdout") || !strcmp (file_name, "stderr")
199 #ifdef HAVE_POPEN
200       || file_name[0] == '|'
201       || (*file_name && file_name[strlen (file_name) - 1] == '|')
202 #endif
203       )
204     return true;
205
206   return false;
207 }
208
209 /* Returns true if file with name NAME exists. */
210 bool
211 fn_exists (const char *name)
212 {
213   struct stat temp;
214   return stat (name, &temp) == 0;
215 }
216 \f
217 /* Environment variables. */
218
219 /* Simulates $VER and $ARCH environment variables. */
220 const char *
221 fn_getenv (const char *s)
222 {
223   if (!strcmp (s, "VER"))
224     return fn_getenv_default ("STAT_VER", bare_version);
225   else if (!strcmp (s, "ARCH"))
226     return fn_getenv_default ("STAT_ARCH", host_system);
227   else
228     return getenv (s);
229 }
230
231 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
232 const char *
233 fn_getenv_default (const char *key, const char *def)
234 {
235   const char *value = getenv (key);
236   return value ? value : def;
237 }
238 \f
239 /* Basic file handling. */
240
241 #if HAVE_POPEN
242 /* Used for giving an error message on a set_safer security
243    violation. */
244 static FILE *
245 safety_violation (const char *fn)
246 {
247   msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
248   errno = EPERM;
249   return NULL;
250 }
251 #endif
252
253 /* As a general comment on the following routines, a `sensible value'
254    for errno includes 0 if there is no associated system error.  The
255    routines will only set errno to 0 if there is an error in a
256    callback that sets errno to 0; they themselves won't. */
257
258 /* File open routine that understands `-' as stdin/stdout and `|cmd'
259    as a pipe to command `cmd'.  Returns resultant FILE on success,
260    NULL on failure.  If NULL is returned then errno is set to a
261    sensible value.  */
262 FILE *
263 fn_open (const char *fn, const char *mode)
264 {
265   assert (mode[0] == 'r' || mode[0] == 'w' || mode[0] == 'a');
266
267   if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
268     return stdin;
269   else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
270     return stdout;
271   else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
272     return stderr;
273
274 #if HAVE_POPEN
275   if (fn[0] == '|')
276     {
277       if (settings_get_safer_mode ())
278         return safety_violation (fn);
279
280       return popen (&fn[1], mode[0] == 'r' ? "r" : "w");
281     }
282   else if (*fn && fn[strlen (fn) - 1] == '|')
283     {
284       char *s;
285       FILE *f;
286
287       if (settings_get_safer_mode ())
288         return safety_violation (fn);
289
290       s = xmalloca (strlen (fn));
291       memcpy (s, fn, strlen (fn) - 1);
292       s[strlen (fn) - 1] = 0;
293
294       f = popen (s, mode[0] == 'r' ? "r" : "w");
295
296       freea (s);
297
298       return f;
299     }
300   else
301 #endif
302     {
303       FILE *f = fopen (fn, mode);
304
305       if (f && mode[0] == 'w')
306         setvbuf (f, NULL, _IOLBF, 0);
307
308       return f;
309     }
310 }
311
312 /* Counterpart to fn_open that closes file F with name FN; returns 0
313    on success, EOF on failure.  If EOF is returned, errno is set to a
314    sensible value. */
315 int
316 fn_close (const char *fn, FILE *f)
317 {
318   if (fileno (f) == STDIN_FILENO
319       || fileno (f) == STDOUT_FILENO
320       || fileno (f) == STDERR_FILENO)
321     return 0;
322 #if HAVE_POPEN
323   else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
324     {
325       pclose (f);
326       return 0;
327     }
328 #endif
329   else
330     return fclose (f);
331 }
332
333 /* Creates a new file named FN with the given PERMISSIONS bits,
334    and returns a stream for it or a null pointer on failure.
335    MODE should be "w" or "wb". */
336 FILE *
337 create_stream (const char *fn, const char *mode, mode_t permissions)
338 {
339   int fd;
340   FILE *stream;
341
342   fd = open (fn, O_WRONLY | O_CREAT | O_TRUNC, permissions);
343   if (fd < 0)
344     return NULL;
345
346   stream = fdopen (fd, mode);
347   if (stream == NULL)
348     {
349       int save_errno = errno;
350       close (fd);
351       errno = save_errno;
352     }
353
354   return stream;
355 }
356
357 /* A file's identity:
358
359    - For a file that exists, this is its device and inode.
360
361    - For a file that does not exist, but which has a directory
362      name that exists, this is the device and inode of the
363      directory, plus the file's base name.
364
365    - For a file that does not exist and has a nonexistent
366      directory, this is the file name.
367
368    Windows doesn't have inode numbers, so we just use the name
369    there. */
370 struct file_identity
371 {
372   dev_t device;               /* Device number. */
373   ino_t inode;                /* Inode number. */
374   char *name;                 /* File name, where needed, otherwise NULL. */
375 };
376
377 /* Returns a pointer to a dynamically allocated structure whose
378    value can be used to tell whether two files are actually the
379    same file.  Returns a null pointer if no information about the
380    file is available, perhaps because it does not exist.  The
381    caller is responsible for freeing the structure with
382    fn_free_identity() when finished. */
383 struct file_identity *
384 fn_get_identity (const char *file_name)
385 {
386   struct file_identity *identity = xmalloc (sizeof *identity);
387
388 #if !(defined _WIN32 || defined __WIN32__)
389   struct stat s;
390   if (lstat (file_name, &s) == 0)
391     {
392       identity->device = s.st_dev;
393       identity->inode = s.st_ino;
394       identity->name = NULL;
395     }
396   else
397     {
398       char *dir = dir_name (file_name);
399       if (last_component (file_name) != NULL && stat (dir, &s) == 0)
400         {
401           identity->device = s.st_dev;
402           identity->inode = s.st_ino;
403           identity->name = base_name (file_name);
404         }
405       else
406         {
407           identity->device = 0;
408           identity->inode = 0;
409           identity->name = xstrdup (file_name);
410         }
411       free (dir);
412     }
413 #else /* Windows */
414   char cname[PATH_MAX];
415   int ok = GetFullPathName (file_name, sizeof cname, cname, NULL);
416   identity->device = 0;
417   identity->inode = 0;
418   identity->name = xstrdup (ok ? cname : file_name);
419   str_lowercase (identity->name);
420 #endif /* Windows */
421
422   return identity;
423 }
424
425 /* Frees IDENTITY obtained from fn_get_identity(). */
426 void
427 fn_free_identity (struct file_identity *identity)
428 {
429   if (identity != NULL)
430     {
431       free (identity->name);
432       free (identity);
433     }
434 }
435
436 /* Compares A and B, returning a strcmp()-type result. */
437 int
438 fn_compare_file_identities (const struct file_identity *a,
439                             const struct file_identity *b)
440 {
441   if (a->device != b->device)
442     return a->device < b->device ? -1 : 1;
443   else if (a->inode != b->inode)
444     return a->inode < b->inode ? -1 : 1;
445   else if (a->name != NULL)
446     return b->name != NULL ? strcmp (a->name, b->name) : 1;
447   else
448     return b->name != NULL ? -1 : 0;
449 }
450
451 /* Returns a hash value for IDENTITY. */
452 unsigned int
453 fn_hash_identity (const struct file_identity *identity)
454 {
455   unsigned int hash = hash_int (identity->device, identity->inode);
456   if (identity->name != NULL)
457     hash = hash_string (identity->name, hash);
458   return hash;
459 }
460
461 #ifdef WIN32
462
463 /* Apparently windoze users like to see output dumped into their home directory,
464    not the current directory (!) */
465 const char *
466 default_output_path (void)
467 {
468   static char *path = NULL;
469
470   if ( path == NULL)
471     {
472       /* Windows NT defines HOMEDRIVE and HOMEPATH.  But give preference
473          to HOME, because the user can change HOME.  */
474
475       const char *home_dir = getenv ("HOME");
476       int i;
477
478       if (home_dir == NULL)
479         {
480           const char *home_drive = getenv ("HOMEDRIVE");
481           const char *home_path = getenv ("HOMEPATH");
482
483           if (home_drive != NULL && home_path != NULL)
484             home_dir = xasprintf ("%s%s",
485                                   home_drive, home_path);
486         }
487
488       if (home_dir == NULL)
489         home_dir = "c:/users/default"; /* poor default */
490
491       /* Copy home_dir into path.  Add a slash at the end but
492          only if there isn't already one there, because Windows
493          treats // specially. */
494       if (home_dir[0] == '\0'
495           || strchr ("/\\", home_dir[strlen (home_dir) - 1]) == NULL)
496         path = xasprintf ("%s%c", home_dir, '/');
497       else
498         path = xstrdup (home_dir);
499
500       for(i = 0; i < strlen (path); i++)
501         if (path[i] == '\\') path[i] = '/';
502     }
503
504   return path;
505 }
506
507 #else
508
509 /* ... whereas the rest of the world just likes it to be
510    put "here" for easy access. */
511 const char *
512 default_output_path (void)
513 {
514   static char current_dir[]  = "";
515
516   return current_dir;
517 }
518
519 #endif
520