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