Merge commit 'origin/stable'
[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 /* 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 $. */
70 void
71 fn_interp_vars (struct substring src, const char *(*getenv) (const char *),
72                 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             size_t start;
88             const char *value;
89
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);
94             else
95               ss_get_chars (&src, MAX (1, ss_span (src, ss_cstr (CC_ALNUM))),
96                             &var_name);
97
98             start = ds_length (&dst);
99             ds_put_substring (&dst, var_name);
100             value = getenv (ds_cstr (&dst) + start);
101             ds_truncate (&dst, start);
102
103             ds_put_cstr (&dst, value);
104           }
105       }
106
107   ds_swap (&dst, dst_);
108   ds_destroy (&dst);
109 }
110
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
115    found. */
116 char *
117 fn_search_path (const char *base_name, const char *path_)
118 {
119   struct string path;
120   struct substring dir;
121   struct string file = DS_EMPTY_INITIALIZER;
122   size_t save_idx = 0;
123
124   if (fn_is_absolute (base_name))
125     return xstrdup (base_name);
126
127   /* Interpolate environment variables. */
128   ds_init_cstr (&path, path_);
129   fn_interp_vars (ds_ss (&path), fn_getenv, &path);
130
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))
134     {
135       /* Construct file name. */
136       ds_clear (&file);
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);
141       ds_relocate (&file);
142
143       /* Check whether file exists. */
144       if (fn_exists (ds_cstr (&file)))
145         {
146           verbose_msg (2, _("...found \"%s\""), ds_cstr (&file));
147           ds_destroy (&path);
148           return ds_cstr (&file);
149         }
150     }
151
152   /* Failure. */
153   verbose_msg (2, _("...not found"));
154   ds_destroy (&path);
155   ds_destroy (&file);
156   return NULL;
157 }
158
159 /* Returns the directory part of FILE_NAME, as a malloc()'d
160    string. */
161 char *
162 fn_dir_name (const char *file_name)
163 {
164   return dir_name (file_name);
165 }
166
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
169    string. */
170 char *
171 fn_extension (const char *file_name)
172 {
173   const char *extension = strrchr (file_name, '.');
174   if (extension == NULL)
175     extension = "";
176   return xstrdup (extension);
177 }
178 \f
179 /* Find out information about files. */
180
181 /* Returns true iff NAME specifies an absolute file name. */
182 bool
183 fn_is_absolute (const char *name)
184 {
185   return IS_ABSOLUTE_FILE_NAME (name);
186 }
187
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. */
190 bool
191 fn_is_special (const char *file_name)
192 {
193   if (!strcmp (file_name, "-") || !strcmp (file_name, "stdin")
194       || !strcmp (file_name, "stdout") || !strcmp (file_name, "stderr")
195 #ifdef HAVE_POPEN
196       || file_name[0] == '|'
197       || (*file_name && file_name[strlen (file_name) - 1] == '|')
198 #endif
199       )
200     return true;
201
202   return false;
203 }
204
205 /* Returns true if file with name NAME exists. */
206 bool
207 fn_exists (const char *name)
208 {
209   struct stat temp;
210   return stat (name, &temp) == 0;
211 }
212 \f
213 /* Environment variables. */
214
215 /* Simulates $VER and $ARCH environment variables. */
216 const char *
217 fn_getenv (const char *s)
218 {
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);
223   else
224     return getenv (s);
225 }
226
227 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
228 const char *
229 fn_getenv_default (const char *key, const char *def)
230 {
231   const char *value = getenv (key);
232   return value ? value : def;
233 }
234 \f
235 /* Basic file handling. */
236
237 #if HAVE_POPEN
238 /* Used for giving an error message on a set_safer security
239    violation. */
240 static FILE *
241 safety_violation (const char *fn)
242 {
243   msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
244   errno = EPERM;
245   return NULL;
246 }
247 #endif
248
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. */
253
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
257    sensible value.  */
258 FILE *
259 fn_open (const char *fn, const char *mode)
260 {
261   assert (mode[0] == 'r' || mode[0] == 'w' || mode[0] == 'a');
262
263   if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
264     return stdin;
265   else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
266     return stdout;
267   else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
268     return stderr;
269
270 #if HAVE_POPEN
271   if (fn[0] == '|')
272     {
273       if (settings_get_safer_mode ())
274         return safety_violation (fn);
275
276       return popen (&fn[1], mode[0] == 'r' ? "r" : "w");
277     }
278   else if (*fn && fn[strlen (fn) - 1] == '|')
279     {
280       char *s;
281       FILE *f;
282
283       if (settings_get_safer_mode ())
284         return safety_violation (fn);
285
286       s = xmalloca (strlen (fn));
287       memcpy (s, fn, strlen (fn) - 1);
288       s[strlen (fn) - 1] = 0;
289
290       f = popen (s, mode[0] == 'r' ? "r" : "w");
291
292       freea (s);
293
294       return f;
295     }
296   else
297 #endif
298     {
299       FILE *f = fopen (fn, mode);
300
301       if (f && mode[0] == 'w')
302         setvbuf (f, NULL, _IOLBF, 0);
303
304       return f;
305     }
306 }
307
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
310    sensible value. */
311 int
312 fn_close (const char *fn, FILE *f)
313 {
314   if (fileno (f) == STDIN_FILENO
315       || fileno (f) == STDOUT_FILENO
316       || fileno (f) == STDERR_FILENO)
317     return 0;
318 #if HAVE_POPEN
319   else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
320     {
321       pclose (f);
322       return 0;
323     }
324 #endif
325   else
326     return fclose (f);
327 }
328
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". */
332 FILE *
333 create_stream (const char *fn, const char *mode, mode_t permissions)
334 {
335   int fd;
336   FILE *stream;
337
338   fd = open (fn, O_WRONLY | O_CREAT | O_TRUNC, permissions);
339   if (fd < 0)
340     return NULL;
341
342   stream = fdopen (fd, mode);
343   if (stream == NULL)
344     {
345       int save_errno = errno;
346       close (fd);
347       errno = save_errno;
348     }
349
350   return stream;
351 }
352
353 /* A file's identity:
354
355    - For a file that exists, this is its device and inode.
356
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.
360
361    - For a file that does not exist and has a nonexistent
362      directory, this is the file name.
363
364    Windows doesn't have inode numbers, so we just use the name
365    there. */
366 struct file_identity
367 {
368   dev_t device;               /* Device number. */
369   ino_t inode;                /* Inode number. */
370   char *name;                 /* File name, where needed, otherwise NULL. */
371 };
372
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)
381 {
382   struct file_identity *identity = xmalloc (sizeof *identity);
383
384 #if !(defined _WIN32 || defined __WIN32__)
385   struct stat s;
386   if (lstat (file_name, &s) == 0)
387     {
388       identity->device = s.st_dev;
389       identity->inode = s.st_ino;
390       identity->name = NULL;
391     }
392   else
393     {
394       char *dir = dir_name (file_name);
395       if (last_component (file_name) != NULL && stat (dir, &s) == 0)
396         {
397           identity->device = s.st_dev;
398           identity->inode = s.st_ino;
399           identity->name = base_name (file_name);
400         }
401       else
402         {
403           identity->device = 0;
404           identity->inode = 0;
405           identity->name = xstrdup (file_name);
406         }
407       free (dir);
408     }
409 #else /* Windows */
410   char cname[PATH_MAX];
411   int ok = GetFullPathName (file_name, sizeof cname, cname, NULL);
412   identity->device = 0;
413   identity->inode = 0;
414   identity->name = xstrdup (ok ? cname : file_name);
415   str_lowercase (identity->name);
416 #endif /* Windows */
417
418   return identity;
419 }
420
421 /* Frees IDENTITY obtained from fn_get_identity(). */
422 void
423 fn_free_identity (struct file_identity *identity)
424 {
425   if (identity != NULL)
426     {
427       free (identity->name);
428       free (identity);
429     }
430 }
431
432 /* Compares A and B, returning a strcmp()-type result. */
433 int
434 fn_compare_file_identities (const struct file_identity *a,
435                             const struct file_identity *b)
436 {
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;
443   else
444     return b->name != NULL ? -1 : 0;
445 }
446
447 /* Returns a hash value for IDENTITY. */
448 unsigned int
449 fn_hash_identity (const struct file_identity *identity)
450 {
451   unsigned int hash = hash_int (identity->device, identity->inode);
452   if (identity->name != NULL)
453     hash = hash_string (identity->name, hash);
454   return hash;
455 }
456
457 #ifdef WIN32
458
459 /* Apparently windoze users like to see output dumped into their home directory,
460    not the current directory (!) */
461 const char *
462 default_output_path (void)
463 {
464   static char *path = NULL;
465
466   if ( path == NULL)
467     {
468       /* Windows NT defines HOMEDRIVE and HOMEPATH.  But give preference
469          to HOME, because the user can change HOME.  */
470
471       const char *home_dir = getenv ("HOME");
472       int i;
473
474       if (home_dir == NULL)
475         {
476           const char *home_drive = getenv ("HOMEDRIVE");
477           const char *home_path = getenv ("HOMEPATH");
478
479
480           if (home_drive != NULL && home_path != NULL)
481             home_dir = xasprintf ("%s%s",
482                                   home_drive, home_path);
483         }
484
485       if (home_dir == NULL)
486         home_dir = "c:/users/default"; /* poor default */
487
488       path = xasprintf ("%s%c", home_dir, '/');
489
490
491       for(i = 0; i < strlen (path); i++)
492         if (path[i] == '\\') path[i] = '/';
493     }
494
495   return path;
496 }
497
498 #else
499
500 /* ... whereas the rest of the world just likes it to be
501    put "here" for easy access. */
502 const char *
503 default_output_path (void)
504 {
505   static char current_dir[]  = "";
506
507   return current_dir;
508 }
509
510 #endif
511