glib/glib.symbols glib/gutils.h Make also g_getenv(), g_setenv(),
[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
733  * @error: return location for a #GError
734  * 
735  * Reads an entire file into allocated memory, with good error
736  * checking. If @error is set, %FALSE is returned, and @contents is set
737  * to %NULL. If %TRUE is returned, @error will not be set, and @contents
738  * will be set to the file contents.  The string stored in @contents
739  * will be nul-terminated, so for text files you can pass %NULL for the
740  * @length argument.  The error domain is #G_FILE_ERROR. Possible
741  * error codes are those in the #GFileError enumeration.
742  *
743  * Return value: %TRUE on success, %FALSE if error is set
744  **/
745 gboolean
746 g_file_get_contents (const gchar *filename,
747                      gchar      **contents,
748                      gsize       *length,
749                      GError     **error)
750 {  
751   g_return_val_if_fail (filename != NULL, FALSE);
752   g_return_val_if_fail (contents != NULL, FALSE);
753
754   *contents = NULL;
755   if (length)
756     *length = 0;
757
758 #ifdef G_OS_WIN32
759   return get_contents_win32 (filename, contents, length, error);
760 #else
761   return get_contents_posix (filename, contents, length, error);
762 #endif
763 }
764
765 #ifdef G_OS_WIN32
766
767 #undef g_file_get_contents
768
769 /* Binary compatibility version. Not for newly compiled code. */
770
771 gboolean
772 g_file_get_contents (const gchar *filename,
773                      gchar      **contents,
774                      gsize       *length,
775                      GError     **error)
776 {
777   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
778   gboolean retval;
779
780   if (utf8_filename == NULL)
781     return FALSE;
782
783   retval = g_file_get_contents (utf8_filename, contents, length, error);
784
785   g_free (utf8_filename);
786
787   return retval;
788 }
789
790 #endif
791
792 /*
793  * mkstemp() implementation is from the GNU C library.
794  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
795  */
796 /**
797  * g_mkstemp:
798  * @tmpl: template filename
799  *
800  * Opens a temporary file. See the mkstemp() documentation
801  * on most UNIX-like systems. This is a portability wrapper, which simply calls 
802  * mkstemp() on systems that have it, and implements 
803  * it in GLib otherwise.
804  *
805  * The parameter is a string that should match the rules for
806  * mkstemp(), i.e. end in "XXXXXX". The X string will 
807  * be modified to form the name of a file that didn't exist.
808  * The string should be in the GLib file name encoding. Most importantly, 
809  * on Windows it should be in UTF-8.
810  *
811  * Return value: A file handle (as from open()) to the file
812  * opened for reading and writing. The file is opened in binary mode
813  * on platforms where there is a difference. The file handle should be
814  * closed with close(). In case of errors, -1 is returned.
815  */
816 gint
817 g_mkstemp (gchar *tmpl)
818 {
819 #ifdef HAVE_MKSTEMP
820   return mkstemp (tmpl);
821 #else
822   int len;
823   char *XXXXXX;
824   int count, fd;
825   static const char letters[] =
826     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
827   static const int NLETTERS = sizeof (letters) - 1;
828   glong value;
829   GTimeVal tv;
830   static int counter = 0;
831
832   len = strlen (tmpl);
833   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
834     return -1;
835
836   /* This is where the Xs start.  */
837   XXXXXX = &tmpl[len - 6];
838
839   /* Get some more or less random data.  */
840   g_get_current_time (&tv);
841   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
842
843   for (count = 0; count < 100; value += 7777, ++count)
844     {
845       glong v = value;
846
847       /* Fill in the random bits.  */
848       XXXXXX[0] = letters[v % NLETTERS];
849       v /= NLETTERS;
850       XXXXXX[1] = letters[v % NLETTERS];
851       v /= NLETTERS;
852       XXXXXX[2] = letters[v % NLETTERS];
853       v /= NLETTERS;
854       XXXXXX[3] = letters[v % NLETTERS];
855       v /= NLETTERS;
856       XXXXXX[4] = letters[v % NLETTERS];
857       v /= NLETTERS;
858       XXXXXX[5] = letters[v % NLETTERS];
859
860       /* tmpl is in UTF-8 on Windows, thus use g_open() */
861       fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
862
863       if (fd >= 0)
864         return fd;
865       else if (errno != EEXIST)
866         /* Any other error will apply also to other names we might
867          *  try, and there are 2^32 or so of them, so give up now.
868          */
869         return -1;
870     }
871
872   /* We got out of the loop because we ran out of combinations to try.  */
873   return -1;
874 #endif
875 }
876
877 #ifdef G_OS_WIN32
878
879 #undef g_mkstemp
880
881 /* Binary compatibility version. Not for newly compiled code. */
882
883 gint
884 g_mkstemp (gchar *tmpl)
885 {
886   int len;
887   char *XXXXXX;
888   int count, fd;
889   static const char letters[] =
890     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
891   static const int NLETTERS = sizeof (letters) - 1;
892   glong value;
893   GTimeVal tv;
894   static int counter = 0;
895
896   len = strlen (tmpl);
897   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
898     return -1;
899
900   /* This is where the Xs start.  */
901   XXXXXX = &tmpl[len - 6];
902
903   /* Get some more or less random data.  */
904   g_get_current_time (&tv);
905   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
906
907   for (count = 0; count < 100; value += 7777, ++count)
908     {
909       glong v = value;
910
911       /* Fill in the random bits.  */
912       XXXXXX[0] = letters[v % NLETTERS];
913       v /= NLETTERS;
914       XXXXXX[1] = letters[v % NLETTERS];
915       v /= NLETTERS;
916       XXXXXX[2] = letters[v % NLETTERS];
917       v /= NLETTERS;
918       XXXXXX[3] = letters[v % NLETTERS];
919       v /= NLETTERS;
920       XXXXXX[4] = letters[v % NLETTERS];
921       v /= NLETTERS;
922       XXXXXX[5] = letters[v % NLETTERS];
923
924       /* This is the backward compatibility system codepage version,
925        * thus use normal open().
926        */
927       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
928
929       if (fd >= 0)
930         return fd;
931       else if (errno != EEXIST)
932         /* Any other error will apply also to other names we might
933          *  try, and there are 2^32 or so of them, so give up now.
934          */
935         return -1;
936     }
937
938   /* We got out of the loop because we ran out of combinations to try.  */
939   return -1;
940 }
941
942 #endif
943
944 /**
945  * g_file_open_tmp:
946  * @tmpl: Template for file name, as in g_mkstemp(), basename only
947  * @name_used: location to store actual name used
948  * @error: return location for a #GError
949  *
950  * Opens a file for writing in the preferred directory for temporary
951  * files (as returned by g_get_tmp_dir()). 
952  *
953  * @tmpl should be a string in the GLib file name encoding ending with
954  * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
955  * However, unlike these functions, the template should only be a
956  * basename, no directory components are allowed. If template is
957  * %NULL, a default template is used.
958  *
959  * Note that in contrast to g_mkstemp() (and mkstemp()) 
960  * @tmpl is not modified, and might thus be a read-only literal string.
961  *
962  * The actual name used is returned in @name_used if non-%NULL. This
963  * string should be freed with g_free() when not needed any longer.
964  * The returned name is in the GLib file name encoding.
965  *
966  * Return value: A file handle (as from open()) to 
967  * the file opened for reading and writing. The file is opened in binary 
968  * mode on platforms where there is a difference. The file handle should be
969  * closed with close(). In case of errors, -1 is returned 
970  * and @error will be set.
971  **/
972 gint
973 g_file_open_tmp (const gchar *tmpl,
974                  gchar      **name_used,
975                  GError     **error)
976 {
977   int retval;
978   const char *tmpdir;
979   char *sep;
980   char *fulltemplate;
981   const char *slash;
982
983   if (tmpl == NULL)
984     tmpl = ".XXXXXX";
985
986   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
987 #ifdef G_OS_WIN32
988       || (strchr (tmpl, '/') != NULL && (slash = "/"))
989 #endif
990       )
991     {
992       gchar *display_tmpl = g_filename_display_name (tmpl);
993       char c[2];
994       c[0] = *slash;
995       c[1] = '\0';
996
997       g_set_error (error,
998                    G_FILE_ERROR,
999                    G_FILE_ERROR_FAILED,
1000                    _("Template '%s' invalid, should not contain a '%s'"),
1001                    display_tmpl, c);
1002       g_free (display_tmpl);
1003
1004       return -1;
1005     }
1006   
1007   if (strlen (tmpl) < 6 ||
1008       strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1009     {
1010       gchar *display_tmpl = g_filename_display_name (tmpl);
1011       g_set_error (error,
1012                    G_FILE_ERROR,
1013                    G_FILE_ERROR_FAILED,
1014                    _("Template '%s' doesn't end with XXXXXX"),
1015                    display_tmpl);
1016       g_free (display_tmpl);
1017       return -1;
1018     }
1019
1020   tmpdir = g_get_tmp_dir ();
1021
1022   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1023     sep = "";
1024   else
1025     sep = G_DIR_SEPARATOR_S;
1026
1027   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1028
1029   retval = g_mkstemp (fulltemplate);
1030
1031   if (retval == -1)
1032     {
1033       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1034       g_set_error (error,
1035                    G_FILE_ERROR,
1036                    g_file_error_from_errno (errno),
1037                    _("Failed to create file '%s': %s"),
1038                    display_fulltemplate, g_strerror (errno));
1039       g_free (display_fulltemplate);
1040       g_free (fulltemplate);
1041       return -1;
1042     }
1043
1044   if (name_used)
1045     *name_used = fulltemplate;
1046   else
1047     g_free (fulltemplate);
1048
1049   return retval;
1050 }
1051
1052 #ifdef G_OS_WIN32
1053
1054 #undef g_file_open_tmp
1055
1056 /* Binary compatibility version. Not for newly compiled code. */
1057
1058 gint
1059 g_file_open_tmp (const gchar *tmpl,
1060                  gchar      **name_used,
1061                  GError     **error)
1062 {
1063   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1064   gchar *utf8_name_used;
1065   gint retval;
1066
1067   if (utf8_tmpl == NULL)
1068     return -1;
1069
1070   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1071   
1072   if (retval == -1)
1073     return -1;
1074
1075   if (name_used)
1076     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1077
1078   g_free (utf8_name_used);
1079
1080   return retval;
1081 }
1082
1083 #endif
1084
1085 static gchar *
1086 g_build_pathv (const gchar *separator,
1087                const gchar *first_element,
1088                va_list      args)
1089 {
1090   GString *result;
1091   gint separator_len = strlen (separator);
1092   gboolean is_first = TRUE;
1093   gboolean have_leading = FALSE;
1094   const gchar *single_element = NULL;
1095   const gchar *next_element;
1096   const gchar *last_trailing = NULL;
1097
1098   result = g_string_new (NULL);
1099
1100   next_element = first_element;
1101
1102   while (TRUE)
1103     {
1104       const gchar *element;
1105       const gchar *start;
1106       const gchar *end;
1107
1108       if (next_element)
1109         {
1110           element = next_element;
1111           next_element = va_arg (args, gchar *);
1112         }
1113       else
1114         break;
1115
1116       /* Ignore empty elements */
1117       if (!*element)
1118         continue;
1119       
1120       start = element;
1121
1122       if (separator_len)
1123         {
1124           while (start &&
1125                  strncmp (start, separator, separator_len) == 0)
1126             start += separator_len;
1127         }
1128
1129       end = start + strlen (start);
1130       
1131       if (separator_len)
1132         {
1133           while (end >= start + separator_len &&
1134                  strncmp (end - separator_len, separator, separator_len) == 0)
1135             end -= separator_len;
1136           
1137           last_trailing = end;
1138           while (last_trailing >= element + separator_len &&
1139                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1140             last_trailing -= separator_len;
1141
1142           if (!have_leading)
1143             {
1144               /* If the leading and trailing separator strings are in the
1145                * same element and overlap, the result is exactly that element
1146                */
1147               if (last_trailing <= start)
1148                 single_element = element;
1149                   
1150               g_string_append_len (result, element, start - element);
1151               have_leading = TRUE;
1152             }
1153           else
1154             single_element = NULL;
1155         }
1156
1157       if (end == start)
1158         continue;
1159
1160       if (!is_first)
1161         g_string_append (result, separator);
1162       
1163       g_string_append_len (result, start, end - start);
1164       is_first = FALSE;
1165     }
1166
1167   if (single_element)
1168     {
1169       g_string_free (result, TRUE);
1170       return g_strdup (single_element);
1171     }
1172   else
1173     {
1174       if (last_trailing)
1175         g_string_append (result, last_trailing);
1176   
1177       return g_string_free (result, FALSE);
1178     }
1179 }
1180
1181 /**
1182  * g_build_path:
1183  * @separator: a string used to separator the elements of the path.
1184  * @first_element: the first element in the path
1185  * @Varargs: remaining elements in path, terminated by %NULL
1186  * 
1187  * Creates a path from a series of elements using @separator as the
1188  * separator between elements. At the boundary between two elements,
1189  * any trailing occurrences of separator in the first element, or
1190  * leading occurrences of separator in the second element are removed
1191  * and exactly one copy of the separator is inserted.
1192  *
1193  * Empty elements are ignored.
1194  *
1195  * The number of leading copies of the separator on the result is
1196  * the same as the number of leading copies of the separator on
1197  * the first non-empty element.
1198  *
1199  * The number of trailing copies of the separator on the result is
1200  * the same as the number of trailing copies of the separator on
1201  * the last non-empty element. (Determination of the number of
1202  * trailing copies is done without stripping leading copies, so
1203  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1204  * has 1 trailing copy.)
1205  *
1206  * However, if there is only a single non-empty element, and there
1207  * are no characters in that element not part of the leading or
1208  * trailing separators, then the result is exactly the original value
1209  * of that element.
1210  *
1211  * Other than for determination of the number of leading and trailing
1212  * copies of the separator, elements consisting only of copies
1213  * of the separator are ignored.
1214  * 
1215  * Return value: a newly-allocated string that must be freed with g_free().
1216  **/
1217 gchar *
1218 g_build_path (const gchar *separator,
1219               const gchar *first_element,
1220               ...)
1221 {
1222   gchar *str;
1223   va_list args;
1224
1225   g_return_val_if_fail (separator != NULL, NULL);
1226
1227   va_start (args, first_element);
1228   str = g_build_pathv (separator, first_element, args);
1229   va_end (args);
1230
1231   return str;
1232 }
1233
1234 /**
1235  * g_build_filename:
1236  * @first_element: the first element in the path
1237  * @Varargs: remaining elements in path, terminated by %NULL
1238  * 
1239  * Creates a filename from a series of elements using the correct
1240  * separator for filenames.
1241  *
1242  * On Unix, this function behaves identically to <literal>g_build_path
1243  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1244  *
1245  * On Windows, it takes into account that either the backslash
1246  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1247  * as separator in filenames, but otherwise behaves as on Unix. When
1248  * file pathname separators need to be inserted, the one that last
1249  * previously occurred in the parameters (reading from left to right)
1250  * is used.
1251  *
1252  * No attempt is made to force the resulting filename to be an absolute
1253  * path. If the first element is a relative path, the result will
1254  * be a relative path. 
1255  * 
1256  * Return value: a newly-allocated string that must be freed with g_free().
1257  **/
1258 gchar *
1259 g_build_filename (const gchar *first_element, 
1260                   ...)
1261 {
1262 #ifndef G_OS_WIN32
1263   gchar *str;
1264   va_list args;
1265
1266   va_start (args, first_element);
1267   str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1268   va_end (args);
1269
1270   return str;
1271 #else
1272   /* Code copied from g_build_pathv(), and modifed to use two
1273    * alternative single-character separators.
1274    */
1275   va_list args;
1276   GString *result;
1277   gboolean is_first = TRUE;
1278   gboolean have_leading = FALSE;
1279   const gchar *single_element = NULL;
1280   const gchar *next_element;
1281   const gchar *last_trailing = NULL;
1282   gchar current_separator = '\\';
1283
1284   va_start (args, first_element);
1285
1286   result = g_string_new (NULL);
1287
1288   next_element = first_element;
1289
1290   while (TRUE)
1291     {
1292       const gchar *element;
1293       const gchar *start;
1294       const gchar *end;
1295
1296       if (next_element)
1297         {
1298           element = next_element;
1299           next_element = va_arg (args, gchar *);
1300         }
1301       else
1302         break;
1303
1304       /* Ignore empty elements */
1305       if (!*element)
1306         continue;
1307       
1308       start = element;
1309
1310       if (TRUE)
1311         {
1312           while (start &&
1313                  (*start == '\\' || *start == '/'))
1314             {
1315               current_separator = *start;
1316               start++;
1317             }
1318         }
1319
1320       end = start + strlen (start);
1321       
1322       if (TRUE)
1323         {
1324           while (end >= start + 1 &&
1325                  (end[-1] == '\\' || end[-1] == '/'))
1326             {
1327               current_separator = end[-1];
1328               end--;
1329             }
1330           
1331           last_trailing = end;
1332           while (last_trailing >= element + 1 &&
1333                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1334             last_trailing--;
1335
1336           if (!have_leading)
1337             {
1338               /* If the leading and trailing separator strings are in the
1339                * same element and overlap, the result is exactly that element
1340                */
1341               if (last_trailing <= start)
1342                 single_element = element;
1343                   
1344               g_string_append_len (result, element, start - element);
1345               have_leading = TRUE;
1346             }
1347           else
1348             single_element = NULL;
1349         }
1350
1351       if (end == start)
1352         continue;
1353
1354       if (!is_first)
1355         g_string_append_len (result, &current_separator, 1);
1356       
1357       g_string_append_len (result, start, end - start);
1358       is_first = FALSE;
1359     }
1360
1361   va_end (args);
1362
1363   if (single_element)
1364     {
1365       g_string_free (result, TRUE);
1366       return g_strdup (single_element);
1367     }
1368   else
1369     {
1370       if (last_trailing)
1371         g_string_append (result, last_trailing);
1372   
1373       return g_string_free (result, FALSE);
1374     }
1375 #endif
1376 }
1377
1378 /**
1379  * g_file_read_link:
1380  * @filename: the symbolic link
1381  * @error: return location for a #GError
1382  *
1383  * Reads the contents of the symbolic link @filename like the POSIX
1384  * readlink() function.  The returned string is in the encoding used
1385  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1386  *
1387  * Returns: A newly allocated string with the contents of the symbolic link, 
1388  *          or %NULL if an error occurred.
1389  *
1390  * Since: 2.4
1391  */
1392 gchar *
1393 g_file_read_link (const gchar *filename,
1394                   GError     **error)
1395 {
1396 #ifdef HAVE_READLINK
1397   gchar *buffer;
1398   guint size;
1399   gint read_size;    
1400   
1401   size = 256; 
1402   buffer = g_malloc (size);
1403   
1404   while (TRUE) 
1405     {
1406       read_size = readlink (filename, buffer, size);
1407       if (read_size < 0) {
1408         gchar *display_filename = g_filename_display_name (filename);
1409         g_free (buffer);
1410         g_set_error (error,
1411                      G_FILE_ERROR,
1412                      g_file_error_from_errno (errno),
1413                      _("Failed to read the symbolic link '%s': %s"),
1414                      display_filename, 
1415                      g_strerror (errno));
1416         g_free (display_filename);
1417         
1418         return NULL;
1419       }
1420     
1421       if (read_size < size) 
1422         {
1423           buffer[read_size] = 0;
1424           return buffer;
1425         }
1426       
1427       size *= 2;
1428       buffer = g_realloc (buffer, size);
1429     }
1430 #else
1431   g_set_error (error,
1432                G_FILE_ERROR,
1433                G_FILE_ERROR_INVAL,
1434                _("Symbolic links not supported"));
1435         
1436   return NULL;
1437 #endif
1438 }