Reform string library.
[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 = 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
180    If PREFIX is non-NULL, then it is prefixed to each file name;
181    i.e., it looks like PREFIX/PATH_COMPONENT/NAME.  This is not
182    done with absolute directories in the path. */
183 char *
184 fn_search_path (const char *base_name, const char *path_, const char *prefix)
185 {
186   struct string path;
187   struct substring dir_;
188   struct string file = DS_EMPTY_INITIALIZER;
189   size_t save_idx = 0;
190
191   if (fn_is_absolute (base_name))
192     return fn_tilde_expand (base_name);
193
194   /* Interpolate environment variables. */
195   ds_init_cstr (&path, path_);
196   fn_interp_vars (ds_ss (&path), fn_getenv, &path);
197
198   verbose_msg (2, _("searching for \"%s\" in path \"%s\""),
199                base_name, ds_cstr (&path));
200   while (ds_separate (&path, ss_cstr (":"), &save_idx, &dir_))
201     {
202       struct string dir;
203
204       /* Do tilde expansion. */
205       ds_init_substring (&dir, dir_);
206       if (ds_first (&dir) == '~') 
207         {
208           char *tmp_str = fn_tilde_expand (ds_cstr (&dir));
209           ds_assign_cstr (&dir, tmp_str);
210           free (tmp_str); 
211         }
212
213       /* Construct file name. */
214       ds_clear (&file);
215       if (prefix != NULL && !fn_is_absolute (ds_cstr (&dir)))
216         {
217           ds_put_cstr (&file, prefix);
218           ds_put_char (&file, '/');
219         }
220       ds_put_cstr (&file, ds_cstr (&dir));
221       if (!ds_is_empty (&file) && ds_last (&file) != '/')
222         ds_put_char (&file, '/');
223       ds_put_cstr (&file, base_name);
224       ds_destroy (&dir);
225
226       /* Check whether file exists. */
227       if (fn_exists (ds_cstr (&file)))
228         {
229           verbose_msg (2, _("...found \"%s\""), ds_cstr (&file));
230           ds_destroy (&path);
231           return ds_cstr (&file);
232         }
233     }
234
235   /* Failure. */
236   verbose_msg (2, _("...not found"));
237   ds_destroy (&path);
238   ds_destroy (&file);
239   return NULL;
240 }
241
242 /* fn_normalize(): This very OS-dependent routine canonicalizes
243    file name FN1.  The file name should not need to be the name of an
244    existing file.  Returns a malloc()'d copy of the canonical name.
245    This function must always succeed; if it needs to bail out then it
246    should return xstrdup(FN1).  */
247 #ifdef unix
248 char *
249 fn_normalize (const char *file_name)
250 {
251   const char *src;
252   char *fn1, *fn2, *dest;
253   int maxlen;
254
255   if (fn_is_special (file_name))
256     return xstrdup (file_name);
257   
258   fn1 = fn_tilde_expand (file_name);
259
260   /* Follow symbolic links. */
261   for (;;)
262     {
263       fn2 = fn1;
264       fn1 = fn_readlink (fn1);
265       if (!fn1)
266         {
267           fn1 = fn2;
268           break;
269         }
270       free (fn2);
271     }
272
273   maxlen = strlen (fn1) * 2;
274   if (maxlen < 31)
275     maxlen = 31;
276   dest = fn2 = xmalloc (maxlen + 1);
277   src = fn1;
278
279   if (*src == '/')
280     *dest++ = *src++;
281   else
282     {
283       errno = 0;
284       while (getcwd (dest, maxlen - (dest - fn2)) == NULL && errno == ERANGE)
285         {
286           maxlen *= 2;
287           dest = fn2 = xrealloc (fn2, maxlen + 1);
288           errno = 0;
289         }
290       if (errno)
291         {
292           free (fn1);
293           free (fn2);
294           return NULL;
295         }
296       dest = strchr (fn2, '\0');
297       if (dest - fn2 >= maxlen)
298         {
299           int ofs = dest - fn2;
300           maxlen *= 2;
301           fn2 = xrealloc (fn2, maxlen + 1);
302           dest = fn2 + ofs;
303         }
304       if (dest[-1] != '/')
305         *dest++ = '/';
306     }
307
308   for (;;)
309     {
310       int c, f;
311
312       c = *src++;
313
314       f = 0;
315       if (c == '/' || c == 0)
316         {
317           /* remove `./', `../' from directory */
318           if (dest[-1] == '.' && dest[-2] == '/')
319             dest--;
320           else if (dest[-1] == '.' && dest[-2] == '.' && dest[-3] == '/')
321             {
322               dest -= 3;
323               if (dest == fn2)
324                 dest++;
325               while (dest[-1] != '/')
326                 dest--;
327             }
328           else if (dest[-1] != '/')     /* remove extra slashes */
329             f = 1;
330
331           if (c == 0)
332             {
333               if (dest[-1] == '/' && dest > fn2 + 1)
334                 dest--;
335               *dest = 0;
336               free (fn1);
337
338               return xrealloc (fn2, strlen (fn2) + 1);
339             }
340         }
341       else
342         f = 1;
343
344       if (f)
345         {
346           if (dest - fn2 >= maxlen)
347             {
348               int ofs = dest - fn2;
349               maxlen *= 2;
350               fn2 = xrealloc (fn2, maxlen + 1);
351               dest = fn2 + ofs;
352             }
353           *dest++ = c;
354         }
355     }
356 }
357 #elif defined (__WIN32__)
358 char *
359 fn_normalize (const char *fn1)
360 {
361   DWORD len;
362   DWORD success;
363   char *fn2;
364
365   /* Don't change special file names. */
366   if (is_special_file_name (file_name))
367     return xstrdup (file_name);
368
369   /* First find the required buffer length. */
370   len = GetFullPathName (fn1, 0, NULL, NULL);
371   if (!len)
372     {
373       fn2 = xstrdup (fn1);
374       return fn2;
375     }
376
377   /* Then make a buffer that big. */
378   fn2 = xmalloc (len);
379   success = GetFullPathName (fn1, len, fn2, NULL);
380   if (success >= len || success == 0)
381     {
382       free (fn2);
383       fn2 = xstrdup (fn1);
384       return fn2;
385     }
386   return fn2;
387 }
388 #elif __BORLANDC__
389 char *
390 fn_normalize (const char *fn1)
391 {
392   char *fn2 = _fullpath (NULL, fn1, 0);
393   if (fn2)
394     {
395       char *cp;
396       for (cp = fn2; *cp; cp++)
397         *cp = toupper ((unsigned char) (*cp));
398       return fn2;
399     }
400   return xstrdup (fn1);
401 }
402 #elif __DJGPP__
403 char *
404 fn_normalize (const char *fn1)
405 {
406   char *fn2 = xmalloc (1024);
407   _fixpath (fn1, fn2);
408   fn2 = xrealloc (fn2, strlen (fn2) + 1);
409   return fn2;
410 }
411 #else /* not Lose32, Unix, or DJGPP */
412 char *
413 fn_normalize (const char *fn)
414 {
415   return xstrdup (fn);
416 }
417 #endif /* not Lose32, Unix, or DJGPP */
418
419 /* Returns the directory part of FILE_NAME, as a malloc()'d
420    string. */
421 char *
422 fn_dir_name (const char *file_name)
423 {
424   const char *p;
425   char *s;
426   size_t len;
427
428   len = strlen (file_name);
429   if (len == 1 && file_name[0] == '/')
430     p = file_name + 1;
431   else if (len && file_name[len - 1] == '/')
432     p = buf_find_reverse (file_name, len - 1, file_name + len - 1, 1);
433   else
434     p = strrchr (file_name, '/');
435   if (p == NULL)
436     p = file_name;
437
438   s = xmalloc (p - file_name + 1);
439   memcpy (s, file_name, p - file_name);
440   s[p - file_name] = 0;
441
442   return s;
443 }
444
445 /* Returns the extension part of FILE_NAME as a malloc()'d string.
446    If FILE_NAME does not have an extension, returns an empty
447    string. */
448 char *
449 fn_extension (const char *file_name) 
450 {
451   const char *extension = strrchr (file_name, '.');
452   if (extension == NULL)
453     extension = "";
454   return xstrdup (extension);
455 }
456 \f
457 #if unix
458 /* Returns the current working directory, as a malloc()'d string.
459    From libc.info. */
460 char *
461 fn_get_cwd (void)
462 {
463   int size = 100;
464   char *buffer = xmalloc (size);
465      
466   for (;;)
467     {
468       char *value = getcwd (buffer, size);
469       if (value != 0)
470         return buffer;
471
472       size *= 2;
473       free (buffer);
474       buffer = xmalloc (size);
475     }
476 }
477 #else
478 char *
479 fn_get_cwd (void)
480 {
481   int size = 2;
482   char *buffer = xmalloc (size);
483   if ( buffer) 
484     {
485       buffer[0]='.';
486       buffer[1]='\0';
487     }
488
489   return buffer;
490      
491 }
492 #endif
493 \f
494 /* Find out information about files. */
495
496 /* Returns nonzero iff NAME specifies an absolute file name. */
497 int
498 fn_is_absolute (const char *name)
499 {
500 #ifdef unix
501   if (name[0] == '/'
502       || !strncmp (name, "./", 2)
503       || !strncmp (name, "../", 3)
504       || name[0] == '~')
505     return 1;
506 #elif defined (__MSDOS__)
507   if (name[0] == '\\'
508       || !strncmp (name, ".\\", 2)
509       || !strncmp (name, "..\\", 3)
510       || (name[0] && name[1] == ':'))
511     return 1;
512 #endif
513   
514   return 0;
515 }
516   
517 /* Returns 1 if FILE_NAME is a virtual file that doesn't
518    really exist on disk, 0 if it's a real file name. */
519 int
520 fn_is_special (const char *file_name)
521 {
522   if (!strcmp (file_name, "-") || !strcmp (file_name, "stdin")
523       || !strcmp (file_name, "stdout") || !strcmp (file_name, "stderr")
524 #ifdef unix
525       || file_name[0] == '|'
526       || (*file_name && file_name[strlen (file_name) - 1] == '|')
527 #endif
528       )
529     return 1;
530
531   return 0;
532 }
533
534 /* Returns nonzero if file with name NAME exists. */
535 int
536 fn_exists (const char *name)
537 {
538 #ifdef unix
539   struct stat temp;
540
541   return stat (name, &temp) == 0;
542 #else
543   FILE *f = fopen (name, "r");
544   if (!f)
545     return 0;
546   fclose (f);
547   return 1;
548 #endif
549 }
550
551 /* Returns the symbolic link value for FILE_NAME as a dynamically
552    allocated buffer, or a null pointer on failure. */
553 char *
554 fn_readlink (const char *file_name)
555 {
556   return xreadlink (file_name, 32);
557 }
558 \f
559 /* Environment variables. */
560
561 /* Simulates $VER and $ARCH environment variables. */
562 const char *
563 fn_getenv (const char *s)
564 {
565   if (!strcmp (s, "VER"))
566     return fn_getenv_default ("STAT_VER", bare_version);
567   else if (!strcmp (s, "ARCH"))
568     return fn_getenv_default ("STAT_ARCH", host_system);
569   else
570     return getenv (s);
571 }
572
573 /* Returns getenv(KEY) if that's non-NULL; else returns DEF. */
574 const char *
575 fn_getenv_default (const char *key, const char *def)
576 {
577   const char *value = getenv (key);
578   return value ? value : def;
579 }
580 \f
581 /* Basic file handling. */
582
583 /* Used for giving an error message on a set_safer security
584    violation. */
585 static FILE *
586 safety_violation (const char *fn)
587 {
588   msg (SE, _("Not opening pipe file `%s' because SAFER option set."), fn);
589   errno = EPERM;
590   return NULL;
591 }
592
593 /* As a general comment on the following routines, a `sensible value'
594    for errno includes 0 if there is no associated system error.  The
595    routines will only set errno to 0 if there is an error in a
596    callback that sets errno to 0; they themselves won't. */
597
598 /* File open routine that understands `-' as stdin/stdout and `|cmd'
599    as a pipe to command `cmd'.  Returns resultant FILE on success,
600    NULL on failure.  If NULL is returned then errno is set to a
601    sensible value.  */
602 FILE *
603 fn_open (const char *fn, const char *mode)
604 {
605   assert (mode[0] == 'r' || mode[0] == 'w');
606
607   if (mode[0] == 'r' && (!strcmp (fn, "stdin") || !strcmp (fn, "-"))) 
608     return stdin;
609   else if (mode[0] == 'w' && (!strcmp (fn, "stdout") || !strcmp (fn, "-")))
610     return stdout;
611   else if (mode[0] == 'w' && !strcmp (fn, "stderr"))
612     return stderr;
613   
614 #ifdef unix
615   if (fn[0] == '|')
616     {
617       if (get_safer_mode ())
618         return safety_violation (fn);
619
620       return popen (&fn[1], mode);
621     }
622   else if (*fn && fn[strlen (fn) - 1] == '|')
623     {
624       char *s;
625       FILE *f;
626
627       if (get_safer_mode ())
628         return safety_violation (fn);
629       
630       s = local_alloc (strlen (fn));
631       memcpy (s, fn, strlen (fn) - 1);
632       s[strlen (fn) - 1] = 0;
633       
634       f = popen (s, mode);
635
636       local_free (s);
637
638       return f;
639     }
640   else
641 #endif
642     {
643       FILE *f = fopen (fn, mode);
644
645       if (f && mode[0] == 'w')
646         setvbuf (f, NULL, _IOLBF, 0);
647
648       return f;
649     }
650 }
651
652 /* Counterpart to fn_open that closes file F with name FN; returns 0
653    on success, EOF on failure.  If EOF is returned, errno is set to a
654    sensible value. */
655 int
656 fn_close (const char *fn, FILE *f)
657 {
658   if (!strcmp (fn, "-"))
659     return 0;
660 #ifdef unix
661   else if (fn[0] == '|' || (*fn && fn[strlen (fn) - 1] == '|'))
662     {
663       pclose (f);
664       return 0;
665     }
666 #endif
667   else
668     return fclose (f);
669 }
670
671 #ifdef unix
672 /* A file's identity. */
673 struct file_identity 
674 {
675   dev_t device;               /* Device number. */
676   ino_t inode;                /* Inode number. */
677 };
678
679 /* Returns a pointer to a dynamically allocated structure whose
680    value can be used to tell whether two files are actually the
681    same file.  Returns a null pointer if no information about the
682    file is available, perhaps because it does not exist.  The
683    caller is responsible for freeing the structure with
684    fn_free_identity() when finished. */  
685 struct file_identity *
686 fn_get_identity (const char *file_name) 
687 {
688   struct stat s;
689
690   if (stat (file_name, &s) == 0) 
691     {
692       struct file_identity *identity = xmalloc (sizeof *identity);
693       identity->device = s.st_dev;
694       identity->inode = s.st_ino;
695       return identity;
696     }
697   else
698     return NULL;
699 }
700
701 /* Frees IDENTITY obtained from fn_get_identity(). */
702 void
703 fn_free_identity (struct file_identity *identity) 
704 {
705   free (identity);
706 }
707
708 /* Compares A and B, returning a strcmp()-type result. */
709 int
710 fn_compare_file_identities (const struct file_identity *a,
711                             const struct file_identity *b) 
712 {
713   assert (a != NULL);
714   assert (b != NULL);
715   if (a->device != b->device)
716     return a->device < b->device ? -1 : 1;
717   else
718     return a->inode < b->inode ? -1 : a->inode > b->inode;
719 }
720 #else /* not unix */
721 /* A file's identity. */
722 struct file_identity 
723 {
724   char *normalized_file_name;  /* File's normalized name. */
725 };
726
727 /* Returns a pointer to a dynamically allocated structure whose
728    value can be used to tell whether two files are actually the
729    same file.  Returns a null pointer if no information about the
730    file is available, perhaps because it does not exist.  The
731    caller is responsible for freeing the structure with
732    fn_free_identity() when finished. */  
733 struct file_identity *
734 fn_get_identity (const char *file_name) 
735 {
736   struct file_identity *identity = xmalloc (sizeof *identity);
737   identity->normalized_file_name = fn_normalize (file_name);
738   return identity;
739 }
740
741 /* Frees IDENTITY obtained from fn_get_identity(). */
742 void
743 fn_free_identity (struct file_identity *identity) 
744 {
745   if (identity != NULL) 
746     {
747       free (identity->normalized_file_name);
748       free (identity);
749     }
750 }
751
752 /* Compares A and B, returning a strcmp()-type result. */
753 int
754 fn_compare_file_identities (const struct file_identity *a,
755                             const struct file_identity *b) 
756 {
757   return strcmp (a->normalized_file_name, b->normalized_file_name);
758 }
759 #endif /* not unix */