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