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