d8ad1b8e402ac535432aa26f78d5f1e71466110e
[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    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, USA. */
19
20 #include <config.h>
21
22 #include "file-name.h"
23
24 #include <ctype.h>
25 #include <errno.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28
29 #include "intprops.h"
30 #include "minmax.h"
31 #include "settings.h"
32 #include "xreadlink.h"
33
34 #include <libpspp/alloc.h>
35 #include <libpspp/message.h>
36 #include <libpspp/message.h>
37 #include <libpspp/str.h>
38 #include <libpspp/verbose-msg.h>
39 #include <libpspp/version.h>
40
41 #include "gettext.h"
42 #define _(msgid) gettext (msgid)
43
44 /* PORTME: Everything in this file is system dependent. */
45
46 #ifdef unix
47 #include <pwd.h>
48 #include <unistd.h>
49 #include <sys/stat.h>
50 #include "stat-macros.h"
51 #endif
52
53 #ifdef __WIN32__
54 #define NOGDI
55 #define NOUSER
56 #define NONLS
57 #include <win32/windows.h>
58 #endif
59
60 #if __DJGPP__
61 #include <sys/stat.h>
62 #endif
63 \f
64 /* Initialization. */
65
66 const char *config_path;
67
68 void
69 fn_init (void)
70 {
71   config_path = fn_getenv_default ("STAT_CONFIG_PATH", default_config_path);
72 }
73 \f
74 /* Functions for performing operations on file names. */
75
76
77 /* Substitutes $variables in SRC, putting the result in DST,
78    properly handling the case where SRC is a substring of DST.
79    Variables are as defined by GETENV. Supports $var and ${var}
80    syntaxes; $$ substitutes as $. */
81 void 
82 fn_interp_vars (struct substring src, const char *(*getenv) (const char *),
83                 struct string *dst_)
84 {
85   struct string dst = DS_EMPTY_INITIALIZER;
86   int c;
87
88   while ((c = ss_get_char (&src)) != EOF)
89     if (c != '$') 
90       ds_put_char (&dst, c);
91     else
92       {
93         if (ss_match_char (&src, '$') || ss_is_empty (src))
94           ds_put_char (&dst, '$');
95         else
96           {
97             struct substring var_name;
98             size_t start;
99             const char *value;
100
101             if (ss_match_char (&src, '('))
102               ss_get_until (&src, ')', &var_name);
103             else if (ss_match_char (&src, '{'))
104               ss_get_until (&src, '}', &var_name);
105             else
106               ss_get_chars (&src, MIN (1, ss_span (src, ss_cstr (CC_ALNUM))),
107                             &var_name);
108
109             start = ds_length (&dst);
110             ds_put_substring (&dst, var_name);
111             value = getenv (ds_cstr (&dst) + start);
112             ds_truncate (&dst, start);
113
114             ds_put_cstr (&dst, value);
115           } 
116       }
117
118   ds_swap (&dst, dst_);
119   ds_destroy (&dst);
120 }
121
122 #ifdef unix
123 /* Expands csh tilde notation from the path INPUT into a malloc()'d
124    returned string. */
125 char *
126 fn_tilde_expand (const char *input)
127 {
128   struct string output = DS_EMPTY_INITIALIZER;
129   if (input[0] == '~')
130     {
131       const char *home = NULL;
132       const char *remainder = NULL;
133       if (input[1] == '/' || input[1] == '\0')
134         {
135           home = fn_getenv ("HOME");
136           remainder = input + 1; 
137         }
138       else
139         {
140           struct string user_name = DS_EMPTY_INITIALIZER;
141           struct passwd *pwd;
142
143           ds_assign_substring (&user_name,
144                                ss_buffer (input + 1,
145                                           strcspn (input + 1, "/")));
146           pwd = getpwnam (ds_cstr (&user_name));
147           if (pwd != NULL && pwd->pw_dir[0] != '\0')
148             {
149               home = xstrdup (pwd->pw_dir);
150               remainder = input + 1 + ds_length (&user_name);
151             }
152           ds_destroy (&user_name);
153         }
154
155       if (home != NULL) 
156         {
157           ds_put_cstr (&output, home);
158           if (*remainder != '\0')
159             ds_put_cstr (&output, remainder);
160         }
161     }
162   if (ds_is_empty (&output))
163     ds_put_cstr (&output, input);
164   return ds_cstr (&output);
165 }
166 #else /* !unix */
167 char *
168 fn_tilde_expand (const char *input)
169 {
170   return xstrdup (input);
171 }
172 #endif /* !unix */
173
174 /* Searches for a configuration file with name NAME in the path
175    given by PATH, which is tilde- and environment-interpolated.
176    Directories in PATH are delimited by ':'.  Returns the
177    malloc'd full name of the first file found, or NULL if none is
178    found. */
179 char *
180 fn_search_path (const char *base_name, const char *path_)
181 {
182   struct string path;
183   struct substring dir_;
184   struct string file = DS_EMPTY_INITIALIZER;
185   size_t save_idx = 0;
186
187   if (fn_is_absolute (base_name))
188     return fn_tilde_expand (base_name);
189
190   /* Interpolate environment variables. */
191   ds_init_cstr (&path, path_);
192   fn_interp_vars (ds_ss (&path), fn_getenv, &path);
193
194   verbose_msg (2, _("searching for \"%s\" in path \"%s\""),
195                base_name, ds_cstr (&path));
196   while (ds_separate (&path, ss_cstr (":"), &save_idx, &dir_))
197     {
198       struct string dir;
199
200       /* Do tilde expansion. */
201       ds_init_substring (&dir, dir_);
202       if (ds_first (&dir) == '~') 
203         {
204           char *tmp_str = fn_tilde_expand (ds_cstr (&dir));
205           ds_assign_cstr (&dir, tmp_str);
206           free (tmp_str); 
207         }
208
209       /* Construct file name. */
210       ds_clear (&file);
211       ds_put_cstr (&file, ds_cstr (&dir));
212       if (!ds_is_empty (&file) && ds_last (&file) != '/')
213         ds_put_char (&file, '/');
214       ds_put_cstr (&file, base_name);
215       ds_destroy (&dir);
216
217       /* Check whether file exists. */
218       if (fn_exists (ds_cstr (&file)))
219         {
220           verbose_msg (2, _("...found \"%s\""), ds_cstr (&file));
221           ds_destroy (&path);
222           return ds_cstr (&file);
223         }
224     }
225
226   /* Failure. */
227   verbose_msg (2, _("...not found"));
228   ds_destroy (&path);
229   ds_destroy (&file);
230   return NULL;
231 }
232
233 /* fn_normalize(): This very OS-dependent routine canonicalizes
234    file name FN1.  The file name should not need to be the name of an
235    existing file.  Returns a malloc()'d copy of the canonical name.
236    This function must always succeed; if it needs to bail out then it
237    should return xstrdup(FN1).  */
238 #ifdef unix
239 char *
240 fn_normalize (const char *file_name)
241 {
242   const char *src;
243   char *fn1, *fn2, *dest;
244   int maxlen;
245
246   if (fn_is_special (file_name))
247     return xstrdup (file_name);
248   
249   fn1 = fn_tilde_expand (file_name);
250
251   /* Follow symbolic links. */
252   for (;;)
253     {
254       fn2 = fn1;
255       fn1 = fn_readlink (fn1);
256       if (!fn1)
257         {
258           fn1 = fn2;
259           break;
260         }
261       free (fn2);
262     }
263
264   maxlen = strlen (fn1) * 2;
265   if (maxlen < 31)
266     maxlen = 31;
267   dest = fn2 = xmalloc (maxlen + 1);
268   src = fn1;
269
270   if (*src == '/')
271     *dest++ = *src++;
272   else
273     {
274       errno = 0;
275       while (getcwd (dest, maxlen - (dest - fn2)) == NULL && errno == ERANGE)
276         {
277           maxlen *= 2;
278           dest = fn2 = xrealloc (fn2, maxlen + 1);
279           errno = 0;
280         }
281       if (errno)
282         {
283           free (fn1);
284           free (fn2);
285           return NULL;
286         }
287       dest = strchr (fn2, '\0');
288       if (dest - fn2 >= maxlen)
289         {
290           int ofs = dest - fn2;
291           maxlen *= 2;
292           fn2 = xrealloc (fn2, maxlen + 1);
293           dest = fn2 + ofs;
294         }
295       if (dest[-1] != '/')
296         *dest++ = '/';
297     }
298
299   for (;;)
300     {
301       int c, f;
302
303       c = *src++;
304
305       f = 0;
306       if (c == '/' || c == 0)
307         {
308           /* remove `./', `../' from directory */
309           if (dest[-1] == '.' && dest[-2] == '/')
310             dest--;
311           else if (dest[-1] == '.' && dest[-2] == '.' && dest[-3] == '/')
312             {
313               dest -= 3;
314               if (dest == fn2)
315                 dest++;
316               while (dest[-1] != '/')
317                 dest--;
318             }
319           else if (dest[-1] != '/')     /* remove extra slashes */
320             f = 1;
321
322           if (c == 0)
323             {
324               if (dest[-1] == '/' && dest > fn2 + 1)
325                 dest--;
326               *dest = 0;
327               free (fn1);
328
329               return xrealloc (fn2, strlen (fn2) + 1);
330             }
331         }
332       else
333         f = 1;
334
335       if (f)
336         {
337           if (dest - fn2 >= maxlen)
338             {
339               int ofs = dest - fn2;
340               maxlen *= 2;
341               fn2 = xrealloc (fn2, maxlen + 1);
342               dest = fn2 + ofs;
343             }
344           *dest++ = c;
345         }
346     }
347 }
348 #elif defined (__WIN32__)
349 char *
350 fn_normalize (const char *fn1)
351 {
352   DWORD len;
353   DWORD success;
354   char *fn2;
355
356   /* Don't change special file names. */
357   if (is_special_file_name (file_name))
358     return xstrdup (file_name);
359
360   /* First find the required buffer length. */
361   len = GetFullPathName (fn1, 0, NULL, NULL);
362   if (!len)
363     {
364       fn2 = xstrdup (fn1);
365       return fn2;
366     }
367
368   /* Then make a buffer that big. */
369   fn2 = xmalloc (len);
370   success = GetFullPathName (fn1, len, fn2, NULL);
371   if (success >= len || success == 0)
372     {
373       free (fn2);
374       fn2 = xstrdup (fn1);
375       return fn2;
376     }
377   return fn2;
378 }
379 #elif __BORLANDC__
380 char *
381 fn_normalize (const char *fn1)
382 {
383   char *fn2 = _fullpath (NULL, fn1, 0);
384   if (fn2)
385     {
386       char *cp;
387       for (cp = fn2; *cp; cp++)
388         *cp = toupper ((unsigned char) (*cp));
389       return fn2;
390     }
391   return xstrdup (fn1);
392 }
393 #elif __DJGPP__
394 char *
395 fn_normalize (const char *fn1)
396 {
397   char *fn2 = xmalloc (1024);
398   _fixpath (fn1, fn2);
399   fn2 = xrealloc (fn2, strlen (fn2) + 1);
400   return fn2;
401 }
402 #else /* not Lose32, Unix, or DJGPP */
403 char *
404 fn_normalize (const char *fn)
405 {
406   return xstrdup (fn);
407 }
408 #endif /* not Lose32, Unix, or DJGPP */
409
410 /* Returns the directory part of FILE_NAME, as a malloc()'d
411    string. */
412 char *
413 fn_dir_name (const char *file_name)
414 {
415   const char *p;
416   char *s;
417   size_t len;
418
419   len = strlen (file_name);
420   if (len == 1 && file_name[0] == '/')
421     p = file_name + 1;
422   else if (len && file_name[len - 1] == '/')
423     p = buf_find_reverse (file_name, len - 1, file_name + len - 1, 1);
424   else
425     p = strrchr (file_name, '/');
426   if (p == NULL)
427     p = file_name;
428
429   s = xmalloc (p - file_name + 1);
430   memcpy (s, file_name, p - file_name);
431   s[p - file_name] = 0;
432
433   return s;
434 }
435
436 /* Returns the extension part of FILE_NAME as a malloc()'d string.
437    If FILE_NAME does not have an extension, returns an empty
438    string. */
439 char *
440 fn_extension (const char *file_name) 
441 {
442   const char *extension = strrchr (file_name, '.');
443   if (extension == NULL)
444     extension = "";
445   return xstrdup (extension);
446 }
447 \f
448 #if unix
449 /* Returns the current working directory, as a malloc()'d string.
450    From libc.info. */
451 char *
452 fn_get_cwd (void)
453 {
454   int size = 100;
455   char *buffer = xmalloc (size);
456      
457   for (;;)
458     {
459       char *value = getcwd (buffer, size);
460       if (value != 0)
461         return buffer;
462
463       size *= 2;
464       free (buffer);
465       buffer = xmalloc (size);
466     }
467 }
468 #else
469 char *
470 fn_get_cwd (void)
471 {
472   int size = 2;
473   char *buffer = xmalloc (size);
474   if ( buffer) 
475     {
476       buffer[0]='.';
477       buffer[1]='\0';
478     }
479
480   return buffer;
481      
482 }
483 #endif
484 \f
485 /* Find out information about files. */
486
487 /* Returns true iff NAME specifies an absolute file name. */
488 bool
489 fn_is_absolute (const char *name)
490 {
491 #ifdef unix
492   if (name[0] == '/'
493       || !strncmp (name, "./", 2)
494       || !strncmp (name, "../", 3)
495       || name[0] == '~')
496     return true;
497 #elif defined (__MSDOS__)
498   if (name[0] == '\\'
499       || !strncmp (name, ".\\", 2)
500       || !strncmp (name, "..\\", 3)
501       || (name[0] && name[1] == ':'))
502     return true;
503 #endif
504   
505   return false;
506 }
507   
508 /* Returns true if FILE_NAME is a virtual file that doesn't
509    really exist on disk, false if it's a real file name. */
510 bool
511 fn_is_special (const char *file_name)
512 {
513   if (!strcmp (file_name, "-") || !strcmp (file_name, "stdin")
514       || !strcmp (file_name, "stdout") || !strcmp (file_name, "stderr")
515 #ifdef unix
516       || file_name[0] == '|'
517       || (*file_name && file_name[strlen (file_name) - 1] == '|')
518 #endif
519       )
520     return true;
521
522   return false;
523 }
524
525 /* Returns true if file with name NAME exists. */
526 bool
527 fn_exists (const char *name)
528 {
529 #ifdef unix
530   struct stat temp;
531
532   return stat (name, &temp) == 0;
533 #else
534   FILE *f = fopen (name, "r");
535   if (!f)
536     return false;
537   fclose (f);
538   return true;
539 #endif
540 }
541
542 /* Returns the symbolic link value for FILE_NAME as a dynamically
543    allocated buffer, or a null pointer on failure. */
544 char *
545 fn_readlink (const char *file_name)
546 {
547   return xreadlink (file_name, 32);
548 }
549 \f
550 /* Environment variables. */
551
552 /* Simulates $VER and $ARCH environment variables. */
553 const char *
554 fn_getenv (const char *s)
555 {
556   if (!strcmp (s, "VER"))
557     return fn_getenv_default ("STAT_VER", bare_version);
558   else if (!strcmp (s, "ARCH"))
559     return fn_getenv_default ("STAT_ARCH", host_system);
560   else
561     return getenv (s);
562 }
563
564 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
565 const char *
566 fn_getenv_default (const char *key, const char *def)
567 {
568   const char *value = getenv (key);
569   return value ? value : def;
570 }
571 \f
572 /* Basic file handling. */
573
574 /* Used for giving an error message on a set_safer security
575    violation. */
576 static FILE *
577 safety_violation (const char *fn)
578 {
579   msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
580   errno = EPERM;
581   return NULL;
582 }
583
584 /* As a general comment on the following routines, a `sensible value'
585    for errno includes 0 if there is no associated system error.  The
586    routines will only set errno to 0 if there is an error in a
587    callback that sets errno to 0; they themselves won't. */
588
589 /* File open routine that understands `-' as stdin/stdout and `|cmd'
590    as a pipe to command `cmd'.  Returns resultant FILE on success,
591    NULL on failure.  If NULL is returned then errno is set to a
592    sensible value.  */
593 FILE *
594 fn_open (const char *fn, const char *mode)
595 {
596   assert (mode[0] == 'r' || mode[0] == 'w');
597
598   if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-"))) 
599     return stdin;
600   else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
601     return stdout;
602   else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
603     return stderr;
604   
605 #ifdef unix
606   if (fn[0] == '|')
607     {
608       if (get_safer_mode ())
609         return safety_violation (fn);
610
611       return popen (&fn[1], mode);
612     }
613   else if (*fn && fn[strlen (fn) - 1] == '|')
614     {
615       char *s;
616       FILE *f;
617
618       if (get_safer_mode ())
619         return safety_violation (fn);
620       
621       s = local_alloc (strlen (fn));
622       memcpy (s, fn, strlen (fn) - 1);
623       s[strlen (fn) - 1] = 0;
624       
625       f = popen (s, mode);
626
627       local_free (s);
628
629       return f;
630     }
631   else
632 #endif
633     {
634       FILE *f = fopen (fn, mode);
635
636       if (f && mode[0] == 'w')
637         setvbuf (f, NULL, _IOLBF, 0);
638
639       return f;
640     }
641 }
642
643 /* Counterpart to fn_open that closes file F with name FN; returns 0
644    on success, EOF on failure.  If EOF is returned, errno is set to a
645    sensible value. */
646 int
647 fn_close (const char *fn, FILE *f)
648 {
649   if (!strcmp (fn, "-"))
650     return 0;
651 #ifdef unix
652   else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
653     {
654       pclose (f);
655       return 0;
656     }
657 #endif
658   else
659     return fclose (f);
660 }
661
662 #ifdef unix
663 /* A file's identity. */
664 struct file_identity 
665 {
666   dev_t device;               /* Device number. */
667   ino_t inode;                /* Inode number. */
668 };
669
670 /* Returns a pointer to a dynamically allocated structure whose
671    value can be used to tell whether two files are actually the
672    same file.  Returns a null pointer if no information about the
673    file is available, perhaps because it does not exist.  The
674    caller is responsible for freeing the structure with
675    fn_free_identity() when finished. */  
676 struct file_identity *
677 fn_get_identity (const char *file_name) 
678 {
679   struct stat s;
680
681   if (stat (file_name, &s) == 0) 
682     {
683       struct file_identity *identity = xmalloc (sizeof *identity);
684       identity->device = s.st_dev;
685       identity->inode = s.st_ino;
686       return identity;
687     }
688   else
689     return NULL;
690 }
691
692 /* Frees IDENTITY obtained from fn_get_identity(). */
693 void
694 fn_free_identity (struct file_identity *identity) 
695 {
696   free (identity);
697 }
698
699 /* Compares A and B, returning a strcmp()-type result. */
700 int
701 fn_compare_file_identities (const struct file_identity *a,
702                             const struct file_identity *b) 
703 {
704   assert (a != NULL);
705   assert (b != NULL);
706   if (a->device != b->device)
707     return a->device < b->device ? -1 : 1;
708   else
709     return a->inode < b->inode ? -1 : a->inode > b->inode;
710 }
711 #else /* not unix */
712 /* A file's identity. */
713 struct file_identity 
714 {
715   char *normalized_file_name;  /* File's normalized name. */
716 };
717
718 /* Returns a pointer to a dynamically allocated structure whose
719    value can be used to tell whether two files are actually the
720    same file.  Returns a null pointer if no information about the
721    file is available, perhaps because it does not exist.  The
722    caller is responsible for freeing the structure with
723    fn_free_identity() when finished. */  
724 struct file_identity *
725 fn_get_identity (const char *file_name) 
726 {
727   struct file_identity *identity = xmalloc (sizeof *identity);
728   identity->normalized_file_name = fn_normalize (file_name);
729   return identity;
730 }
731
732 /* Frees IDENTITY obtained from fn_get_identity(). */
733 void
734 fn_free_identity (struct file_identity *identity) 
735 {
736   if (identity != NULL) 
737     {
738       free (identity->normalized_file_name);
739       free (identity);
740     }
741 }
742
743 /* Compares A and B, returning a strcmp()-type result. */
744 int
745 fn_compare_file_identities (const struct file_identity *a,
746                             const struct file_identity *b) 
747 {
748   return strcmp (a->normalized_file_name, b->normalized_file_name);
749 }
750 #endif /* not unix */