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