b2e5a90a68fea3f5c2f1668fbc0b9976fb1b3d83
[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 "galias.h"
24 #include "glib.h"
25
26 #include <sys/stat.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <fcntl.h>
38 #include <stdlib.h>
39
40 #ifdef G_OS_WIN32
41 #include <io.h>
42 #ifndef F_OK
43 #define F_OK 0
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 #ifdef G_OS_WIN32
69 #define G_IS_DIR_SEPARATOR(c) (c == G_DIR_SEPARATOR || c == '/')
70 #else
71 #define G_IS_DIR_SEPARATOR(c) (c == G_DIR_SEPARATOR)
72 #endif
73
74 /**
75  * g_file_test:
76  * @filename: a filename to test
77  * @test: bitfield of #GFileTest flags
78  * 
79  * Returns %TRUE if any of the tests in the bitfield @test are
80  * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS | 
81  * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists; 
82  * the check whether it's a directory doesn't matter since the existence 
83  * test is %TRUE. With the current set of available tests, there's no point
84  * passing in more than one test at a time.
85  * 
86  * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
87  * so for a symbolic link to a regular file g_file_test() will return
88  * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
89  *
90  * Note, that for a dangling symbolic link g_file_test() will return
91  * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
92  *
93  * You should never use g_file_test() to test whether it is safe
94  * to perform an operaton, because there is always the possibility
95  * of the condition changing before you actually perform the operation.
96  * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
97  * to know whether it is is safe to write to a file without being
98  * tricked into writing into a different location. It doesn't work!
99  *
100  * <informalexample><programlisting>
101  * /&ast; DON'T DO THIS &ast;/
102  *  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
103  *    fd = open (filename, O_WRONLY);
104  *    /&ast; write to fd &ast;/
105  *  }
106  * </programlisting></informalexample>
107  *
108  * Another thing to note is that %G_FILE_TEST_EXISTS and
109  * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
110  * system call. This usually doesn't matter, but if your program
111  * is setuid or setgid it means that these tests will give you
112  * the answer for the real user ID and group ID , rather than the
113  * effective user ID and group ID.
114  *
115  * Return value: whether a test was %TRUE
116  **/
117 gboolean
118 g_file_test (const gchar *filename,
119              GFileTest    test)
120 {
121   if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
122     return TRUE;
123   
124 #ifndef G_OS_WIN32
125   if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
126     {
127       if (getuid () != 0)
128         return TRUE;
129
130       /* For root, on some POSIX systems, access (filename, X_OK)
131        * will succeed even if no executable bits are set on the
132        * file. We fall through to a stat test to avoid that.
133        */
134     }
135   else
136     test &= ~G_FILE_TEST_IS_EXECUTABLE;
137 #endif  
138
139   if (test & G_FILE_TEST_IS_SYMLINK)
140     {
141 #ifdef G_OS_WIN32
142       /* no sym links on win32, no lstat in msvcrt */
143 #else
144       struct stat s;
145
146       if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
147         return TRUE;
148 #endif
149     }
150   
151   if (test & (G_FILE_TEST_IS_REGULAR |
152               G_FILE_TEST_IS_DIR |
153               G_FILE_TEST_IS_EXECUTABLE))
154     {
155       struct stat s;
156       
157       if (stat (filename, &s) == 0)
158         {
159           if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
160             return TRUE;
161           
162           if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
163             return TRUE;
164
165 #ifndef G_OS_WIN32
166           /* The extra test for root when access (file, X_OK) succeeds.
167            * Probably only makes sense on Unix.
168            */
169           if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
170               ((s.st_mode & S_IXOTH) ||
171                (s.st_mode & S_IXUSR) ||
172                (s.st_mode & S_IXGRP)))
173             return TRUE;
174 #else
175           if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
176               (s.st_mode & _S_IEXEC))
177             return TRUE;
178 #endif
179         }
180     }
181
182   return FALSE;
183 }
184
185 GQuark
186 g_file_error_quark (void)
187 {
188   static GQuark q = 0;
189   if (q == 0)
190     q = g_quark_from_static_string ("g-file-error-quark");
191
192   return q;
193 }
194
195 /**
196  * g_file_error_from_errno:
197  * @err_no: an "errno" value
198  * 
199  * Gets a #GFileError constant based on the passed-in @errno.
200  * For example, if you pass in %EEXIST this function returns
201  * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
202  * assume that all #GFileError values will exist.
203  *
204  * Normally a #GFileError value goes into a #GError returned
205  * from a function that manipulates files. So you would use
206  * g_file_error_from_errno() when constructing a #GError.
207  * 
208  * Return value: #GFileError corresponding to the given @errno
209  **/
210 GFileError
211 g_file_error_from_errno (gint err_no)
212 {
213   switch (err_no)
214     {
215 #ifdef EEXIST
216     case EEXIST:
217       return G_FILE_ERROR_EXIST;
218       break;
219 #endif
220
221 #ifdef EISDIR
222     case EISDIR:
223       return G_FILE_ERROR_ISDIR;
224       break;
225 #endif
226
227 #ifdef EACCES
228     case EACCES:
229       return G_FILE_ERROR_ACCES;
230       break;
231 #endif
232
233 #ifdef ENAMETOOLONG
234     case ENAMETOOLONG:
235       return G_FILE_ERROR_NAMETOOLONG;
236       break;
237 #endif
238
239 #ifdef ENOENT
240     case ENOENT:
241       return G_FILE_ERROR_NOENT;
242       break;
243 #endif
244
245 #ifdef ENOTDIR
246     case ENOTDIR:
247       return G_FILE_ERROR_NOTDIR;
248       break;
249 #endif
250
251 #ifdef ENXIO
252     case ENXIO:
253       return G_FILE_ERROR_NXIO;
254       break;
255 #endif
256
257 #ifdef ENODEV
258     case ENODEV:
259       return G_FILE_ERROR_NODEV;
260       break;
261 #endif
262
263 #ifdef EROFS
264     case EROFS:
265       return G_FILE_ERROR_ROFS;
266       break;
267 #endif
268
269 #ifdef ETXTBSY
270     case ETXTBSY:
271       return G_FILE_ERROR_TXTBSY;
272       break;
273 #endif
274
275 #ifdef EFAULT
276     case EFAULT:
277       return G_FILE_ERROR_FAULT;
278       break;
279 #endif
280
281 #ifdef ELOOP
282     case ELOOP:
283       return G_FILE_ERROR_LOOP;
284       break;
285 #endif
286
287 #ifdef ENOSPC
288     case ENOSPC:
289       return G_FILE_ERROR_NOSPC;
290       break;
291 #endif
292
293 #ifdef ENOMEM
294     case ENOMEM:
295       return G_FILE_ERROR_NOMEM;
296       break;
297 #endif
298
299 #ifdef EMFILE
300     case EMFILE:
301       return G_FILE_ERROR_MFILE;
302       break;
303 #endif
304
305 #ifdef ENFILE
306     case ENFILE:
307       return G_FILE_ERROR_NFILE;
308       break;
309 #endif
310
311 #ifdef EBADF
312     case EBADF:
313       return G_FILE_ERROR_BADF;
314       break;
315 #endif
316
317 #ifdef EINVAL
318     case EINVAL:
319       return G_FILE_ERROR_INVAL;
320       break;
321 #endif
322
323 #ifdef EPIPE
324     case EPIPE:
325       return G_FILE_ERROR_PIPE;
326       break;
327 #endif
328
329 #ifdef EAGAIN
330     case EAGAIN:
331       return G_FILE_ERROR_AGAIN;
332       break;
333 #endif
334
335 #ifdef EINTR
336     case EINTR:
337       return G_FILE_ERROR_INTR;
338       break;
339 #endif
340
341 #ifdef EIO
342     case EIO:
343       return G_FILE_ERROR_IO;
344       break;
345 #endif
346
347 #ifdef EPERM
348     case EPERM:
349       return G_FILE_ERROR_PERM;
350       break;
351 #endif
352
353 #ifdef ENOSYS
354     case ENOSYS:
355       return G_FILE_ERROR_NOSYS;
356       break;
357 #endif
358
359     default:
360       return G_FILE_ERROR_FAILED;
361       break;
362     }
363 }
364
365 static gboolean
366 get_contents_stdio (const gchar *filename,
367                     FILE        *f,
368                     gchar      **contents,
369                     gsize       *length, 
370                     GError     **error)
371 {
372   gchar buf[2048];
373   size_t bytes;
374   char *str;
375   size_t total_bytes;
376   size_t total_allocated;
377   
378   g_assert (f != NULL);
379
380 #define STARTING_ALLOC 64
381   
382   total_bytes = 0;
383   total_allocated = STARTING_ALLOC;
384   str = g_malloc (STARTING_ALLOC);
385   
386   while (!feof (f))
387     {
388       bytes = fread (buf, 1, 2048, f);
389
390       while ((total_bytes + bytes + 1) > total_allocated)
391         {
392           total_allocated *= 2;
393           str = g_try_realloc (str, total_allocated);
394
395           if (str == NULL)
396             {
397               gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
398                                                          NULL, NULL, NULL);
399               g_set_error (error,
400                            G_FILE_ERROR,
401                            G_FILE_ERROR_NOMEM,
402                            _("Could not allocate %lu bytes to read file \"%s\""),
403                            (gulong) total_allocated, 
404                            utf8_filename ? utf8_filename : "???");
405               g_free (utf8_filename);
406
407               goto error;
408             }
409         }
410       
411       if (ferror (f))
412         {
413           gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
414                                                      NULL, NULL, NULL);
415           g_set_error (error,
416                        G_FILE_ERROR,
417                        g_file_error_from_errno (errno),
418                        _("Error reading file '%s': %s"),
419                        utf8_filename ? utf8_filename : "???", 
420                        g_strerror (errno));
421           g_free (utf8_filename);
422
423           goto error;
424         }
425
426       memcpy (str + total_bytes, buf, bytes);
427       total_bytes += bytes;
428     }
429
430   fclose (f);
431
432   str[total_bytes] = '\0';
433   
434   if (length)
435     *length = total_bytes;
436   
437   *contents = str;
438   
439   return TRUE;
440
441  error:
442
443   g_free (str);
444   fclose (f);
445   
446   return FALSE;  
447 }
448
449 #ifndef G_OS_WIN32
450
451 static gboolean
452 get_contents_regfile (const gchar *filename,
453                       struct stat *stat_buf,
454                       gint         fd,
455                       gchar      **contents,
456                       gsize       *length,
457                       GError     **error)
458 {
459   gchar *buf;
460   size_t bytes_read;
461   size_t size;
462   size_t alloc_size;
463   
464   size = stat_buf->st_size;
465
466   alloc_size = size + 1;
467   buf = g_try_malloc (alloc_size);
468
469   if (buf == NULL)
470     {
471       gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
472                                                  NULL, NULL, NULL);
473       g_set_error (error,
474                    G_FILE_ERROR,
475                    G_FILE_ERROR_NOMEM,
476                    _("Could not allocate %lu bytes to read file \"%s\""),
477                    (gulong) alloc_size, 
478                    utf8_filename ? utf8_filename : "???");
479       g_free (utf8_filename);
480
481       goto error;
482     }
483   
484   bytes_read = 0;
485   while (bytes_read < size)
486     {
487       gssize rc;
488           
489       rc = read (fd, buf + bytes_read, size - bytes_read);
490
491       if (rc < 0)
492         {
493           if (errno != EINTR) 
494             {
495               g_free (buf);
496               gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
497                                                          NULL, NULL, NULL);
498               g_set_error (error,
499                            G_FILE_ERROR,
500                            g_file_error_from_errno (errno),
501                            _("Failed to read from file '%s': %s"),
502                            utf8_filename ? utf8_filename : "???", 
503                            g_strerror (errno));
504               g_free (utf8_filename);
505
506               goto error;
507             }
508         }
509       else if (rc == 0)
510         break;
511       else
512         bytes_read += rc;
513     }
514       
515   buf[bytes_read] = '\0';
516
517   if (length)
518     *length = bytes_read;
519   
520   *contents = buf;
521
522   close (fd);
523
524   return TRUE;
525
526  error:
527
528   close (fd);
529   
530   return FALSE;
531 }
532
533 static gboolean
534 get_contents_posix (const gchar *filename,
535                     gchar      **contents,
536                     gsize       *length,
537                     GError     **error)
538 {
539   struct stat stat_buf;
540   gint fd;
541   
542   /* O_BINARY useful on Cygwin */
543   fd = open (filename, O_RDONLY|O_BINARY);
544
545   if (fd < 0)
546     {
547       gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
548                                                  NULL, NULL, NULL);
549       g_set_error (error,
550                    G_FILE_ERROR,
551                    g_file_error_from_errno (errno),
552                    _("Failed to open file '%s': %s"),
553                    utf8_filename ? utf8_filename : "???", 
554                    g_strerror (errno));
555       g_free (utf8_filename);
556
557       return FALSE;
558     }
559
560   /* I don't think this will ever fail, aside from ENOMEM, but. */
561   if (fstat (fd, &stat_buf) < 0)
562     {
563       close (fd);
564       
565       gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
566                                                  NULL, NULL, NULL);
567       g_set_error (error,
568                    G_FILE_ERROR,
569                    g_file_error_from_errno (errno),
570                    _("Failed to get attributes of file '%s': fstat() failed: %s"),
571                    utf8_filename ? utf8_filename : "???", 
572                    g_strerror (errno));
573       g_free (utf8_filename);
574
575       return FALSE;
576     }
577
578   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
579     {
580       return get_contents_regfile (filename,
581                                    &stat_buf,
582                                    fd,
583                                    contents,
584                                    length,
585                                    error);
586     }
587   else
588     {
589       FILE *f;
590
591       f = fdopen (fd, "r");
592       
593       if (f == NULL)
594         {
595           gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
596                                                      NULL, NULL, NULL);
597
598           g_set_error (error,
599                        G_FILE_ERROR,
600                        g_file_error_from_errno (errno),
601                        _("Failed to open file '%s': fdopen() failed: %s"),
602                        utf8_filename ? utf8_filename : "???", 
603                        g_strerror (errno));
604           g_free (utf8_filename);
605
606           return FALSE;
607         }
608   
609       return get_contents_stdio (filename, f, contents, length, error);
610     }
611 }
612
613 #else  /* G_OS_WIN32 */
614
615 static gboolean
616 get_contents_win32 (const gchar *filename,
617                     gchar      **contents,
618                     gsize       *length,
619                     GError     **error)
620 {
621   FILE *f;
622
623   /* I guess you want binary mode; maybe you want text sometimes? */
624   f = fopen (filename, "rb");
625
626   if (f == NULL)
627     {
628       gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
629                                                  NULL, NULL, NULL);
630       
631       g_set_error (error,
632                    G_FILE_ERROR,
633                    g_file_error_from_errno (errno),
634                    _("Failed to open file '%s': %s"),
635                    utf8_filename ? utf8_filename : "???", 
636                    g_strerror (errno));
637       g_free (utf8_filename);
638
639       return FALSE;
640     }
641   
642   return get_contents_stdio (filename, f, contents, length, error);
643 }
644
645 #endif
646
647 /**
648  * g_file_get_contents:
649  * @filename: a file to read contents from
650  * @contents: location to store an allocated string
651  * @length: location to store length in bytes of the contents
652  * @error: return location for a #GError
653  * 
654  * Reads an entire file into allocated memory, with good error
655  * checking. If @error is set, %FALSE is returned, and @contents is set
656  * to %NULL. If %TRUE is returned, @error will not be set, and @contents
657  * will be set to the file contents.  The string stored in @contents
658  * will be nul-terminated, so for text files you can pass %NULL for the
659  * @length argument.  The error domain is #G_FILE_ERROR. Possible
660  * error codes are those in the #GFileError enumeration.
661  *
662  * Return value: %TRUE on success, %FALSE if error is set
663  **/
664 gboolean
665 g_file_get_contents (const gchar *filename,
666                      gchar      **contents,
667                      gsize       *length,
668                      GError     **error)
669 {  
670   g_return_val_if_fail (filename != NULL, FALSE);
671   g_return_val_if_fail (contents != NULL, FALSE);
672
673   *contents = NULL;
674   if (length)
675     *length = 0;
676
677 #ifdef G_OS_WIN32
678   return get_contents_win32 (filename, contents, length, error);
679 #else
680   return get_contents_posix (filename, contents, length, error);
681 #endif
682 }
683
684 /*
685  * mkstemp() implementation is from the GNU C library.
686  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
687  */
688 /**
689  * g_mkstemp:
690  * @tmpl: template filename
691  *
692  * Opens a temporary file. See the mkstemp() documentation
693  * on most UNIX-like systems. This is a portability wrapper, which simply calls 
694  * mkstemp() on systems that have it, and implements 
695  * it in GLib otherwise.
696  *
697  * The parameter is a string that should match the rules for
698  * mkstemp(), i.e. end in "XXXXXX". The X string will 
699  * be modified to form the name of a file that didn't exist.
700  *
701  * Return value: A file handle (as from open()) to the file
702  * opened for reading and writing. The file is opened in binary mode
703  * on platforms where there is a difference. The file handle should be
704  * closed with close(). In case of errors, -1 is returned.
705  */
706 gint
707 g_mkstemp (gchar *tmpl)
708 {
709 #ifdef HAVE_MKSTEMP
710   return mkstemp (tmpl);
711 #else
712   int len;
713   char *XXXXXX;
714   int count, fd;
715   static const char letters[] =
716     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
717   static const int NLETTERS = sizeof (letters) - 1;
718   glong value;
719   GTimeVal tv;
720   static int counter = 0;
721
722   len = strlen (tmpl);
723   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
724     return -1;
725
726   /* This is where the Xs start.  */
727   XXXXXX = &tmpl[len - 6];
728
729   /* Get some more or less random data.  */
730   g_get_current_time (&tv);
731   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
732
733   for (count = 0; count < 100; value += 7777, ++count)
734     {
735       glong v = value;
736
737       /* Fill in the random bits.  */
738       XXXXXX[0] = letters[v % NLETTERS];
739       v /= NLETTERS;
740       XXXXXX[1] = letters[v % NLETTERS];
741       v /= NLETTERS;
742       XXXXXX[2] = letters[v % NLETTERS];
743       v /= NLETTERS;
744       XXXXXX[3] = letters[v % NLETTERS];
745       v /= NLETTERS;
746       XXXXXX[4] = letters[v % NLETTERS];
747       v /= NLETTERS;
748       XXXXXX[5] = letters[v % NLETTERS];
749
750       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
751
752       if (fd >= 0)
753         return fd;
754       else if (errno != EEXIST)
755         /* Any other error will apply also to other names we might
756          *  try, and there are 2^32 or so of them, so give up now.
757          */
758         return -1;
759     }
760
761   /* We got out of the loop because we ran out of combinations to try.  */
762   return -1;
763 #endif
764 }
765
766 /**
767  * g_file_open_tmp:
768  * @tmpl: Template for file name, as in g_mkstemp(), basename only
769  * @name_used: location to store actual name used
770  * @error: return location for a #GError
771  *
772  * Opens a file for writing in the preferred directory for temporary
773  * files (as returned by g_get_tmp_dir()). 
774  *
775  * @tmpl should be a string ending with six 'X' characters, as the
776  * parameter to g_mkstemp() (or mkstemp()). 
777  * However, unlike these functions, the template should only be a 
778  * basename, no directory components are allowed. If template is %NULL, 
779  * a default template is used.
780  *
781  * Note that in contrast to g_mkstemp() (and mkstemp()) 
782  * @tmpl is not modified, and might thus be a read-only literal string.
783  *
784  * The actual name used is returned in @name_used if non-%NULL. This
785  * string should be freed with g_free() when not needed any longer.
786  *
787  * Return value: A file handle (as from open()) to 
788  * the file opened for reading and writing. The file is opened in binary 
789  * mode on platforms where there is a difference. The file handle should be
790  * closed with close(). In case of errors, -1 is returned 
791  * and @error will be set.
792  **/
793 gint
794 g_file_open_tmp (const gchar *tmpl,
795                  gchar      **name_used,
796                  GError     **error)
797 {
798   int retval;
799   const char *tmpdir;
800   char *sep;
801   char *fulltemplate;
802   const char *slash;
803
804   if (tmpl == NULL)
805     tmpl = ".XXXXXX";
806
807   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
808 #ifdef G_OS_WIN32
809       || (strchr (tmpl, '/') != NULL && (slash = "/"))
810 #endif
811       )
812     {
813       char c[2];
814       c[0] = *slash;
815       c[1] = '\0';
816
817       g_set_error (error,
818                    G_FILE_ERROR,
819                    G_FILE_ERROR_FAILED,
820                    _("Template '%s' invalid, should not contain a '%s'"),
821                    tmpl, c);
822
823       return -1;
824     }
825   
826   if (strlen (tmpl) < 6 ||
827       strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
828     {
829       g_set_error (error,
830                    G_FILE_ERROR,
831                    G_FILE_ERROR_FAILED,
832                    _("Template '%s' doesn't end with XXXXXX"),
833                    tmpl);
834       return -1;
835     }
836
837   tmpdir = g_get_tmp_dir ();
838
839   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
840     sep = "";
841   else
842     sep = G_DIR_SEPARATOR_S;
843
844   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
845
846   retval = g_mkstemp (fulltemplate);
847
848   if (retval == -1)
849     {
850       g_set_error (error,
851                    G_FILE_ERROR,
852                    g_file_error_from_errno (errno),
853                    _("Failed to create file '%s': %s"),
854                    fulltemplate, g_strerror (errno));
855       g_free (fulltemplate);
856       return -1;
857     }
858
859   if (name_used)
860     *name_used = fulltemplate;
861   else
862     g_free (fulltemplate);
863
864   return retval;
865 }
866
867 static gchar *
868 g_build_pathv (const gchar *separator,
869                const gchar *first_element,
870                va_list      args)
871 {
872   GString *result;
873   gint separator_len = strlen (separator);
874   gboolean is_first = TRUE;
875   gboolean have_leading = FALSE;
876   const gchar *single_element = NULL;
877   const gchar *next_element;
878   const gchar *last_trailing = NULL;
879
880   result = g_string_new (NULL);
881
882   next_element = first_element;
883
884   while (TRUE)
885     {
886       const gchar *element;
887       const gchar *start;
888       const gchar *end;
889
890       if (next_element)
891         {
892           element = next_element;
893           next_element = va_arg (args, gchar *);
894         }
895       else
896         break;
897
898       /* Ignore empty elements */
899       if (!*element)
900         continue;
901       
902       start = element;
903
904       if (separator_len)
905         {
906           while (start &&
907                  strncmp (start, separator, separator_len) == 0)
908             start += separator_len;
909         }
910
911       end = start + strlen (start);
912       
913       if (separator_len)
914         {
915           while (end >= start + separator_len &&
916                  strncmp (end - separator_len, separator, separator_len) == 0)
917             end -= separator_len;
918           
919           last_trailing = end;
920           while (last_trailing >= element + separator_len &&
921                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
922             last_trailing -= separator_len;
923
924           if (!have_leading)
925             {
926               /* If the leading and trailing separator strings are in the
927                * same element and overlap, the result is exactly that element
928                */
929               if (last_trailing <= start)
930                 single_element = element;
931                   
932               g_string_append_len (result, element, start - element);
933               have_leading = TRUE;
934             }
935           else
936             single_element = NULL;
937         }
938
939       if (end == start)
940         continue;
941
942       if (!is_first)
943         g_string_append (result, separator);
944       
945       g_string_append_len (result, start, end - start);
946       is_first = FALSE;
947     }
948
949   if (single_element)
950     {
951       g_string_free (result, TRUE);
952       return g_strdup (single_element);
953     }
954   else
955     {
956       if (last_trailing)
957         g_string_append (result, last_trailing);
958   
959       return g_string_free (result, FALSE);
960     }
961 }
962
963 /**
964  * g_build_path:
965  * @separator: a string used to separator the elements of the path.
966  * @first_element: the first element in the path
967  * @Varargs: remaining elements in path, terminated by %NULL
968  * 
969  * Creates a path from a series of elements using @separator as the
970  * separator between elements. At the boundary between two elements,
971  * any trailing occurrences of separator in the first element, or
972  * leading occurrences of separator in the second element are removed
973  * and exactly one copy of the separator is inserted.
974  *
975  * Empty elements are ignored.
976  *
977  * The number of leading copies of the separator on the result is
978  * the same as the number of leading copies of the separator on
979  * the first non-empty element.
980  *
981  * The number of trailing copies of the separator on the result is
982  * the same as the number of trailing copies of the separator on
983  * the last non-empty element. (Determination of the number of
984  * trailing copies is done without stripping leading copies, so
985  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
986  * has 1 trailing copy.)
987  *
988  * However, if there is only a single non-empty element, and there
989  * are no characters in that element not part of the leading or
990  * trailing separators, then the result is exactly the original value
991  * of that element.
992  *
993  * Other than for determination of the number of leading and trailing
994  * copies of the separator, elements consisting only of copies
995  * of the separator are ignored.
996  * 
997  * Return value: a newly-allocated string that must be freed with g_free().
998  **/
999 gchar *
1000 g_build_path (const gchar *separator,
1001               const gchar *first_element,
1002               ...)
1003 {
1004   gchar *str;
1005   va_list args;
1006
1007   g_return_val_if_fail (separator != NULL, NULL);
1008
1009   va_start (args, first_element);
1010   str = g_build_pathv (separator, first_element, args);
1011   va_end (args);
1012
1013   return str;
1014 }
1015
1016 /**
1017  * g_build_filename:
1018  * @first_element: the first element in the path
1019  * @Varargs: remaining elements in path, terminated by %NULL
1020  * 
1021  * Creates a filename from a series of elements using the correct
1022  * separator for filenames.
1023  *
1024  * On Unix, this function behaves identically to <literal>g_build_path
1025  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1026  *
1027  * On Windows, it takes into account that either the backslash
1028  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1029  * as separator in filenames, but otherwise behaves as on Unix. When
1030  * file pathname separators need to be inserted, the one that last
1031  * previously occurred in the parameters (reading from left to right)
1032  * is used.
1033  *
1034  * No attempt is made to force the resulting filename to be an absolute
1035  * path. If the first element is a relative path, the result will
1036  * be a relative path. 
1037  * 
1038  * Return value: a newly-allocated string that must be freed with g_free().
1039  **/
1040 gchar *
1041 g_build_filename (const gchar *first_element, 
1042                   ...)
1043 {
1044 #ifndef G_OS_WIN32
1045   gchar *str;
1046   va_list args;
1047
1048   va_start (args, first_element);
1049   str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1050   va_end (args);
1051
1052   return str;
1053 #else
1054   /* Code copied from g_build_pathv(), and modifed to use two
1055    * alternative single-character separators.
1056    */
1057   va_list args;
1058   GString *result;
1059   gboolean is_first = TRUE;
1060   gboolean have_leading = FALSE;
1061   const gchar *single_element = NULL;
1062   const gchar *next_element;
1063   const gchar *last_trailing = NULL;
1064   gchar current_separator = '\\';
1065
1066   va_start (args, first_element);
1067
1068   result = g_string_new (NULL);
1069
1070   next_element = first_element;
1071
1072   while (TRUE)
1073     {
1074       const gchar *element;
1075       const gchar *start;
1076       const gchar *end;
1077
1078       if (next_element)
1079         {
1080           element = next_element;
1081           next_element = va_arg (args, gchar *);
1082         }
1083       else
1084         break;
1085
1086       /* Ignore empty elements */
1087       if (!*element)
1088         continue;
1089       
1090       start = element;
1091
1092       if (TRUE)
1093         {
1094           while (start &&
1095                  (*start == '\\' || *start == '/'))
1096             {
1097               current_separator = *start;
1098               start++;
1099             }
1100         }
1101
1102       end = start + strlen (start);
1103       
1104       if (TRUE)
1105         {
1106           while (end >= start + 1 &&
1107                  (end[-1] == '\\' || end[-1] == '/'))
1108             {
1109               current_separator = end[-1];
1110               end--;
1111             }
1112           
1113           last_trailing = end;
1114           while (last_trailing >= element + 1 &&
1115                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1116             last_trailing--;
1117
1118           if (!have_leading)
1119             {
1120               /* If the leading and trailing separator strings are in the
1121                * same element and overlap, the result is exactly that element
1122                */
1123               if (last_trailing <= start)
1124                 single_element = element;
1125                   
1126               g_string_append_len (result, element, start - element);
1127               have_leading = TRUE;
1128             }
1129           else
1130             single_element = NULL;
1131         }
1132
1133       if (end == start)
1134         continue;
1135
1136       if (!is_first)
1137         g_string_append_len (result, &current_separator, 1);
1138       
1139       g_string_append_len (result, start, end - start);
1140       is_first = FALSE;
1141     }
1142
1143   va_end (args);
1144
1145   if (single_element)
1146     {
1147       g_string_free (result, TRUE);
1148       return g_strdup (single_element);
1149     }
1150   else
1151     {
1152       if (last_trailing)
1153         g_string_append (result, last_trailing);
1154   
1155       return g_string_free (result, FALSE);
1156     }
1157 #endif
1158 }
1159
1160 /**
1161  * g_file_read_link:
1162  * @filename: the symbolic link
1163  * @error: return location for a #GError
1164  *
1165  * Reads the contents of the symbolic link @filename like the POSIX readlink() function.
1166  * The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to 
1167  * convert it to UTF-8.
1168  *
1169  * Returns: A newly allocated string with the contents of the symbolic link, 
1170  *          or %NULL if an error occurred.
1171  *
1172  * Since: 2.4
1173  */
1174 gchar *
1175 g_file_read_link (const gchar *filename,
1176                   GError     **error)
1177 {
1178 #ifdef HAVE_READLINK
1179   gchar *buffer;
1180   guint size;
1181   gint read_size;    
1182   
1183   size = 256; 
1184   buffer = g_malloc (size);
1185   
1186   while (TRUE) 
1187     {
1188       read_size = readlink (filename, buffer, size);
1189       if (read_size < 0) {
1190         g_free (buffer);
1191       
1192         gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
1193                                                    NULL, NULL, NULL);
1194         g_set_error (error,
1195                      G_FILE_ERROR,
1196                      g_file_error_from_errno (errno),
1197                      _("Failed to read the symbolic link '%s': %s"),
1198                      utf8_filename ? utf8_filename : "???", 
1199                      g_strerror (errno));
1200         g_free (utf8_filename);
1201         
1202         return NULL;
1203       }
1204     
1205       if (read_size < size) 
1206         {
1207           buffer[read_size] = 0;
1208           return buffer;
1209         }
1210       
1211       size *= 2;
1212       buffer = g_realloc (buffer, size);
1213     }
1214 #else
1215   g_set_error (error,
1216                G_FILE_ERROR,
1217                G_FILE_ERROR_INVAL,
1218                _("Symbolic links not supported"));
1219         
1220   return NULL;
1221 #endif
1222 }