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