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