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