Do not follow symbolic links for G_FILE_TEST_SYMLINK. Also fixed the
[platform/upstream/glib.git] / glib / gfileutils.c
1 /* gfileutils.c - File utility functions
2  *
3  *  Copyright 2000 Red Hat, Inc.
4  *
5  * GLib is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU Lesser 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  * GLib is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with GLib; see the file COPYING.LIB.  If not,
17  * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  *   Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include "glib.h"
24
25 #include <sys/stat.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <fcntl.h>
37 #include <stdlib.h>
38
39 #ifdef G_OS_WIN32
40 #include <io.h>
41 #ifndef F_OK
42 #define F_OK 0
43 #define X_OK 1
44 #define W_OK 2
45 #define R_OK 4
46 #endif /* !F_OK */
47
48 #ifndef S_ISREG
49 #define S_ISREG(mode) ((mode)&_S_IFREG)
50 #endif
51
52 #ifndef S_ISDIR
53 #define S_ISDIR(mode) ((mode)&_S_IFDIR)
54 #endif
55
56 #endif /* G_OS_WIN32 */
57
58 #ifndef S_ISLNK
59 #define S_ISLNK(x) 0
60 #endif
61
62 #ifndef O_BINARY
63 #define O_BINARY 0
64 #endif
65
66 #include "glibintl.h"
67
68 /**
69  * g_file_test:
70  * @filename: a filename to test
71  * @test: bitfield of #GFileTest flags
72  * 
73  * Returns %TRUE if any of the tests in the bitfield @test are
74  * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS | 
75  * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists; 
76  * the check whether it's a directory doesn't matter since the existence 
77  * test is %TRUE. With the current set of available tests, there's no point
78  * passing in more than one test at a time.
79  * 
80  * Apart from #G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
81  * so for a symbolic link to a regular file g_file_test() will return
82  * %TRUE for both #G_FILE_TEST_IS_SYMLINK and #G_FILE_TEST_IS_REGULAR.
83  *
84  * Return value: whether a test was %TRUE
85  **/
86 gboolean
87 g_file_test (const gchar *filename,
88              GFileTest    test)
89 {
90   if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
91     return TRUE;
92   
93   if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
94     return TRUE;
95
96   if (test & G_FILE_TEST_IS_SYMLINK)
97     {
98       struct stat s;
99
100       if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
101         return TRUE;
102     }
103   
104   if (test & (G_FILE_TEST_IS_REGULAR | G_FILE_TEST_IS_DIR))
105     {
106       struct stat s;
107       
108       if (stat (filename, &s) == 0)
109         {
110           if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
111             return TRUE;
112           
113           if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
114             return TRUE;
115         }
116     }
117
118   return FALSE;
119 }
120
121 GQuark
122 g_file_error_quark (void)
123 {
124   static GQuark q = 0;
125   if (q == 0)
126     q = g_quark_from_static_string ("g-file-error-quark");
127
128   return q;
129 }
130
131 /**
132  * g_file_error_from_errno:
133  * @err_no: an "errno" value
134  * 
135  * Gets a #GFileError constant based on the passed-in @errno.
136  * For example, if you pass in %EEXIST this function returns
137  * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
138  * assume that all #GFileError values will exist.
139  *
140  * Normally a #GFileError value goes into a #GError returned
141  * from a function that manipulates files. So you would use
142  * g_file_error_from_errno() when constructing a #GError.
143  * 
144  * Return value: #GFileError corresponding to the given @errno
145  **/
146 GFileError
147 g_file_error_from_errno (gint err_no)
148 {
149   switch (err_no)
150     {
151 #ifdef EEXIST
152     case EEXIST:
153       return G_FILE_ERROR_EXIST;
154       break;
155 #endif
156
157 #ifdef EISDIR
158     case EISDIR:
159       return G_FILE_ERROR_ISDIR;
160       break;
161 #endif
162
163 #ifdef EACCES
164     case EACCES:
165       return G_FILE_ERROR_ACCES;
166       break;
167 #endif
168
169 #ifdef ENAMETOOLONG
170     case ENAMETOOLONG:
171       return G_FILE_ERROR_NAMETOOLONG;
172       break;
173 #endif
174
175 #ifdef ENOENT
176     case ENOENT:
177       return G_FILE_ERROR_NOENT;
178       break;
179 #endif
180
181 #ifdef ENOTDIR
182     case ENOTDIR:
183       return G_FILE_ERROR_NOTDIR;
184       break;
185 #endif
186
187 #ifdef ENXIO
188     case ENXIO:
189       return G_FILE_ERROR_NXIO;
190       break;
191 #endif
192
193 #ifdef ENODEV
194     case ENODEV:
195       return G_FILE_ERROR_NODEV;
196       break;
197 #endif
198
199 #ifdef EROFS
200     case EROFS:
201       return G_FILE_ERROR_ROFS;
202       break;
203 #endif
204
205 #ifdef ETXTBSY
206     case ETXTBSY:
207       return G_FILE_ERROR_TXTBSY;
208       break;
209 #endif
210
211 #ifdef EFAULT
212     case EFAULT:
213       return G_FILE_ERROR_FAULT;
214       break;
215 #endif
216
217 #ifdef ELOOP
218     case ELOOP:
219       return G_FILE_ERROR_LOOP;
220       break;
221 #endif
222
223 #ifdef ENOSPC
224     case ENOSPC:
225       return G_FILE_ERROR_NOSPC;
226       break;
227 #endif
228
229 #ifdef ENOMEM
230     case ENOMEM:
231       return G_FILE_ERROR_NOMEM;
232       break;
233 #endif
234
235 #ifdef EMFILE
236     case EMFILE:
237       return G_FILE_ERROR_MFILE;
238       break;
239 #endif
240
241 #ifdef ENFILE
242     case ENFILE:
243       return G_FILE_ERROR_NFILE;
244       break;
245 #endif
246
247 #ifdef EBADF
248     case EBADF:
249       return G_FILE_ERROR_BADF;
250       break;
251 #endif
252
253 #ifdef EINVAL
254     case EINVAL:
255       return G_FILE_ERROR_INVAL;
256       break;
257 #endif
258
259 #ifdef EPIPE
260     case EPIPE:
261       return G_FILE_ERROR_PIPE;
262       break;
263 #endif
264
265 #ifdef EAGAIN
266     case EAGAIN:
267       return G_FILE_ERROR_AGAIN;
268       break;
269 #endif
270
271 #ifdef EINTR
272     case EINTR:
273       return G_FILE_ERROR_INTR;
274       break;
275 #endif
276
277 #ifdef EIO
278     case EIO:
279       return G_FILE_ERROR_IO;
280       break;
281 #endif
282
283 #ifdef EPERM
284     case EPERM:
285       return G_FILE_ERROR_PERM;
286       break;
287 #endif
288       
289     default:
290       return G_FILE_ERROR_FAILED;
291       break;
292     }
293 }
294
295 static gboolean
296 get_contents_stdio (const gchar *filename,
297                     FILE        *f,
298                     gchar      **contents,
299                     gsize       *length, 
300                     GError     **error)
301 {
302   gchar buf[2048];
303   size_t bytes;
304   char *str;
305   size_t total_bytes;
306   size_t total_allocated;
307   
308   g_assert (f != NULL);
309
310 #define STARTING_ALLOC 64
311   
312   total_bytes = 0;
313   total_allocated = STARTING_ALLOC;
314   str = g_malloc (STARTING_ALLOC);
315   
316   while (!feof (f))
317     {
318       bytes = fread (buf, 1, 2048, f);
319
320       while ((total_bytes + bytes + 1) > total_allocated)
321         {
322           total_allocated *= 2;
323           str = g_try_realloc (str, total_allocated);
324
325           if (str == NULL)
326             {
327               g_set_error (error,
328                            G_FILE_ERROR,
329                            G_FILE_ERROR_NOMEM,
330                            _("Could not allocate %lu bytes to read file \"%s\""),
331                            (gulong) total_allocated, filename);
332               goto error;
333             }
334         }
335       
336       if (ferror (f))
337         {
338           g_set_error (error,
339                        G_FILE_ERROR,
340                        g_file_error_from_errno (errno),
341                        _("Error reading file '%s': %s"),
342                        filename, strerror (errno));
343
344           goto error;
345         }
346
347       memcpy (str + total_bytes, buf, bytes);
348       total_bytes += bytes;
349     }
350
351   fclose (f);
352
353   str[total_bytes] = '\0';
354   
355   if (length)
356     *length = total_bytes;
357   
358   *contents = str;
359   
360   return TRUE;
361
362  error:
363
364   g_free (str);
365   fclose (f);
366   
367   return FALSE;  
368 }
369
370 #ifndef G_OS_WIN32
371
372 static gboolean
373 get_contents_regfile (const gchar *filename,
374                       struct stat *stat_buf,
375                       gint         fd,
376                       gchar      **contents,
377                       gsize       *length,
378                       GError     **error)
379 {
380   gchar *buf;
381   size_t bytes_read;
382   size_t size;
383   size_t alloc_size;
384   
385   size = stat_buf->st_size;
386
387   alloc_size = size + 1;
388   buf = g_try_malloc (alloc_size);
389
390   if (buf == NULL)
391     {
392       g_set_error (error,
393                    G_FILE_ERROR,
394                    G_FILE_ERROR_NOMEM,
395                    _("Could not allocate %lu bytes to read file \"%s\""),
396                    (gulong) alloc_size, filename);
397
398       return FALSE;
399     }
400   
401   bytes_read = 0;
402   while (bytes_read < size)
403     {
404       gssize rc;
405           
406       rc = read (fd, buf + bytes_read, size - bytes_read);
407
408       if (rc < 0)
409         {
410           if (errno != EINTR) 
411             {
412               close (fd);
413
414               g_free (buf);
415                   
416               g_set_error (error,
417                            G_FILE_ERROR,
418                            g_file_error_from_errno (errno),
419                            _("Failed to read from file '%s': %s"),
420                            filename, strerror (errno));
421
422               return FALSE;
423             }
424         }
425       else if (rc == 0)
426         break;
427       else
428         bytes_read += rc;
429     }
430       
431   buf[bytes_read] = '\0';
432
433   if (length)
434     *length = bytes_read;
435   
436   *contents = buf;
437
438   return TRUE;
439 }
440
441 static gboolean
442 get_contents_posix (const gchar *filename,
443                     gchar      **contents,
444                     gsize       *length,
445                     GError     **error)
446 {
447   struct stat stat_buf;
448   gint fd;
449   
450   /* O_BINARY useful on Cygwin */
451   fd = open (filename, O_RDONLY|O_BINARY);
452
453   if (fd < 0)
454     {
455       g_set_error (error,
456                    G_FILE_ERROR,
457                    g_file_error_from_errno (errno),
458                    _("Failed to open file '%s': %s"),
459                    filename, strerror (errno));
460
461       return FALSE;
462     }
463
464   /* I don't think this will ever fail, aside from ENOMEM, but. */
465   if (fstat (fd, &stat_buf) < 0)
466     {
467       close (fd);
468       
469       g_set_error (error,
470                    G_FILE_ERROR,
471                    g_file_error_from_errno (errno),
472                    _("Failed to get attributes of file '%s': fstat() failed: %s"),
473                    filename, strerror (errno));
474
475       return FALSE;
476     }
477
478   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
479     {
480       return get_contents_regfile (filename,
481                                    &stat_buf,
482                                    fd,
483                                    contents,
484                                    length,
485                                    error);
486     }
487   else
488     {
489       FILE *f;
490
491       f = fdopen (fd, "r");
492       
493       if (f == NULL)
494         {
495           g_set_error (error,
496                        G_FILE_ERROR,
497                        g_file_error_from_errno (errno),
498                        _("Failed to open file '%s': fdopen() failed: %s"),
499                        filename, strerror (errno));
500           
501           return FALSE;
502         }
503   
504       return get_contents_stdio (filename, f, contents, length, error);
505     }
506 }
507
508 #else  /* G_OS_WIN32 */
509
510 static gboolean
511 get_contents_win32 (const gchar *filename,
512                     gchar      **contents,
513                     gsize       *length,
514                     GError     **error)
515 {
516   FILE *f;
517
518   /* I guess you want binary mode; maybe you want text sometimes? */
519   f = fopen (filename, "rb");
520
521   if (f == NULL)
522     {
523       g_set_error (error,
524                    G_FILE_ERROR,
525                    g_file_error_from_errno (errno),
526                    _("Failed to open file '%s': %s"),
527                    filename, strerror (errno));
528       
529       return FALSE;
530     }
531   
532   return get_contents_stdio (filename, f, contents, length, error);
533 }
534
535 #endif
536
537 /**
538  * g_file_get_contents:
539  * @filename: a file to read contents from
540  * @contents: location to store an allocated string
541  * @length: location to store length in bytes of the contents
542  * @error: return location for a #GError
543  * 
544  * Reads an entire file into allocated memory, with good error
545  * checking. If @error is set, %FALSE is returned, and @contents is set
546  * to %NULL. If %TRUE is returned, @error will not be set, and @contents
547  * will be set to the file contents.  The string stored in @contents
548  * will be nul-terminated, so for text files you can pass %NULL for the
549  * @length argument.  The error domain is #G_FILE_ERROR. Possible
550  * error codes are those in the #GFileError enumeration.
551  *
552  * Return value: %TRUE on success, %FALSE if error is set
553  **/
554 gboolean
555 g_file_get_contents (const gchar *filename,
556                      gchar      **contents,
557                      gsize       *length,
558                      GError     **error)
559 {  
560   g_return_val_if_fail (filename != NULL, FALSE);
561   g_return_val_if_fail (contents != NULL, FALSE);
562
563   *contents = NULL;
564   if (length)
565     *length = 0;
566
567 #ifdef G_OS_WIN32
568   return get_contents_win32 (filename, contents, length, error);
569 #else
570   return get_contents_posix (filename, contents, length, error);
571 #endif
572 }
573
574 /*
575  * mkstemp() implementation is from the GNU C library.
576  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
577  */
578 /**
579  * g_mkstemp:
580  * @tmpl: template filename
581  *
582  * Opens a temporary file. See the <function>mkstemp()</function> documentation
583  * on most UNIX-like systems. This is a portability wrapper, which simply calls 
584  * <function>mkstemp()</function> on systems that have it, and implements 
585  * it in GLib otherwise.
586  *
587  * The parameter is a string that should match the rules for
588  * <function>mkstemp()</function>, i.e. end in "XXXXXX". The X string will 
589  * be modified to form the name of a file that didn't exist.
590  *
591  * Return value: A file handle (as from <function>open()</function>) to the file
592  * opened for reading and writing. The file is opened in binary mode
593  * on platforms where there is a difference. The file handle should be
594  * closed with <function>close()</function>. In case of errors, -1 is returned.
595  */
596 int
597 g_mkstemp (char *tmpl)
598 {
599 #ifdef HAVE_MKSTEMP
600   return mkstemp (tmpl);
601 #else
602   int len;
603   char *XXXXXX;
604   int count, fd;
605   static const char letters[] =
606     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
607   static const int NLETTERS = sizeof (letters) - 1;
608   glong value;
609   GTimeVal tv;
610   static int counter = 0;
611
612   len = strlen (tmpl);
613   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
614     return -1;
615
616   /* This is where the Xs start.  */
617   XXXXXX = &tmpl[len - 6];
618
619   /* Get some more or less random data.  */
620   g_get_current_time (&tv);
621   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
622
623   for (count = 0; count < 100; value += 7777, ++count)
624     {
625       glong v = value;
626
627       /* Fill in the random bits.  */
628       XXXXXX[0] = letters[v % NLETTERS];
629       v /= NLETTERS;
630       XXXXXX[1] = letters[v % NLETTERS];
631       v /= NLETTERS;
632       XXXXXX[2] = letters[v % NLETTERS];
633       v /= NLETTERS;
634       XXXXXX[3] = letters[v % NLETTERS];
635       v /= NLETTERS;
636       XXXXXX[4] = letters[v % NLETTERS];
637       v /= NLETTERS;
638       XXXXXX[5] = letters[v % NLETTERS];
639
640       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
641
642       if (fd >= 0)
643         return fd;
644       else if (errno != EEXIST)
645         /* Any other error will apply also to other names we might
646          *  try, and there are 2^32 or so of them, so give up now.
647          */
648         return -1;
649     }
650
651   /* We got out of the loop because we ran out of combinations to try.  */
652   return -1;
653 #endif
654 }
655
656 /**
657  * g_file_open_tmp:
658  * @tmpl: Template for file name, as in g_mkstemp(), basename only
659  * @name_used: location to store actual name used
660  * @error: return location for a #GError
661  *
662  * Opens a file for writing in the preferred directory for temporary
663  * files (as returned by g_get_tmp_dir()). 
664  *
665  * @tmpl should be a string ending with six 'X' characters, as the
666  * parameter to g_mkstemp() (or <function>mkstemp()</function>). 
667  * However, unlike these functions, the template should only be a 
668  * basename, no directory components are allowed. If template is %NULL, 
669  * a default template is used.
670  *
671  * Note that in contrast to g_mkstemp() (and <function>mkstemp()</function>) 
672  * @tmpl is not modified, and might thus be a read-only literal string.
673  *
674  * The actual name used is returned in @name_used if non-%NULL. This
675  * string should be freed with g_free() when not needed any longer.
676  *
677  * Return value: A file handle (as from <function>open()</function>) to 
678  * the file opened for reading and writing. The file is opened in binary 
679  * mode on platforms where there is a difference. The file handle should be
680  * closed with <function>close()</function>. In case of errors, -1 is returned 
681  * and @error will be set.
682  **/
683 int
684 g_file_open_tmp (const char *tmpl,
685                  char      **name_used,
686                  GError    **error)
687 {
688   int retval;
689   const char *tmpdir;
690   char *sep;
691   char *fulltemplate;
692
693   if (tmpl == NULL)
694     tmpl = ".XXXXXX";
695
696   if (strchr (tmpl, G_DIR_SEPARATOR)
697 #ifdef G_OS_WIN32
698       || strchr (tmpl, '/')
699 #endif
700                                     )
701     {
702       g_set_error (error,
703                    G_FILE_ERROR,
704                    G_FILE_ERROR_FAILED,
705                    _("Template '%s' invalid, should not contain a '%s'"),
706                    tmpl, G_DIR_SEPARATOR_S);
707
708       return -1;
709     }
710   
711   if (strlen (tmpl) < 6 ||
712       strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
713     {
714       g_set_error (error,
715                    G_FILE_ERROR,
716                    G_FILE_ERROR_FAILED,
717                    _("Template '%s' doesn't end with XXXXXX"),
718                    tmpl);
719       return -1;
720     }
721
722   tmpdir = g_get_tmp_dir ();
723
724   if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
725     sep = "";
726   else
727     sep = G_DIR_SEPARATOR_S;
728
729   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
730
731   retval = g_mkstemp (fulltemplate);
732
733   if (retval == -1)
734     {
735       g_set_error (error,
736                    G_FILE_ERROR,
737                    g_file_error_from_errno (errno),
738                    _("Failed to create file '%s': %s"),
739                    fulltemplate, strerror (errno));
740       g_free (fulltemplate);
741       return -1;
742     }
743
744   if (name_used)
745     *name_used = fulltemplate;
746   else
747     g_free (fulltemplate);
748
749   return retval;
750 }
751
752 static gchar *
753 g_build_pathv (const gchar *separator,
754                const gchar *first_element,
755                va_list      args)
756 {
757   GString *result;
758   gint separator_len = strlen (separator);
759   gboolean is_first = TRUE;
760   const gchar *next_element;
761
762   result = g_string_new (NULL);
763
764   next_element = first_element;
765
766   while (TRUE)
767     {
768       const gchar *element;
769       const gchar *start;
770       const gchar *end;
771
772       if (next_element)
773         {
774           element = next_element;
775           next_element = va_arg (args, gchar *);
776         }
777       else
778         break;
779
780       start = element;
781       
782       if (is_first)
783         is_first = FALSE;
784       else if (separator_len)
785         {
786           while (start &&
787                  strncmp (start, separator, separator_len) == 0)
788             start += separator_len;
789         }
790
791       end = start + strlen (start);
792       
793       if (next_element && separator_len)
794         {
795           while (end > start + separator_len &&
796                  strncmp (end - separator_len, separator, separator_len) == 0)
797             end -= separator_len;
798         }
799
800       if (end > start)
801         {
802           if (result->len > 0)
803             g_string_append (result, separator);
804
805           g_string_append_len (result, start, end - start);
806         }
807     }
808   
809   return g_string_free (result, FALSE);
810 }
811
812 /**
813  * g_build_path:
814  * @separator: a string used to separator the elements of the path.
815  * @first_element: the first element in the path
816  * @Varargs: remaining elements in path
817  * 
818  * Creates a path from a series of elements using @separator as the
819  * separator between elements. At the boundary between two elements,
820  * any trailing occurrences of separator in the first element, or
821  * leading occurrences of separator in the second element are removed
822  * and exactly one copy of the separator is inserted.
823  * 
824  * Return value: a newly-allocated string that must be freed with g_free().
825  **/
826 gchar *
827 g_build_path (const gchar *separator,
828               const gchar *first_element,
829               ...)
830 {
831   gchar *str;
832   va_list args;
833
834   g_return_val_if_fail (separator != NULL, NULL);
835
836   va_start (args, first_element);
837   str = g_build_pathv (separator, first_element, args);
838   va_end (args);
839
840   return str;
841 }
842
843 /**
844  * g_build_filename:
845  * @first_element: the first element in the path
846  * @Varargs: remaining elements in path
847  * 
848  * Creates a filename from a series of elements using the correct
849  * separator for filenames. This function behaves identically
850  * to <literal>g_build_path (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
851  *
852  * No attempt is made to force the resulting filename to be an absolute
853  * path. If the first element is a relative path, the result will
854  * be a relative path. 
855  * 
856  * Return value: a newly-allocated string that must be freed with g_free().
857  **/
858 gchar *
859 g_build_filename (const gchar *first_element, 
860                   ...)
861 {
862   gchar *str;
863   va_list args;
864
865   va_start (args, first_element);
866   str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
867   va_end (args);
868
869   return str;
870 }