f8ad11d07a342f22fd5bf4cfa026d9a93a412ce0
[pspp-builds.git] / src / data / file-name.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2007 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
32 #include <libpspp/alloc.h>
33 #include <libpspp/message.h>
34 #include <data/settings.h>
35 #include <libpspp/str.h>
36 #include <libpspp/verbose-msg.h>
37 #include <libpspp/version.h>
38
39 #include "gettext.h"
40 #define _(msgid) gettext (msgid)
41
42 #include <unistd.h>
43 #include <sys/stat.h>
44
45 #if defined _WIN32 || defined __WIN32__
46 #define WIN32_LEAN_AND_MEAN  /* avoid including junk */
47 #include <windows.h>
48 #endif
49 \f
50 /* Initialization. */
51
52 const char *config_path;
53
54 void
55 fn_init (void)
56 {
57   config_path = fn_getenv_default ("STAT_CONFIG_PATH", default_config_path);
58 }
59 \f
60 /* Functions for performing operations on file names. */
61
62
63 /* Substitutes $variables in SRC, putting the result in DST,
64    properly handling the case where SRC is a substring of DST.
65    Variables are as defined by GETENV. Supports $var and ${var}
66    syntaxes; $$ substitutes as $. */
67 void
68 fn_interp_vars (struct substring src, const char *(*getenv) (const char *),
69                 struct string *dst_)
70 {
71   struct string dst = DS_EMPTY_INITIALIZER;
72   int c;
73
74   while ((c = ss_get_char (&src)) != EOF)
75     if (c != '$')
76       ds_put_char (&dst, c);
77     else
78       {
79         if (ss_match_char (&src, '$') || ss_is_empty (src))
80           ds_put_char (&dst, '$');
81         else
82           {
83             struct substring var_name;
84             size_t start;
85             const char *value;
86
87             if (ss_match_char (&src, '('))
88               ss_get_until (&src, ')', &var_name);
89             else if (ss_match_char (&src, '{'))
90               ss_get_until (&src, '}', &var_name);
91             else
92               ss_get_chars (&src, MAX (1, ss_span (src, ss_cstr (CC_ALNUM))),
93                             &var_name);
94
95             start = ds_length (&dst);
96             ds_put_substring (&dst, var_name);
97             value = getenv (ds_cstr (&dst) + start);
98             ds_truncate (&dst, start);
99
100             ds_put_cstr (&dst, value);
101           }
102       }
103
104   ds_swap (&dst, dst_);
105   ds_destroy (&dst);
106 }
107
108 /* Searches for a configuration file with name NAME in the path
109    given by PATH, which is environment-interpolated.
110    Directories in PATH are delimited by ':'.  Returns the
111    malloc'd full name of the first file found, or NULL if none is
112    found. */
113 char *
114 fn_search_path (const char *base_name, const char *path_)
115 {
116   struct string path;
117   struct substring dir;
118   struct string file = DS_EMPTY_INITIALIZER;
119   size_t save_idx = 0;
120
121   if (fn_is_absolute (base_name))
122     return xstrdup (base_name);
123
124   /* Interpolate environment variables. */
125   ds_init_cstr (&path, path_);
126   fn_interp_vars (ds_ss (&path), fn_getenv, &path);
127
128   verbose_msg (2, _("searching for \"%s\" in path \"%s\""),
129                base_name, ds_cstr (&path));
130   while (ds_separate (&path, ss_cstr (":"), &save_idx, &dir))
131     {
132       /* Construct file name. */
133       ds_clear (&file);
134       ds_put_substring (&file, dir);
135       if (!ds_is_empty (&file) && !ISSLASH (ds_last (&file)))
136         ds_put_char (&file, '/');
137       ds_put_cstr (&file, base_name);
138
139       /* Check whether file exists. */
140       if (fn_exists (ds_cstr (&file)))
141         {
142           verbose_msg (2, _("...found \"%s\""), ds_cstr (&file));
143           ds_destroy (&path);
144           return ds_cstr (&file);
145         }
146     }
147
148   /* Failure. */
149   verbose_msg (2, _("...not found"));
150   ds_destroy (&path);
151   ds_destroy (&file);
152   return NULL;
153 }
154
155 /* Returns the directory part of FILE_NAME, as a malloc()'d
156    string. */
157 char *
158 fn_dir_name (const char *file_name)
159 {
160   return dir_name (file_name);
161 }
162
163 /* Returns the extension part of FILE_NAME as a malloc()'d string.
164    If FILE_NAME does not have an extension, returns an empty
165    string. */
166 char *
167 fn_extension (const char *file_name)
168 {
169   const char *extension = strrchr (file_name, '.');
170   if (extension == NULL)
171     extension = "";
172   return xstrdup (extension);
173 }
174 \f
175 /* Find out information about files. */
176
177 /* Returns true iff NAME specifies an absolute file name. */
178 bool
179 fn_is_absolute (const char *name)
180 {
181   return IS_ABSOLUTE_FILE_NAME (name);
182 }
183
184 /* Returns true if FILE_NAME is a virtual file that doesn't
185    really exist on disk, false if it's a real file name. */
186 bool
187 fn_is_special (const char *file_name)
188 {
189   if (!strcmp (file_name, "-") || !strcmp (file_name, "stdin")
190       || !strcmp (file_name, "stdout") || !strcmp (file_name, "stderr")
191 #ifdef HAVE_POPEN
192       || file_name[0] == '|'
193       || (*file_name && file_name[strlen (file_name) - 1] == '|')
194 #endif
195       )
196     return true;
197
198   return false;
199 }
200
201 /* Returns true if file with name NAME exists. */
202 bool
203 fn_exists (const char *name)
204 {
205   struct stat temp;
206   return stat (name, &temp) == 0;
207 }
208 \f
209 /* Environment variables. */
210
211 /* Simulates $VER and $ARCH environment variables. */
212 const char *
213 fn_getenv (const char *s)
214 {
215   if (!strcmp (s, "VER"))
216     return fn_getenv_default ("STAT_VER", bare_version);
217   else if (!strcmp (s, "ARCH"))
218     return fn_getenv_default ("STAT_ARCH", host_system);
219   else
220     return getenv (s);
221 }
222
223 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
224 const char *
225 fn_getenv_default (const char *key, const char *def)
226 {
227   const char *value = getenv (key);
228   return value ? value : def;
229 }
230 \f
231 /* Basic file handling. */
232
233 #if HAVE_POPEN
234 /* Used for giving an error message on a set_safer security
235    violation. */
236 static FILE *
237 safety_violation (const char *fn)
238 {
239   msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
240   errno = EPERM;
241   return NULL;
242 }
243 #endif
244
245 /* As a general comment on the following routines, a `sensible value'
246    for errno includes 0 if there is no associated system error.  The
247    routines will only set errno to 0 if there is an error in a
248    callback that sets errno to 0; they themselves won't. */
249
250 /* File open routine that understands `-' as stdin/stdout and `|cmd'
251    as a pipe to command `cmd'.  Returns resultant FILE on success,
252    NULL on failure.  If NULL is returned then errno is set to a
253    sensible value.  */
254 FILE *
255 fn_open (const char *fn, const char *mode)
256 {
257   assert (mode[0] == 'r' || mode[0] == 'w' || mode[0] == 'a');
258
259   if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-")))
260     return stdin;
261   else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
262     return stdout;
263   else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
264     return stderr;
265
266 #if HAVE_POPEN
267   if (fn[0] == '|')
268     {
269       if (get_safer_mode ())
270         return safety_violation (fn);
271
272       return popen (&fn[1], mode[0] == 'r' ? "r" : "w");
273     }
274   else if (*fn && fn[strlen (fn) - 1] == '|')
275     {
276       char *s;
277       FILE *f;
278
279       if (get_safer_mode ())
280         return safety_violation (fn);
281
282       s = local_alloc (strlen (fn));
283       memcpy (s, fn, strlen (fn) - 1);
284       s[strlen (fn) - 1] = 0;
285
286       f = popen (s, mode[0] == 'r' ? "r" : "w");
287
288       local_free (s);
289
290       return f;
291     }
292   else
293 #endif
294     {
295       FILE *f = fopen (fn, mode);
296
297       if (f && mode[0] == 'w')
298         setvbuf (f, NULL, _IOLBF, 0);
299
300       return f;
301     }
302 }
303
304 /* Counterpart to fn_open that closes file F with name FN; returns 0
305    on success, EOF on failure.  If EOF is returned, errno is set to a
306    sensible value. */
307 int
308 fn_close (const char *fn, FILE *f)
309 {
310   if (fileno (f) == STDIN_FILENO
311       || fileno (f) == STDOUT_FILENO
312       || fileno (f) == STDERR_FILENO)
313     return 0;
314 #if HAVE_POPEN
315   else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
316     {
317       pclose (f);
318       return 0;
319     }
320 #endif
321   else
322     return fclose (f);
323 }
324
325 /* Creates a new file named FN with the given PERMISSIONS bits,
326    and returns a stream for it or a null pointer on failure.
327    MODE should be "w" or "wb". */
328 FILE *
329 create_stream (const char *fn, const char *mode, mode_t permissions)
330 {
331   int fd;
332   FILE *stream;
333
334   fd = open (fn, O_WRONLY | O_CREAT | O_TRUNC, permissions);
335   if (fd < 0)
336     return NULL;
337
338   stream = fdopen (fd, mode);
339   if (stream == NULL)
340     {
341       int save_errno = errno;
342       close (fd);
343       errno = save_errno;
344     }
345
346   return stream;
347 }
348
349 #if !(defined _WIN32 || defined __WIN32__)
350 /* A file's identity. */
351 struct file_identity
352 {
353   dev_t device;               /* Device number. */
354   ino_t inode;                /* Inode number. */
355 };
356
357 /* Returns a pointer to a dynamically allocated structure whose
358    value can be used to tell whether two files are actually the
359    same file.  Returns a null pointer if no information about the
360    file is available, perhaps because it does not exist.  The
361    caller is responsible for freeing the structure with
362    fn_free_identity() when finished. */
363 struct file_identity *
364 fn_get_identity (const char *file_name)
365 {
366   struct stat s;
367
368   if (stat (file_name, &s) == 0)
369     {
370       struct file_identity *identity = xmalloc (sizeof *identity);
371       identity->device = s.st_dev;
372       identity->inode = s.st_ino;
373       return identity;
374     }
375   else
376     return NULL;
377 }
378
379 /* Frees IDENTITY obtained from fn_get_identity(). */
380 void
381 fn_free_identity (struct file_identity *identity)
382 {
383   free (identity);
384 }
385
386 /* Compares A and B, returning a strcmp()-type result. */
387 int
388 fn_compare_file_identities (const struct file_identity *a,
389                             const struct file_identity *b)
390 {
391   assert (a != NULL);
392   assert (b != NULL);
393   if (a->device != b->device)
394     return a->device < b->device ? -1 : 1;
395   else
396     return a->inode < b->inode ? -1 : a->inode > b->inode;
397 }
398 #else /* Windows */
399 /* A file's identity. */
400 struct file_identity
401 {
402   char *normalized_file_name;  /* File's normalized name. */
403 };
404
405 /* Returns a pointer to a dynamically allocated structure whose
406    value can be used to tell whether two files are actually the
407    same file.  Returns a null pointer if no information about the
408    file is available, perhaps because it does not exist.  The
409    caller is responsible for freeing the structure with
410    fn_free_identity() when finished. */
411 struct file_identity *
412 fn_get_identity (const char *file_name)
413 {
414   struct file_identity *identity = xmalloc (sizeof *identity);
415   char cname[PATH_MAX];
416
417   if (GetFullPathName (file_name, sizeof cname, cname, NULL))
418     identity->normalized_file_name = xstrdup (cname);
419   else
420     identity->normalized_file_name = xstrdup (file_name);
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->normalized_file_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   return strcasecmp (a->normalized_file_name, b->normalized_file_name);
442 }
443 #endif /* Windows */