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