gfileutils: Add missing g_free() in error path
[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  * see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "config.h"
21 #include "glibconfig.h"
22
23 #include <sys/stat.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <stdlib.h>
33
34 #ifdef G_OS_UNIX
35 #include <unistd.h>
36 #endif
37 #ifdef G_OS_WIN32
38 #include <windows.h>
39 #include <io.h>
40 #endif /* G_OS_WIN32 */
41
42 #ifndef S_ISLNK
43 #define S_ISLNK(x) 0
44 #endif
45
46 #ifndef O_BINARY
47 #define O_BINARY 0
48 #endif
49
50 #include "gfileutils.h"
51
52 #include "gstdio.h"
53 #include "glibintl.h"
54
55 #ifdef HAVE_LINUX_MAGIC_H /* for btrfs check */
56 #include <linux/magic.h>
57 #include <sys/vfs.h>
58 #endif
59
60
61 /**
62  * SECTION:fileutils
63  * @title: File Utilities
64  * @short_description: various file-related functions
65  *
66  * There is a group of functions which wrap the common POSIX functions
67  * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
68  * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
69  * wrappers is to make it possible to handle file names with any Unicode
70  * characters in them on Windows without having to use ifdefs and the
71  * wide character API in the application code.
72  *
73  * The pathname argument should be in the GLib file name encoding.
74  * On POSIX this is the actual on-disk encoding which might correspond
75  * to the locale settings of the process (or the `G_FILENAME_ENCODING`
76  * environment variable), or not.
77  *
78  * On Windows the GLib file name encoding is UTF-8. Note that the
79  * Microsoft C library does not use UTF-8, but has separate APIs for
80  * current system code page and wide characters (UTF-16). The GLib
81  * wrappers call the wide character API if present (on modern Windows
82  * systems), otherwise convert to/from the system code page.
83  *
84  * Another group of functions allows to open and read directories
85  * in the GLib file name encoding. These are g_dir_open(),
86  * g_dir_read_name(), g_dir_rewind(), g_dir_close().
87  */
88
89 /**
90  * GFileError:
91  * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
92  *     the file (or other resource) or processes with special privileges
93  *     can perform the operation.
94  * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
95  *     for writing, or create or remove hard links to it.
96  * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
97  *     allow the attempted operation.
98  * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
99  * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
100  *     doesn't exist" error for ordinary files that are referenced in
101  *     contexts where they are expected to already exist.
102  * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
103  *     a directory is required.
104  * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
105  *     use the device represented by a file you specified, and it
106  *     couldn't find the device. This can mean that the device file was
107  *     installed incorrectly, or that the physical device is missing or
108  *     not correctly attached to the computer.
109  * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
110  *     does not support memory mapping.
111  * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
112  *     modified because it's on a read-only file system.
113  * @G_FILE_ERROR_TXTBSY: Text file busy.
114  * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
115  *     (GLib won't reliably return this, don't pass in pointers to bad
116  *     memory.)
117  * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
118  *     in looking up a file name. This often indicates a cycle of symbolic
119  *     links.
120  * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
121  *     file failed because the disk is full.
122  * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
123  *     more virtual memory because its capacity is full.
124  * @G_FILE_ERROR_MFILE: The current process has too many files open and
125  *     can't open any more. Duplicate descriptors do count toward this
126  *     limit.
127  * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
128  *     entire system.
129  * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
130  *     descriptor that has been closed or reading from a descriptor open
131  *     only for writing (or vice versa).
132  * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
133  *     various kinds of problems with passing the wrong argument to a
134  *     library function.
135  * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
136  *     other end of a pipe. Every library function that returns this
137  *     error code also generates a 'SIGPIPE' signal; this signal
138  *     terminates the program if not handled or blocked. Thus, your
139  *     program will never actually see this code unless it has handled
140  *     or blocked 'SIGPIPE'.
141  * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
142  *     work if you try again later.
143  * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
144  *     occurred and prevented completion of the call. When this
145  *     happens, you should try the call again.
146  * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
147  *    or write errors. i.e. the disk or other physical device hardware
148  *    is returning errors.
149  * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
150  *    file (or other resource) or processes with special privileges can
151  *    perform the operation.
152  * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
153  *    the system is missing some functionality.
154  * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
155  *    is the standard "failed for unspecified reason" error code present
156  *    in all #GError error code enumerations. Returned if no specific
157  *    code applies.
158  *
159  * Values corresponding to @errno codes returned from file operations
160  * on UNIX. Unlike @errno codes, GFileError values are available on
161  * all systems, even Windows. The exact meaning of each code depends
162  * on what sort of file operation you were performing; the UNIX
163  * documentation gives more details. The following error code descriptions
164  * come from the GNU C Library manual, and are under the copyright
165  * of that manual.
166  *
167  * It's not very portable to make detailed assumptions about exactly
168  * which errors will be returned from a given operation. Some errors
169  * don't occur on some systems, etc., sometimes there are subtle
170  * differences in when a system will report a given error, etc.
171  */
172
173 /**
174  * G_FILE_ERROR:
175  *
176  * Error domain for file operations. Errors in this domain will
177  * be from the #GFileError enumeration. See #GError for information
178  * on error domains.
179  */
180
181 /**
182  * GFileTest:
183  * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
184  *     (not a directory). Note that this test will also return %TRUE
185  *     if the tested file is a symlink to a regular file.
186  * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
187  * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
188  * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
189  * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
190  *     be a regular file.
191  *
192  * A test to perform on a file using g_file_test().
193  */
194
195 /**
196  * g_mkdir_with_parents:
197  * @pathname: a pathname in the GLib file name encoding
198  * @mode: permissions to use for newly created directories
199  *
200  * Create a directory if it doesn't already exist. Create intermediate
201  * parent directories as needed, too.
202  *
203  * Returns: 0 if the directory already exists, or was successfully
204  * created. Returns -1 if an error occurred, with errno set.
205  *
206  * Since: 2.8
207  */
208 int
209 g_mkdir_with_parents (const gchar *pathname,
210                       int          mode)
211 {
212   gchar *fn, *p;
213
214   if (pathname == NULL || *pathname == '\0')
215     {
216       errno = EINVAL;
217       return -1;
218     }
219
220   fn = g_strdup (pathname);
221
222   if (g_path_is_absolute (fn))
223     p = (gchar *) g_path_skip_root (fn);
224   else
225     p = fn;
226
227   do
228     {
229       while (*p && !G_IS_DIR_SEPARATOR (*p))
230         p++;
231       
232       if (!*p)
233         p = NULL;
234       else
235         *p = '\0';
236       
237       if (!g_file_test (fn, G_FILE_TEST_EXISTS))
238         {
239           if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
240             {
241               int errno_save = errno;
242               g_free (fn);
243               errno = errno_save;
244               return -1;
245             }
246         }
247       else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
248         {
249           g_free (fn);
250           errno = ENOTDIR;
251           return -1;
252         }
253       if (p)
254         {
255           *p++ = G_DIR_SEPARATOR;
256           while (*p && G_IS_DIR_SEPARATOR (*p))
257             p++;
258         }
259     }
260   while (p);
261
262   g_free (fn);
263
264   return 0;
265 }
266
267 /**
268  * g_file_test:
269  * @filename: a filename to test in the GLib file name encoding
270  * @test: bitfield of #GFileTest flags
271  * 
272  * Returns %TRUE if any of the tests in the bitfield @test are
273  * %TRUE. For example, `(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)`
274  * will return %TRUE if the file exists; the check whether it's a
275  * directory doesn't matter since the existence test is %TRUE. With
276  * the current set of available tests, there's no point passing in
277  * more than one test at a time.
278  * 
279  * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
280  * so for a symbolic link to a regular file g_file_test() will return
281  * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
282  *
283  * Note, that for a dangling symbolic link g_file_test() will return
284  * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
285  *
286  * You should never use g_file_test() to test whether it is safe
287  * to perform an operation, because there is always the possibility
288  * of the condition changing before you actually perform the operation.
289  * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
290  * to know whether it is safe to write to a file without being
291  * tricked into writing into a different location. It doesn't work!
292  * |[<!-- language="C" -->
293  *  // DON'T DO THIS
294  *  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) 
295  *    {
296  *      fd = g_open (filename, O_WRONLY);
297  *      // write to fd
298  *    }
299  * ]|
300  *
301  * Another thing to note is that %G_FILE_TEST_EXISTS and
302  * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
303  * system call. This usually doesn't matter, but if your program
304  * is setuid or setgid it means that these tests will give you
305  * the answer for the real user ID and group ID, rather than the
306  * effective user ID and group ID.
307  *
308  * On Windows, there are no symlinks, so testing for
309  * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
310  * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
311  * its name indicates that it is executable, checking for well-known
312  * extensions and those listed in the `PATHEXT` environment variable.
313  *
314  * Returns: whether a test was %TRUE
315  **/
316 gboolean
317 g_file_test (const gchar *filename,
318              GFileTest    test)
319 {
320 #ifdef G_OS_WIN32
321 /* stuff missing in std vc6 api */
322 #  ifndef INVALID_FILE_ATTRIBUTES
323 #    define INVALID_FILE_ATTRIBUTES -1
324 #  endif
325 #  ifndef FILE_ATTRIBUTE_DEVICE
326 #    define FILE_ATTRIBUTE_DEVICE 64
327 #  endif
328   int attributes;
329   wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
330
331   if (wfilename == NULL)
332     return FALSE;
333
334   attributes = GetFileAttributesW (wfilename);
335
336   g_free (wfilename);
337
338   if (attributes == INVALID_FILE_ATTRIBUTES)
339     return FALSE;
340
341   if (test & G_FILE_TEST_EXISTS)
342     return TRUE;
343       
344   if (test & G_FILE_TEST_IS_REGULAR)
345     {
346       if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
347         return TRUE;
348     }
349
350   if (test & G_FILE_TEST_IS_DIR)
351     {
352       if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
353         return TRUE;
354     }
355
356   /* "while" so that we can exit this "loop" with a simple "break" */
357   while (test & G_FILE_TEST_IS_EXECUTABLE)
358     {
359       const gchar *lastdot = strrchr (filename, '.');
360       const gchar *pathext = NULL, *p;
361       int extlen;
362
363       if (lastdot == NULL)
364         break;
365
366       if (_stricmp (lastdot, ".exe") == 0 ||
367           _stricmp (lastdot, ".cmd") == 0 ||
368           _stricmp (lastdot, ".bat") == 0 ||
369           _stricmp (lastdot, ".com") == 0)
370         return TRUE;
371
372       /* Check if it is one of the types listed in %PATHEXT% */
373
374       pathext = g_getenv ("PATHEXT");
375       if (pathext == NULL)
376         break;
377
378       pathext = g_utf8_casefold (pathext, -1);
379
380       lastdot = g_utf8_casefold (lastdot, -1);
381       extlen = strlen (lastdot);
382
383       p = pathext;
384       while (TRUE)
385         {
386           const gchar *q = strchr (p, ';');
387           if (q == NULL)
388             q = p + strlen (p);
389           if (extlen == q - p &&
390               memcmp (lastdot, p, extlen) == 0)
391             {
392               g_free ((gchar *) pathext);
393               g_free ((gchar *) lastdot);
394               return TRUE;
395             }
396           if (*q)
397             p = q + 1;
398           else
399             break;
400         }
401
402       g_free ((gchar *) pathext);
403       g_free ((gchar *) lastdot);
404       break;
405     }
406
407   return FALSE;
408 #else
409   if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
410     return TRUE;
411   
412   if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
413     {
414       if (getuid () != 0)
415         return TRUE;
416
417       /* For root, on some POSIX systems, access (filename, X_OK)
418        * will succeed even if no executable bits are set on the
419        * file. We fall through to a stat test to avoid that.
420        */
421     }
422   else
423     test &= ~G_FILE_TEST_IS_EXECUTABLE;
424
425   if (test & G_FILE_TEST_IS_SYMLINK)
426     {
427       struct stat s;
428
429       if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
430         return TRUE;
431     }
432   
433   if (test & (G_FILE_TEST_IS_REGULAR |
434               G_FILE_TEST_IS_DIR |
435               G_FILE_TEST_IS_EXECUTABLE))
436     {
437       struct stat s;
438       
439       if (stat (filename, &s) == 0)
440         {
441           if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
442             return TRUE;
443           
444           if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
445             return TRUE;
446
447           /* The extra test for root when access (file, X_OK) succeeds.
448            */
449           if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
450               ((s.st_mode & S_IXOTH) ||
451                (s.st_mode & S_IXUSR) ||
452                (s.st_mode & S_IXGRP)))
453             return TRUE;
454         }
455     }
456
457   return FALSE;
458 #endif
459 }
460
461 G_DEFINE_QUARK (g-file-error-quark, g_file_error)
462
463 /**
464  * g_file_error_from_errno:
465  * @err_no: an "errno" value
466  * 
467  * Gets a #GFileError constant based on the passed-in @err_no.
468  * For example, if you pass in `EEXIST` this function returns
469  * #G_FILE_ERROR_EXIST. Unlike `errno` values, you can portably
470  * assume that all #GFileError values will exist.
471  *
472  * Normally a #GFileError value goes into a #GError returned
473  * from a function that manipulates files. So you would use
474  * g_file_error_from_errno() when constructing a #GError.
475  * 
476  * Returns: #GFileError corresponding to the given @errno
477  **/
478 GFileError
479 g_file_error_from_errno (gint err_no)
480 {
481   switch (err_no)
482     {
483 #ifdef EEXIST
484     case EEXIST:
485       return G_FILE_ERROR_EXIST;
486 #endif
487
488 #ifdef EISDIR
489     case EISDIR:
490       return G_FILE_ERROR_ISDIR;
491 #endif
492
493 #ifdef EACCES
494     case EACCES:
495       return G_FILE_ERROR_ACCES;
496 #endif
497
498 #ifdef ENAMETOOLONG
499     case ENAMETOOLONG:
500       return G_FILE_ERROR_NAMETOOLONG;
501 #endif
502
503 #ifdef ENOENT
504     case ENOENT:
505       return G_FILE_ERROR_NOENT;
506 #endif
507
508 #ifdef ENOTDIR
509     case ENOTDIR:
510       return G_FILE_ERROR_NOTDIR;
511 #endif
512
513 #ifdef ENXIO
514     case ENXIO:
515       return G_FILE_ERROR_NXIO;
516 #endif
517
518 #ifdef ENODEV
519     case ENODEV:
520       return G_FILE_ERROR_NODEV;
521 #endif
522
523 #ifdef EROFS
524     case EROFS:
525       return G_FILE_ERROR_ROFS;
526 #endif
527
528 #ifdef ETXTBSY
529     case ETXTBSY:
530       return G_FILE_ERROR_TXTBSY;
531 #endif
532
533 #ifdef EFAULT
534     case EFAULT:
535       return G_FILE_ERROR_FAULT;
536 #endif
537
538 #ifdef ELOOP
539     case ELOOP:
540       return G_FILE_ERROR_LOOP;
541 #endif
542
543 #ifdef ENOSPC
544     case ENOSPC:
545       return G_FILE_ERROR_NOSPC;
546 #endif
547
548 #ifdef ENOMEM
549     case ENOMEM:
550       return G_FILE_ERROR_NOMEM;
551 #endif
552
553 #ifdef EMFILE
554     case EMFILE:
555       return G_FILE_ERROR_MFILE;
556 #endif
557
558 #ifdef ENFILE
559     case ENFILE:
560       return G_FILE_ERROR_NFILE;
561 #endif
562
563 #ifdef EBADF
564     case EBADF:
565       return G_FILE_ERROR_BADF;
566 #endif
567
568 #ifdef EINVAL
569     case EINVAL:
570       return G_FILE_ERROR_INVAL;
571 #endif
572
573 #ifdef EPIPE
574     case EPIPE:
575       return G_FILE_ERROR_PIPE;
576 #endif
577
578 #ifdef EAGAIN
579     case EAGAIN:
580       return G_FILE_ERROR_AGAIN;
581 #endif
582
583 #ifdef EINTR
584     case EINTR:
585       return G_FILE_ERROR_INTR;
586 #endif
587
588 #ifdef EIO
589     case EIO:
590       return G_FILE_ERROR_IO;
591 #endif
592
593 #ifdef EPERM
594     case EPERM:
595       return G_FILE_ERROR_PERM;
596 #endif
597
598 #ifdef ENOSYS
599     case ENOSYS:
600       return G_FILE_ERROR_NOSYS;
601 #endif
602
603     default:
604       return G_FILE_ERROR_FAILED;
605     }
606 }
607
608 static char *
609 format_error_message (const gchar  *filename,
610                       const gchar  *format_string) G_GNUC_FORMAT(2);
611
612 #pragma GCC diagnostic push
613 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
614
615 static char *
616 format_error_message (const gchar  *filename,
617                       const gchar  *format_string)
618 {
619   gint saved_errno = errno;
620   gchar *display_name;
621   gchar *msg;
622
623   display_name = g_filename_display_name (filename);
624   msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
625   g_free (display_name);
626
627   return msg;
628 }
629
630 #pragma GCC diagnostic pop
631
632 /* format string must have two '%s':
633  *
634  *   - the place for the filename
635  *   - the place for the strerror
636  */
637 static void
638 set_file_error (GError      **error,
639                 const gchar  *filename,
640                 const gchar  *format_string)
641 {
642   int saved_errno = errno;
643   char *msg = format_error_message (filename, format_string);
644
645   g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
646                        msg);
647   g_free (msg);
648 }
649
650 static gboolean
651 get_contents_stdio (const gchar  *filename,
652                     FILE         *f,
653                     gchar       **contents,
654                     gsize        *length,
655                     GError      **error)
656 {
657   gchar buf[4096];
658   gsize bytes;  /* always <= sizeof(buf) */
659   gchar *str = NULL;
660   gsize total_bytes = 0;
661   gsize total_allocated = 0;
662   gchar *tmp;
663   gchar *display_filename;
664
665   g_assert (f != NULL);
666
667   while (!feof (f))
668     {
669       gint save_errno;
670
671       bytes = fread (buf, 1, sizeof (buf), f);
672       save_errno = errno;
673
674       if (total_bytes > G_MAXSIZE - bytes)
675           goto file_too_large;
676
677       /* Possibility of overflow eliminated above. */
678       while (total_bytes + bytes >= total_allocated)
679         {
680           if (str)
681             {
682               if (total_allocated > G_MAXSIZE / 2)
683                   goto file_too_large;
684               total_allocated *= 2;
685             }
686           else
687             {
688               total_allocated = MIN (bytes + 1, sizeof (buf));
689             }
690
691           tmp = g_try_realloc (str, total_allocated);
692
693           if (tmp == NULL)
694             {
695               display_filename = g_filename_display_name (filename);
696               g_set_error (error,
697                            G_FILE_ERROR,
698                            G_FILE_ERROR_NOMEM,
699                            g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file \"%s\"", "Could not allocate %lu bytes to read file \"%s\"", (gulong)total_allocated),
700                            (gulong) total_allocated,
701                            display_filename);
702               g_free (display_filename);
703
704               goto error;
705             }
706
707           str = tmp;
708         }
709
710       if (ferror (f))
711         {
712           display_filename = g_filename_display_name (filename);
713           g_set_error (error,
714                        G_FILE_ERROR,
715                        g_file_error_from_errno (save_errno),
716                        _("Error reading file '%s': %s"),
717                        display_filename,
718                        g_strerror (save_errno));
719           g_free (display_filename);
720
721           goto error;
722         }
723
724       g_assert (str != NULL);
725       memcpy (str + total_bytes, buf, bytes);
726
727       total_bytes += bytes;
728     }
729
730   fclose (f);
731
732   if (total_allocated == 0)
733     {
734       str = g_new (gchar, 1);
735       total_bytes = 0;
736     }
737
738   str[total_bytes] = '\0';
739
740   if (length)
741     *length = total_bytes;
742
743   *contents = str;
744
745   return TRUE;
746
747  file_too_large:
748   display_filename = g_filename_display_name (filename);
749   g_set_error (error,
750                G_FILE_ERROR,
751                G_FILE_ERROR_FAILED,
752                _("File \"%s\" is too large"),
753                display_filename);
754   g_free (display_filename);
755
756  error:
757
758   g_free (str);
759   fclose (f);
760
761   return FALSE;
762 }
763
764 #ifndef G_OS_WIN32
765
766 static gboolean
767 get_contents_regfile (const gchar  *filename,
768                       struct stat  *stat_buf,
769                       gint          fd,
770                       gchar       **contents,
771                       gsize        *length,
772                       GError      **error)
773 {
774   gchar *buf;
775   gsize bytes_read;
776   gsize size;
777   gsize alloc_size;
778   gchar *display_filename;
779   
780   size = stat_buf->st_size;
781
782   alloc_size = size + 1;
783   buf = g_try_malloc (alloc_size);
784
785   if (buf == NULL)
786     {
787       display_filename = g_filename_display_name (filename);
788       g_set_error (error,
789                    G_FILE_ERROR,
790                    G_FILE_ERROR_NOMEM,
791                            g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file \"%s\"", "Could not allocate %lu bytes to read file \"%s\"", (gulong)alloc_size),
792                    (gulong) alloc_size, 
793                    display_filename);
794       g_free (display_filename);
795       goto error;
796     }
797   
798   bytes_read = 0;
799   while (bytes_read < size)
800     {
801       gssize rc;
802           
803       rc = read (fd, buf + bytes_read, size - bytes_read);
804
805       if (rc < 0)
806         {
807           if (errno != EINTR) 
808             {
809               int save_errno = errno;
810
811               g_free (buf);
812               display_filename = g_filename_display_name (filename);
813               g_set_error (error,
814                            G_FILE_ERROR,
815                            g_file_error_from_errno (save_errno),
816                            _("Failed to read from file '%s': %s"),
817                            display_filename, 
818                            g_strerror (save_errno));
819               g_free (display_filename);
820               goto error;
821             }
822         }
823       else if (rc == 0)
824         break;
825       else
826         bytes_read += rc;
827     }
828       
829   buf[bytes_read] = '\0';
830
831   if (length)
832     *length = bytes_read;
833   
834   *contents = buf;
835
836   close (fd);
837
838   return TRUE;
839
840  error:
841
842   close (fd);
843   
844   return FALSE;
845 }
846
847 static gboolean
848 get_contents_posix (const gchar  *filename,
849                     gchar       **contents,
850                     gsize        *length,
851                     GError      **error)
852 {
853   struct stat stat_buf;
854   gint fd;
855
856   /* O_BINARY useful on Cygwin */
857   fd = open (filename, O_RDONLY|O_BINARY);
858
859   if (fd < 0)
860     {
861       set_file_error (error,
862                       filename,
863                       _("Failed to open file '%s': %s"));
864
865       return FALSE;
866     }
867
868   /* I don't think this will ever fail, aside from ENOMEM, but. */
869   if (fstat (fd, &stat_buf) < 0)
870     {
871       set_file_error (error,
872                       filename,
873                       _("Failed to get attributes of file '%s': fstat() failed: %s"));
874       close (fd);
875
876       return FALSE;
877     }
878
879   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
880     {
881       gboolean retval = get_contents_regfile (filename,
882                                               &stat_buf,
883                                               fd,
884                                               contents,
885                                               length,
886                                               error);
887
888       return retval;
889     }
890   else
891     {
892       FILE *f;
893       gboolean retval;
894
895       f = fdopen (fd, "r");
896       
897       if (f == NULL)
898         {
899           set_file_error (error,
900                           filename,
901                           _("Failed to open file '%s': fdopen() failed: %s"));
902
903           return FALSE;
904         }
905   
906       retval = get_contents_stdio (filename, f, contents, length, error);
907
908       return retval;
909     }
910 }
911
912 #else  /* G_OS_WIN32 */
913
914 static gboolean
915 get_contents_win32 (const gchar  *filename,
916                     gchar       **contents,
917                     gsize        *length,
918                     GError      **error)
919 {
920   FILE *f;
921   gboolean retval;
922   
923   f = g_fopen (filename, "rb");
924
925   if (f == NULL)
926     {
927       set_file_error (error,
928                       filename,
929                       _("Failed to open file '%s': %s"));
930
931       return FALSE;
932     }
933   
934   retval = get_contents_stdio (filename, f, contents, length, error);
935
936   return retval;
937 }
938
939 #endif
940
941 /**
942  * g_file_get_contents:
943  * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
944  * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
945  *     the returned string
946  * @length: (allow-none): location to store length in bytes of the contents, or %NULL
947  * @error: return location for a #GError, or %NULL
948  *
949  * Reads an entire file into allocated memory, with good error
950  * checking.
951  *
952  * If the call was successful, it returns %TRUE and sets @contents to the file
953  * contents and @length to the length of the file contents in bytes. The string
954  * stored in @contents will be nul-terminated, so for text files you can pass
955  * %NULL for the @length argument. If the call was not successful, it returns
956  * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
957  * codes are those in the #GFileError enumeration. In the error case,
958  * @contents is set to %NULL and @length is set to zero.
959  *
960  * Returns: %TRUE on success, %FALSE if an error occurred
961  **/
962 gboolean
963 g_file_get_contents (const gchar  *filename,
964                      gchar       **contents,
965                      gsize        *length,
966                      GError      **error)
967 {  
968   g_return_val_if_fail (filename != NULL, FALSE);
969   g_return_val_if_fail (contents != NULL, FALSE);
970
971   *contents = NULL;
972   if (length)
973     *length = 0;
974
975 #ifdef G_OS_WIN32
976   return get_contents_win32 (filename, contents, length, error);
977 #else
978   return get_contents_posix (filename, contents, length, error);
979 #endif
980 }
981
982 static gboolean
983 rename_file (const char  *old_name,
984              const char  *new_name,
985              GError     **err)
986 {
987   errno = 0;
988   if (g_rename (old_name, new_name) == -1)
989     {
990       int save_errno = errno;
991       gchar *display_old_name = g_filename_display_name (old_name);
992       gchar *display_new_name = g_filename_display_name (new_name);
993
994       g_set_error (err,
995                    G_FILE_ERROR,
996                    g_file_error_from_errno (save_errno),
997                    _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
998                    display_old_name,
999                    display_new_name,
1000                    g_strerror (save_errno));
1001
1002       g_free (display_old_name);
1003       g_free (display_new_name);
1004       
1005       return FALSE;
1006     }
1007   
1008   return TRUE;
1009 }
1010
1011 static gchar *
1012 write_to_temp_file (const gchar  *contents,
1013                     gssize        length,
1014                     const gchar  *dest_file,
1015                     GError      **err)
1016 {
1017   gchar *tmp_name;
1018   gchar *retval;
1019   gint fd;
1020
1021   retval = NULL;
1022
1023   tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
1024
1025   errno = 0;
1026   fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
1027
1028   if (fd == -1)
1029     {
1030       set_file_error (err, tmp_name, _("Failed to create file '%s': %s"));
1031       goto out;
1032     }
1033
1034 #ifdef HAVE_FALLOCATE
1035   if (length > 0)
1036     {
1037       /* We do this on a 'best effort' basis... It may not be supported
1038        * on the underlying filesystem.
1039        */
1040       (void) fallocate (fd, 0, 0, length);
1041     }
1042 #endif
1043   while (length > 0)
1044     {
1045       gssize s;
1046
1047       s = write (fd, contents, length);
1048
1049       if (s < 0)
1050         {
1051           if (errno == EINTR)
1052             continue;
1053
1054           set_file_error (err, tmp_name, _("Failed to write file '%s': write() failed: %s"));
1055           close (fd);
1056           g_unlink (tmp_name);
1057
1058           goto out;
1059         }
1060
1061       g_assert (s <= length);
1062
1063       contents += s;
1064       length -= s;
1065     }
1066
1067 #ifdef BTRFS_SUPER_MAGIC
1068   {
1069     struct statfs buf;
1070
1071     /* On Linux, on btrfs, skip the fsync since rename-over-existing is
1072      * guaranteed to be atomic and this is the only case in which we
1073      * would fsync() anyway.
1074      */
1075
1076     if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
1077       goto no_fsync;
1078   }
1079 #endif
1080
1081 #ifdef HAVE_FSYNC
1082   {
1083     struct stat statbuf;
1084
1085     errno = 0;
1086     /* If the final destination exists and is > 0 bytes, we want to sync the
1087      * newly written file to ensure the data is on disk when we rename over
1088      * the destination. Otherwise if we get a system crash we can lose both
1089      * the new and the old file on some filesystems. (I.E. those that don't
1090      * guarantee the data is written to the disk before the metadata.)
1091      */
1092     if (g_lstat (dest_file, &statbuf) == 0 && statbuf.st_size > 0 && fsync (fd) != 0)
1093       {
1094         set_file_error (err, tmp_name, _("Failed to write file '%s': fsync() failed: %s"));
1095         close (fd);
1096         g_unlink (tmp_name);
1097
1098         goto out;
1099       }
1100   }
1101 #endif
1102
1103 #ifdef BTRFS_SUPER_MAGIC
1104  no_fsync:
1105 #endif
1106
1107   errno = 0;
1108   if (!g_close (fd, err))
1109     {
1110       g_unlink (tmp_name);
1111
1112       goto out;
1113     }
1114
1115   retval = g_strdup (tmp_name);
1116
1117  out:
1118   g_free (tmp_name);
1119
1120   return retval;
1121 }
1122
1123 /**
1124  * g_file_set_contents:
1125  * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1126  *   encoding
1127  * @contents: (array length=length) (element-type guint8): string to write to the file
1128  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1129  * @error: return location for a #GError, or %NULL
1130  *
1131  * Writes all of @contents to a file named @filename, with good error checking.
1132  * If a file called @filename already exists it will be overwritten.
1133  *
1134  * This write is atomic in the sense that it is first written to a temporary
1135  * file which is then renamed to the final name. Notes:
1136  *
1137  * - On UNIX, if @filename already exists hard links to @filename will break.
1138  *   Also since the file is recreated, existing permissions, access control
1139  *   lists, metadata etc. may be lost. If @filename is a symbolic link,
1140  *   the link itself will be replaced, not the linked file.
1141  *
1142  * - On Windows renaming a file will not remove an existing file with the
1143  *   new name, so on Windows there is a race condition between the existing
1144  *   file being removed and the temporary file being renamed.
1145  *
1146  * - On Windows there is no way to remove a file that is open to some
1147  *   process, or mapped into memory. Thus, this function will fail if
1148  *   @filename already exists and is open.
1149  *
1150  * If the call was successful, it returns %TRUE. If the call was not successful,
1151  * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1152  * Possible error codes are those in the #GFileError enumeration.
1153  *
1154  * Note that the name for the temporary file is constructed by appending up
1155  * to 7 characters to @filename.
1156  *
1157  * Returns: %TRUE on success, %FALSE if an error occurred
1158  *
1159  * Since: 2.8
1160  */
1161 gboolean
1162 g_file_set_contents (const gchar  *filename,
1163                      const gchar  *contents,
1164                      gssize        length,
1165                      GError      **error)
1166 {
1167   gchar *tmp_filename;
1168   gboolean retval;
1169   GError *rename_error = NULL;
1170   
1171   g_return_val_if_fail (filename != NULL, FALSE);
1172   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1173   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1174   g_return_val_if_fail (length >= -1, FALSE);
1175   
1176   if (length == -1)
1177     length = strlen (contents);
1178
1179   tmp_filename = write_to_temp_file (contents, length, filename, error);
1180   
1181   if (!tmp_filename)
1182     {
1183       retval = FALSE;
1184       goto out;
1185     }
1186
1187   if (!rename_file (tmp_filename, filename, &rename_error))
1188     {
1189 #ifndef G_OS_WIN32
1190
1191       g_unlink (tmp_filename);
1192       g_propagate_error (error, rename_error);
1193       retval = FALSE;
1194       goto out;
1195
1196 #else /* G_OS_WIN32 */
1197       
1198       /* Renaming failed, but on Windows this may just mean
1199        * the file already exists. So if the target file
1200        * exists, try deleting it and do the rename again.
1201        */
1202       if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1203         {
1204           g_unlink (tmp_filename);
1205           g_propagate_error (error, rename_error);
1206           retval = FALSE;
1207           goto out;
1208         }
1209
1210       g_error_free (rename_error);
1211       
1212       if (g_unlink (filename) == -1)
1213         {
1214           set_file_error (error,
1215                           filename,
1216                           _("Existing file '%s' could not be removed: g_unlink() failed: %s"));
1217           g_unlink (tmp_filename);
1218           retval = FALSE;
1219           goto out;
1220         }
1221       
1222       if (!rename_file (tmp_filename, filename, error))
1223         {
1224           g_unlink (tmp_filename);
1225           retval = FALSE;
1226           goto out;
1227         }
1228
1229 #endif
1230     }
1231
1232   retval = TRUE;
1233   
1234  out:
1235   g_free (tmp_filename);
1236   return retval;
1237 }
1238
1239 /*
1240  * get_tmp_file based on the mkstemp implementation from the GNU C library.
1241  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1242  */
1243 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1244
1245 static gint
1246 get_tmp_file (gchar            *tmpl,
1247               GTmpFileCallback  f,
1248               int               flags,
1249               int               mode)
1250 {
1251   char *XXXXXX;
1252   int count, fd;
1253   static const char letters[] =
1254     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1255   static const int NLETTERS = sizeof (letters) - 1;
1256   glong value;
1257   GTimeVal tv;
1258   static int counter = 0;
1259
1260   g_return_val_if_fail (tmpl != NULL, -1);
1261
1262   /* find the last occurrence of "XXXXXX" */
1263   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1264
1265   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1266     {
1267       errno = EINVAL;
1268       return -1;
1269     }
1270
1271   /* Get some more or less random data.  */
1272   g_get_current_time (&tv);
1273   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1274
1275   for (count = 0; count < 100; value += 7777, ++count)
1276     {
1277       glong v = value;
1278
1279       /* Fill in the random bits.  */
1280       XXXXXX[0] = letters[v % NLETTERS];
1281       v /= NLETTERS;
1282       XXXXXX[1] = letters[v % NLETTERS];
1283       v /= NLETTERS;
1284       XXXXXX[2] = letters[v % NLETTERS];
1285       v /= NLETTERS;
1286       XXXXXX[3] = letters[v % NLETTERS];
1287       v /= NLETTERS;
1288       XXXXXX[4] = letters[v % NLETTERS];
1289       v /= NLETTERS;
1290       XXXXXX[5] = letters[v % NLETTERS];
1291
1292       fd = f (tmpl, flags, mode);
1293
1294       if (fd >= 0)
1295         return fd;
1296       else if (errno != EEXIST)
1297         /* Any other error will apply also to other names we might
1298          *  try, and there are 2^32 or so of them, so give up now.
1299          */
1300         return -1;
1301     }
1302
1303   /* We got out of the loop because we ran out of combinations to try.  */
1304   errno = EEXIST;
1305   return -1;
1306 }
1307
1308 /* Some GTmpFileCallback implementations.
1309  *
1310  * Note: we cannot use open() or g_open() directly because even though
1311  * they appear compatible, they may be vararg functions and calling
1312  * varargs functions through a non-varargs type is undefined.
1313  */
1314 static gint
1315 wrap_g_mkdir (const gchar *filename,
1316               int          flags G_GNUC_UNUSED,
1317               int          mode)
1318 {
1319   /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1320   return g_mkdir (filename, mode);
1321 }
1322
1323 static gint
1324 wrap_g_open (const gchar *filename,
1325                 int          flags,
1326                 int          mode)
1327 {
1328   return g_open (filename, flags, mode);
1329 }
1330
1331 /**
1332  * g_mkdtemp_full:
1333  * @tmpl: (type filename): template directory name
1334  * @mode: permissions to create the temporary directory with
1335  *
1336  * Creates a temporary directory. See the mkdtemp() documentation
1337  * on most UNIX-like systems.
1338  *
1339  * The parameter is a string that should follow the rules for
1340  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1341  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1342  * sequence does not have to occur at the very end of the template
1343  * and you can pass a @mode. The X string will be modified to form
1344  * the name of a directory that didn't exist. The string should be
1345  * in the GLib file name encoding. Most importantly, on Windows it
1346  * should be in UTF-8.
1347  *
1348  * Returns: A pointer to @tmpl, which has been modified
1349  *     to hold the directory name. In case of errors, %NULL is
1350  *     returned, and %errno will be set.
1351  *
1352  * Since: 2.30
1353  */
1354 gchar *
1355 g_mkdtemp_full (gchar *tmpl,
1356                 gint   mode)
1357 {
1358   if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1359     return NULL;
1360   else
1361     return tmpl;
1362 }
1363
1364 /**
1365  * g_mkdtemp:
1366  * @tmpl: (type filename): template directory name
1367  *
1368  * Creates a temporary directory. See the mkdtemp() documentation
1369  * on most UNIX-like systems.
1370  *
1371  * The parameter is a string that should follow the rules for
1372  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1373  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1374  * sequence does not have to occur at the very end of the template
1375  * and you can pass a @mode and additional @flags. The X string will
1376  * be modified to form the name of a directory that didn't exist.
1377  * The string should be in the GLib file name encoding. Most importantly,
1378  * on Windows it should be in UTF-8.
1379  *
1380  * Returns: A pointer to @tmpl, which has been modified
1381  *     to hold the directory name.  In case of errors, %NULL is
1382  *     returned and %errno will be set.
1383  *
1384  * Since: 2.30
1385  */
1386 gchar *
1387 g_mkdtemp (gchar *tmpl)
1388 {
1389   return g_mkdtemp_full (tmpl, 0700);
1390 }
1391
1392 /**
1393  * g_mkstemp_full:
1394  * @tmpl: (type filename): template filename
1395  * @flags: flags to pass to an open() call in addition to O_EXCL
1396  *     and O_CREAT, which are passed automatically
1397  * @mode: permissions to create the temporary file with
1398  *
1399  * Opens a temporary file. See the mkstemp() documentation
1400  * on most UNIX-like systems.
1401  *
1402  * The parameter is a string that should follow the rules for
1403  * mkstemp() templates, i.e. contain the string "XXXXXX".
1404  * g_mkstemp_full() is slightly more flexible than mkstemp()
1405  * in that the sequence does not have to occur at the very end of the
1406  * template and you can pass a @mode and additional @flags. The X
1407  * string will be modified to form the name of a file that didn't exist.
1408  * The string should be in the GLib file name encoding. Most importantly,
1409  * on Windows it should be in UTF-8.
1410  *
1411  * Returns: A file handle (as from open()) to the file
1412  *     opened for reading and writing. The file handle should be
1413  *     closed with close(). In case of errors, -1 is returned
1414  *     and %errno will be set.
1415  *
1416  * Since: 2.22
1417  */
1418 gint
1419 g_mkstemp_full (gchar *tmpl,
1420                 gint   flags,
1421                 gint   mode)
1422 {
1423   /* tmpl is in UTF-8 on Windows, thus use g_open() */
1424   return get_tmp_file (tmpl, wrap_g_open,
1425                        flags | O_CREAT | O_EXCL, mode);
1426 }
1427
1428 /**
1429  * g_mkstemp:
1430  * @tmpl: (type filename): template filename
1431  *
1432  * Opens a temporary file. See the mkstemp() documentation
1433  * on most UNIX-like systems.
1434  *
1435  * The parameter is a string that should follow the rules for
1436  * mkstemp() templates, i.e. contain the string "XXXXXX".
1437  * g_mkstemp() is slightly more flexible than mkstemp() in that the
1438  * sequence does not have to occur at the very end of the template.
1439  * The X string will be modified to form the name of a file that
1440  * didn't exist. The string should be in the GLib file name encoding.
1441  * Most importantly, on Windows it should be in UTF-8.
1442  *
1443  * Returns: A file handle (as from open()) to the file
1444  *     opened for reading and writing. The file is opened in binary
1445  *     mode on platforms where there is a difference. The file handle
1446  *     should be closed with close(). In case of errors, -1 is
1447  *     returned and %errno will be set.
1448  */
1449 gint
1450 g_mkstemp (gchar *tmpl)
1451 {
1452   return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1453 }
1454
1455 static gint
1456 g_get_tmp_name (const gchar      *tmpl,
1457                 gchar           **name_used,
1458                 GTmpFileCallback  f,
1459                 gint              flags,
1460                 gint              mode,
1461                 GError          **error)
1462 {
1463   int retval;
1464   const char *tmpdir;
1465   const char *sep;
1466   char *fulltemplate;
1467   const char *slash;
1468
1469   if (tmpl == NULL)
1470     tmpl = ".XXXXXX";
1471
1472   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1473 #ifdef G_OS_WIN32
1474       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1475 #endif
1476       )
1477     {
1478       gchar *display_tmpl = g_filename_display_name (tmpl);
1479       char c[2];
1480       c[0] = *slash;
1481       c[1] = '\0';
1482
1483       g_set_error (error,
1484                    G_FILE_ERROR,
1485                    G_FILE_ERROR_FAILED,
1486                    _("Template '%s' invalid, should not contain a '%s'"),
1487                    display_tmpl, c);
1488       g_free (display_tmpl);
1489
1490       return -1;
1491     }
1492
1493   if (strstr (tmpl, "XXXXXX") == NULL)
1494     {
1495       gchar *display_tmpl = g_filename_display_name (tmpl);
1496       g_set_error (error,
1497                    G_FILE_ERROR,
1498                    G_FILE_ERROR_FAILED,
1499                    _("Template '%s' doesn't contain XXXXXX"),
1500                    display_tmpl);
1501       g_free (display_tmpl);
1502       return -1;
1503     }
1504
1505   tmpdir = g_get_tmp_dir ();
1506
1507   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1508     sep = "";
1509   else
1510     sep = G_DIR_SEPARATOR_S;
1511
1512   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1513
1514   retval = get_tmp_file (fulltemplate, f, flags, mode);
1515   if (retval == -1)
1516     {
1517       set_file_error (error,
1518                       fulltemplate,
1519                       _("Failed to create file '%s': %s"));
1520       g_free (fulltemplate);
1521       return -1;
1522     }
1523
1524   *name_used = fulltemplate;
1525
1526   return retval;
1527 }
1528
1529 /**
1530  * g_file_open_tmp:
1531  * @tmpl: (type filename) (allow-none): Template for file name, as in
1532  *     g_mkstemp(), basename only, or %NULL for a default template
1533  * @name_used: (out) (type filename): location to store actual name used,
1534  *     or %NULL
1535  * @error: return location for a #GError
1536  *
1537  * Opens a file for writing in the preferred directory for temporary
1538  * files (as returned by g_get_tmp_dir()).
1539  *
1540  * @tmpl should be a string in the GLib file name encoding containing
1541  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1542  * However, unlike these functions, the template should only be a
1543  * basename, no directory components are allowed. If template is
1544  * %NULL, a default template is used.
1545  *
1546  * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1547  * modified, and might thus be a read-only literal string.
1548  *
1549  * Upon success, and if @name_used is non-%NULL, the actual name used
1550  * is returned in @name_used. This string should be freed with g_free()
1551  * when not needed any longer. The returned name is in the GLib file
1552  * name encoding.
1553  *
1554  * Returns: A file handle (as from open()) to the file opened for
1555  *     reading and writing. The file is opened in binary mode on platforms
1556  *     where there is a difference. The file handle should be closed with
1557  *     close(). In case of errors, -1 is returned and @error will be set.
1558  */
1559 gint
1560 g_file_open_tmp (const gchar  *tmpl,
1561                  gchar       **name_used,
1562                  GError      **error)
1563 {
1564   gchar *fulltemplate;
1565   gint result;
1566
1567   result = g_get_tmp_name (tmpl, &fulltemplate,
1568                            wrap_g_open,
1569                            O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1570                            0600,
1571                            error);
1572   if (result != -1)
1573     {
1574       if (name_used)
1575         *name_used = fulltemplate;
1576       else
1577         g_free (fulltemplate);
1578     }
1579
1580   return result;
1581 }
1582
1583 /**
1584  * g_dir_make_tmp:
1585  * @tmpl: (type filename) (allow-none): Template for directory name,
1586  *     as in g_mkdtemp(), basename only, or %NULL for a default template
1587  * @error: return location for a #GError
1588  *
1589  * Creates a subdirectory in the preferred directory for temporary
1590  * files (as returned by g_get_tmp_dir()).
1591  *
1592  * @tmpl should be a string in the GLib file name encoding containing
1593  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1594  * However, unlike these functions, the template should only be a
1595  * basename, no directory components are allowed. If template is
1596  * %NULL, a default template is used.
1597  *
1598  * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1599  * modified, and might thus be a read-only literal string.
1600  *
1601  * Returns: (type filename): The actual name used. This string
1602  *     should be freed with g_free() when not needed any longer and is
1603  *     is in the GLib file name encoding. In case of errors, %NULL is
1604  *     returned and @error will be set.
1605  *
1606  * Since: 2.30
1607  */
1608 gchar *
1609 g_dir_make_tmp (const gchar  *tmpl,
1610                 GError      **error)
1611 {
1612   gchar *fulltemplate;
1613
1614   if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1615     return NULL;
1616   else
1617     return fulltemplate;
1618 }
1619
1620 static gchar *
1621 g_build_path_va (const gchar  *separator,
1622                  const gchar  *first_element,
1623                  va_list      *args,
1624                  gchar       **str_array)
1625 {
1626   GString *result;
1627   gint separator_len = strlen (separator);
1628   gboolean is_first = TRUE;
1629   gboolean have_leading = FALSE;
1630   const gchar *single_element = NULL;
1631   const gchar *next_element;
1632   const gchar *last_trailing = NULL;
1633   gint i = 0;
1634
1635   result = g_string_new (NULL);
1636
1637   if (str_array)
1638     next_element = str_array[i++];
1639   else
1640     next_element = first_element;
1641
1642   while (TRUE)
1643     {
1644       const gchar *element;
1645       const gchar *start;
1646       const gchar *end;
1647
1648       if (next_element)
1649         {
1650           element = next_element;
1651           if (str_array)
1652             next_element = str_array[i++];
1653           else
1654             next_element = va_arg (*args, gchar *);
1655         }
1656       else
1657         break;
1658
1659       /* Ignore empty elements */
1660       if (!*element)
1661         continue;
1662       
1663       start = element;
1664
1665       if (separator_len)
1666         {
1667           while (strncmp (start, separator, separator_len) == 0)
1668             start += separator_len;
1669         }
1670
1671       end = start + strlen (start);
1672       
1673       if (separator_len)
1674         {
1675           while (end >= start + separator_len &&
1676                  strncmp (end - separator_len, separator, separator_len) == 0)
1677             end -= separator_len;
1678           
1679           last_trailing = end;
1680           while (last_trailing >= element + separator_len &&
1681                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1682             last_trailing -= separator_len;
1683
1684           if (!have_leading)
1685             {
1686               /* If the leading and trailing separator strings are in the
1687                * same element and overlap, the result is exactly that element
1688                */
1689               if (last_trailing <= start)
1690                 single_element = element;
1691                   
1692               g_string_append_len (result, element, start - element);
1693               have_leading = TRUE;
1694             }
1695           else
1696             single_element = NULL;
1697         }
1698
1699       if (end == start)
1700         continue;
1701
1702       if (!is_first)
1703         g_string_append (result, separator);
1704       
1705       g_string_append_len (result, start, end - start);
1706       is_first = FALSE;
1707     }
1708
1709   if (single_element)
1710     {
1711       g_string_free (result, TRUE);
1712       return g_strdup (single_element);
1713     }
1714   else
1715     {
1716       if (last_trailing)
1717         g_string_append (result, last_trailing);
1718   
1719       return g_string_free (result, FALSE);
1720     }
1721 }
1722
1723 /**
1724  * g_build_pathv:
1725  * @separator: a string used to separator the elements of the path.
1726  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1727  * 
1728  * Behaves exactly like g_build_path(), but takes the path elements 
1729  * as a string array, instead of varargs. This function is mainly
1730  * meant for language bindings.
1731  *
1732  * Returns: a newly-allocated string that must be freed with g_free().
1733  *
1734  * Since: 2.8
1735  */
1736 gchar *
1737 g_build_pathv (const gchar  *separator,
1738                gchar       **args)
1739 {
1740   if (!args)
1741     return NULL;
1742
1743   return g_build_path_va (separator, NULL, NULL, args);
1744 }
1745
1746
1747 /**
1748  * g_build_path:
1749  * @separator: a string used to separator the elements of the path.
1750  * @first_element: the first element in the path
1751  * @...: remaining elements in path, terminated by %NULL
1752  * 
1753  * Creates a path from a series of elements using @separator as the
1754  * separator between elements. At the boundary between two elements,
1755  * any trailing occurrences of separator in the first element, or
1756  * leading occurrences of separator in the second element are removed
1757  * and exactly one copy of the separator is inserted.
1758  *
1759  * Empty elements are ignored.
1760  *
1761  * The number of leading copies of the separator on the result is
1762  * the same as the number of leading copies of the separator on
1763  * the first non-empty element.
1764  *
1765  * The number of trailing copies of the separator on the result is
1766  * the same as the number of trailing copies of the separator on
1767  * the last non-empty element. (Determination of the number of
1768  * trailing copies is done without stripping leading copies, so
1769  * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
1770  *
1771  * However, if there is only a single non-empty element, and there
1772  * are no characters in that element not part of the leading or
1773  * trailing separators, then the result is exactly the original value
1774  * of that element.
1775  *
1776  * Other than for determination of the number of leading and trailing
1777  * copies of the separator, elements consisting only of copies
1778  * of the separator are ignored.
1779  * 
1780  * Returns: a newly-allocated string that must be freed with g_free().
1781  **/
1782 gchar *
1783 g_build_path (const gchar *separator,
1784               const gchar *first_element,
1785               ...)
1786 {
1787   gchar *str;
1788   va_list args;
1789
1790   g_return_val_if_fail (separator != NULL, NULL);
1791
1792   va_start (args, first_element);
1793   str = g_build_path_va (separator, first_element, &args, NULL);
1794   va_end (args);
1795
1796   return str;
1797 }
1798
1799 #ifdef G_OS_WIN32
1800
1801 static gchar *
1802 g_build_pathname_va (const gchar  *first_element,
1803                      va_list      *args,
1804                      gchar       **str_array)
1805 {
1806   /* Code copied from g_build_pathv(), and modified to use two
1807    * alternative single-character separators.
1808    */
1809   GString *result;
1810   gboolean is_first = TRUE;
1811   gboolean have_leading = FALSE;
1812   const gchar *single_element = NULL;
1813   const gchar *next_element;
1814   const gchar *last_trailing = NULL;
1815   gchar current_separator = '\\';
1816   gint i = 0;
1817
1818   result = g_string_new (NULL);
1819
1820   if (str_array)
1821     next_element = str_array[i++];
1822   else
1823     next_element = first_element;
1824   
1825   while (TRUE)
1826     {
1827       const gchar *element;
1828       const gchar *start;
1829       const gchar *end;
1830
1831       if (next_element)
1832         {
1833           element = next_element;
1834           if (str_array)
1835             next_element = str_array[i++];
1836           else
1837             next_element = va_arg (*args, gchar *);
1838         }
1839       else
1840         break;
1841
1842       /* Ignore empty elements */
1843       if (!*element)
1844         continue;
1845       
1846       start = element;
1847
1848       if (TRUE)
1849         {
1850           while (start &&
1851                  (*start == '\\' || *start == '/'))
1852             {
1853               current_separator = *start;
1854               start++;
1855             }
1856         }
1857
1858       end = start + strlen (start);
1859       
1860       if (TRUE)
1861         {
1862           while (end >= start + 1 &&
1863                  (end[-1] == '\\' || end[-1] == '/'))
1864             {
1865               current_separator = end[-1];
1866               end--;
1867             }
1868           
1869           last_trailing = end;
1870           while (last_trailing >= element + 1 &&
1871                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1872             last_trailing--;
1873
1874           if (!have_leading)
1875             {
1876               /* If the leading and trailing separator strings are in the
1877                * same element and overlap, the result is exactly that element
1878                */
1879               if (last_trailing <= start)
1880                 single_element = element;
1881                   
1882               g_string_append_len (result, element, start - element);
1883               have_leading = TRUE;
1884             }
1885           else
1886             single_element = NULL;
1887         }
1888
1889       if (end == start)
1890         continue;
1891
1892       if (!is_first)
1893         g_string_append_len (result, &current_separator, 1);
1894       
1895       g_string_append_len (result, start, end - start);
1896       is_first = FALSE;
1897     }
1898
1899   if (single_element)
1900     {
1901       g_string_free (result, TRUE);
1902       return g_strdup (single_element);
1903     }
1904   else
1905     {
1906       if (last_trailing)
1907         g_string_append (result, last_trailing);
1908   
1909       return g_string_free (result, FALSE);
1910     }
1911 }
1912
1913 #endif
1914
1915 /**
1916  * g_build_filenamev:
1917  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1918  * 
1919  * Behaves exactly like g_build_filename(), but takes the path elements 
1920  * as a string array, instead of varargs. This function is mainly
1921  * meant for language bindings.
1922  *
1923  * Returns: a newly-allocated string that must be freed with g_free().
1924  * 
1925  * Since: 2.8
1926  */
1927 gchar *
1928 g_build_filenamev (gchar **args)
1929 {
1930   gchar *str;
1931
1932 #ifndef G_OS_WIN32
1933   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1934 #else
1935   str = g_build_pathname_va (NULL, NULL, args);
1936 #endif
1937
1938   return str;
1939 }
1940
1941 /**
1942  * g_build_filename:
1943  * @first_element: the first element in the path
1944  * @...: remaining elements in path, terminated by %NULL
1945  * 
1946  * Creates a filename from a series of elements using the correct
1947  * separator for filenames.
1948  *
1949  * On Unix, this function behaves identically to `g_build_path
1950  * (G_DIR_SEPARATOR_S, first_element, ....)`.
1951  *
1952  * On Windows, it takes into account that either the backslash
1953  * (`\` or slash (`/`) can be used as separator in filenames, but
1954  * otherwise behaves as on UNIX. When file pathname separators need
1955  * to be inserted, the one that last previously occurred in the
1956  * parameters (reading from left to right) is used.
1957  *
1958  * No attempt is made to force the resulting filename to be an absolute
1959  * path. If the first element is a relative path, the result will
1960  * be a relative path. 
1961  * 
1962  * Returns: a newly-allocated string that must be freed with g_free().
1963  **/
1964 gchar *
1965 g_build_filename (const gchar *first_element, 
1966                   ...)
1967 {
1968   gchar *str;
1969   va_list args;
1970
1971   va_start (args, first_element);
1972 #ifndef G_OS_WIN32
1973   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1974 #else
1975   str = g_build_pathname_va (first_element, &args, NULL);
1976 #endif
1977   va_end (args);
1978
1979   return str;
1980 }
1981
1982 /**
1983  * g_file_read_link:
1984  * @filename: the symbolic link
1985  * @error: return location for a #GError
1986  *
1987  * Reads the contents of the symbolic link @filename like the POSIX
1988  * readlink() function.  The returned string is in the encoding used
1989  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1990  *
1991  * Returns: A newly-allocated string with the contents of the symbolic link, 
1992  *          or %NULL if an error occurred.
1993  *
1994  * Since: 2.4
1995  */
1996 gchar *
1997 g_file_read_link (const gchar  *filename,
1998                   GError      **error)
1999 {
2000 #ifdef HAVE_READLINK
2001   gchar *buffer;
2002   guint size;
2003   gint read_size;    
2004   
2005   size = 256; 
2006   buffer = g_malloc (size);
2007   
2008   while (TRUE) 
2009     {
2010       read_size = readlink (filename, buffer, size);
2011       if (read_size < 0)
2012         {
2013           set_file_error (error,
2014                           filename,
2015                           _("Failed to read the symbolic link '%s': %s"));
2016           g_free (buffer);
2017           return NULL;
2018         }
2019     
2020       if (read_size < size) 
2021         {
2022           buffer[read_size] = 0;
2023           return buffer;
2024         }
2025       
2026       size *= 2;
2027       buffer = g_realloc (buffer, size);
2028     }
2029 #else
2030   g_set_error_literal (error,
2031                        G_FILE_ERROR,
2032                        G_FILE_ERROR_INVAL,
2033                        _("Symbolic links not supported"));
2034         
2035   return NULL;
2036 #endif
2037 }
2038
2039 /**
2040  * g_path_is_absolute:
2041  * @file_name: a file name
2042  *
2043  * Returns %TRUE if the given @file_name is an absolute file name.
2044  * Note that this is a somewhat vague concept on Windows.
2045  *
2046  * On POSIX systems, an absolute file name is well-defined. It always
2047  * starts from the single root directory. For example "/usr/local".
2048  *
2049  * On Windows, the concepts of current drive and drive-specific
2050  * current directory introduce vagueness. This function interprets as
2051  * an absolute file name one that either begins with a directory
2052  * separator such as "\Users\tml" or begins with the root on a drive,
2053  * for example "C:\Windows". The first case also includes UNC paths
2054  * such as "\\myserver\docs\foo". In all cases, either slashes or
2055  * backslashes are accepted.
2056  *
2057  * Note that a file name relative to the current drive root does not
2058  * truly specify a file uniquely over time and across processes, as
2059  * the current drive is a per-process value and can be changed.
2060  *
2061  * File names relative the current directory on some specific drive,
2062  * such as "D:foo/bar", are not interpreted as absolute by this
2063  * function, but they obviously are not relative to the normal current
2064  * directory as returned by getcwd() or g_get_current_dir()
2065  * either. Such paths should be avoided, or need to be handled using
2066  * Windows-specific code.
2067  *
2068  * Returns: %TRUE if @file_name is absolute
2069  */
2070 gboolean
2071 g_path_is_absolute (const gchar *file_name)
2072 {
2073   g_return_val_if_fail (file_name != NULL, FALSE);
2074
2075   if (G_IS_DIR_SEPARATOR (file_name[0]))
2076     return TRUE;
2077
2078 #ifdef G_OS_WIN32
2079   /* Recognize drive letter on native Windows */
2080   if (g_ascii_isalpha (file_name[0]) &&
2081       file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2082     return TRUE;
2083 #endif
2084
2085   return FALSE;
2086 }
2087
2088 /**
2089  * g_path_skip_root:
2090  * @file_name: a file name
2091  *
2092  * Returns a pointer into @file_name after the root component,
2093  * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2094  * is not an absolute path it returns %NULL.
2095  *
2096  * Returns: a pointer into @file_name after the root component
2097  */
2098 const gchar *
2099 g_path_skip_root (const gchar *file_name)
2100 {
2101   g_return_val_if_fail (file_name != NULL, NULL);
2102
2103 #ifdef G_PLATFORM_WIN32
2104   /* Skip \\server\share or //server/share */
2105   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2106       G_IS_DIR_SEPARATOR (file_name[1]) &&
2107       file_name[2] &&
2108       !G_IS_DIR_SEPARATOR (file_name[2]))
2109     {
2110       gchar *p;
2111       p = strchr (file_name + 2, G_DIR_SEPARATOR);
2112
2113 #ifdef G_OS_WIN32
2114       {
2115         gchar *q;
2116
2117         q = strchr (file_name + 2, '/');
2118         if (p == NULL || (q != NULL && q < p))
2119         p = q;
2120       }
2121 #endif
2122
2123       if (p && p > file_name + 2 && p[1])
2124         {
2125           file_name = p + 1;
2126
2127           while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2128             file_name++;
2129
2130           /* Possibly skip a backslash after the share name */
2131           if (G_IS_DIR_SEPARATOR (file_name[0]))
2132             file_name++;
2133
2134           return (gchar *)file_name;
2135         }
2136     }
2137 #endif
2138
2139   /* Skip initial slashes */
2140   if (G_IS_DIR_SEPARATOR (file_name[0]))
2141     {
2142       while (G_IS_DIR_SEPARATOR (file_name[0]))
2143         file_name++;
2144       return (gchar *)file_name;
2145     }
2146
2147 #ifdef G_OS_WIN32
2148   /* Skip X:\ */
2149   if (g_ascii_isalpha (file_name[0]) &&
2150       file_name[1] == ':' &&
2151       G_IS_DIR_SEPARATOR (file_name[2]))
2152     return (gchar *)file_name + 3;
2153 #endif
2154
2155   return NULL;
2156 }
2157
2158 /**
2159  * g_basename:
2160  * @file_name: the name of the file
2161  *
2162  * Gets the name of the file without any leading directory
2163  * components. It returns a pointer into the given file name
2164  * string.
2165  *
2166  * Returns: the name of the file without any leading
2167  *     directory components
2168  *
2169  * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2170  *     that g_path_get_basename() allocates new memory for the
2171  *     returned string, unlike this function which returns a pointer
2172  *     into the argument.
2173  */
2174 const gchar *
2175 g_basename (const gchar *file_name)
2176 {
2177   gchar *base;
2178
2179   g_return_val_if_fail (file_name != NULL, NULL);
2180
2181   base = strrchr (file_name, G_DIR_SEPARATOR);
2182
2183 #ifdef G_OS_WIN32
2184   {
2185     gchar *q;
2186     q = strrchr (file_name, '/');
2187     if (base == NULL || (q != NULL && q > base))
2188       base = q;
2189   }
2190 #endif
2191
2192   if (base)
2193     return base + 1;
2194
2195 #ifdef G_OS_WIN32
2196   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2197     return (gchar*) file_name + 2;
2198 #endif
2199
2200   return (gchar*) file_name;
2201 }
2202
2203 /**
2204  * g_path_get_basename:
2205  * @file_name: the name of the file
2206  *
2207  * Gets the last component of the filename.
2208  *
2209  * If @file_name ends with a directory separator it gets the component
2210  * before the last slash. If @file_name consists only of directory
2211  * separators (and on Windows, possibly a drive letter), a single
2212  * separator is returned. If @file_name is empty, it gets ".".
2213  *
2214  * Returns: a newly allocated string containing the last
2215  *    component of the filename
2216  */
2217 gchar *
2218 g_path_get_basename (const gchar *file_name)
2219 {
2220   gssize base;
2221   gssize last_nonslash;
2222   gsize len;
2223   gchar *retval;
2224
2225   g_return_val_if_fail (file_name != NULL, NULL);
2226
2227   if (file_name[0] == '\0')
2228     return g_strdup (".");
2229
2230   last_nonslash = strlen (file_name) - 1;
2231
2232   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2233     last_nonslash--;
2234
2235   if (last_nonslash == -1)
2236     /* string only containing slashes */
2237     return g_strdup (G_DIR_SEPARATOR_S);
2238
2239 #ifdef G_OS_WIN32
2240   if (last_nonslash == 1 &&
2241       g_ascii_isalpha (file_name[0]) &&
2242       file_name[1] == ':')
2243     /* string only containing slashes and a drive */
2244     return g_strdup (G_DIR_SEPARATOR_S);
2245 #endif
2246   base = last_nonslash;
2247
2248   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2249     base--;
2250
2251 #ifdef G_OS_WIN32
2252   if (base == -1 &&
2253       g_ascii_isalpha (file_name[0]) &&
2254       file_name[1] == ':')
2255     base = 1;
2256 #endif /* G_OS_WIN32 */
2257
2258   len = last_nonslash - base;
2259   retval = g_malloc (len + 1);
2260   memcpy (retval, file_name + base + 1, len);
2261   retval [len] = '\0';
2262
2263   return retval;
2264 }
2265
2266 /**
2267  * g_dirname:
2268  * @file_name: the name of the file
2269  *
2270  * Gets the directory components of a file name.
2271  *
2272  * If the file name has no directory components "." is returned.
2273  * The returned string should be freed when no longer needed.
2274  *
2275  * Returns: the directory components of the file
2276  *
2277  * Deprecated: use g_path_get_dirname() instead
2278  */
2279
2280 /**
2281  * g_path_get_dirname:
2282  * @file_name: the name of the file
2283  *
2284  * Gets the directory components of a file name.
2285  *
2286  * If the file name has no directory components "." is returned.
2287  * The returned string should be freed when no longer needed.
2288  *
2289  * Returns: the directory components of the file
2290  */
2291 gchar *
2292 g_path_get_dirname (const gchar *file_name)
2293 {
2294   gchar *base;
2295   gsize len;
2296
2297   g_return_val_if_fail (file_name != NULL, NULL);
2298
2299   base = strrchr (file_name, G_DIR_SEPARATOR);
2300
2301 #ifdef G_OS_WIN32
2302   {
2303     gchar *q;
2304     q = strrchr (file_name, '/');
2305     if (base == NULL || (q != NULL && q > base))
2306       base = q;
2307   }
2308 #endif
2309
2310   if (!base)
2311     {
2312 #ifdef G_OS_WIN32
2313       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2314         {
2315           gchar drive_colon_dot[4];
2316
2317           drive_colon_dot[0] = file_name[0];
2318           drive_colon_dot[1] = ':';
2319           drive_colon_dot[2] = '.';
2320           drive_colon_dot[3] = '\0';
2321
2322           return g_strdup (drive_colon_dot);
2323         }
2324 #endif
2325     return g_strdup (".");
2326     }
2327
2328   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2329     base--;
2330
2331 #ifdef G_OS_WIN32
2332   /* base points to the char before the last slash.
2333    *
2334    * In case file_name is the root of a drive (X:\) or a child of the
2335    * root of a drive (X:\foo), include the slash.
2336    *
2337    * In case file_name is the root share of an UNC path
2338    * (\\server\share), add a slash, returning \\server\share\ .
2339    *
2340    * In case file_name is a direct child of a share in an UNC path
2341    * (\\server\share\foo), include the slash after the share name,
2342    * returning \\server\share\ .
2343    */
2344   if (base == file_name + 1 &&
2345       g_ascii_isalpha (file_name[0]) &&
2346       file_name[1] == ':')
2347     base++;
2348   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2349            G_IS_DIR_SEPARATOR (file_name[1]) &&
2350            file_name[2] &&
2351            !G_IS_DIR_SEPARATOR (file_name[2]) &&
2352            base >= file_name + 2)
2353     {
2354       const gchar *p = file_name + 2;
2355       while (*p && !G_IS_DIR_SEPARATOR (*p))
2356         p++;
2357       if (p == base + 1)
2358         {
2359           len = (guint) strlen (file_name) + 1;
2360           base = g_new (gchar, len + 1);
2361           strcpy (base, file_name);
2362           base[len-1] = G_DIR_SEPARATOR;
2363           base[len] = 0;
2364           return base;
2365         }
2366       if (G_IS_DIR_SEPARATOR (*p))
2367         {
2368           p++;
2369           while (*p && !G_IS_DIR_SEPARATOR (*p))
2370             p++;
2371           if (p == base + 1)
2372             base++;
2373         }
2374     }
2375 #endif
2376
2377   len = (guint) 1 + base - file_name;
2378   base = g_new (gchar, len + 1);
2379   memmove (base, file_name, len);
2380   base[len] = 0;
2381
2382   return base;
2383 }
2384
2385 #if defined(MAXPATHLEN)
2386 #define G_PATH_LENGTH MAXPATHLEN
2387 #elif defined(PATH_MAX)
2388 #define G_PATH_LENGTH PATH_MAX
2389 #elif defined(_PC_PATH_MAX)
2390 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2391 #else
2392 #define G_PATH_LENGTH 2048
2393 #endif
2394
2395 /**
2396  * g_get_current_dir:
2397  *
2398  * Gets the current directory.
2399  *
2400  * The returned string should be freed when no longer needed.
2401  * The encoding of the returned string is system defined.
2402  * On Windows, it is always UTF-8.
2403  *
2404  * Since GLib 2.40, this function will return the value of the "PWD"
2405  * environment variable if it is set and it happens to be the same as
2406  * the current directory.  This can make a difference in the case that
2407  * the current directory is the target of a symbolic link.
2408  *
2409  * Returns: the current directory
2410  */
2411 gchar *
2412 g_get_current_dir (void)
2413 {
2414 #ifdef G_OS_WIN32
2415
2416   gchar *dir = NULL;
2417   wchar_t dummy[2], *wdir;
2418   int len;
2419
2420   len = GetCurrentDirectoryW (2, dummy);
2421   wdir = g_new (wchar_t, len);
2422
2423   if (GetCurrentDirectoryW (len, wdir) == len - 1)
2424     dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2425
2426   g_free (wdir);
2427
2428   if (dir == NULL)
2429     dir = g_strdup ("\\");
2430
2431   return dir;
2432
2433 #else
2434   const gchar *pwd;
2435   gchar *buffer = NULL;
2436   gchar *dir = NULL;
2437   static gulong max_len = 0;
2438   struct stat pwdbuf, dotbuf;
2439
2440   pwd = g_getenv ("PWD");
2441   if (pwd != NULL &&
2442       g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2443       dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2444     return g_strdup (pwd);
2445
2446   if (max_len == 0)
2447     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2448
2449   while (max_len < G_MAXULONG / 2)
2450     {
2451       g_free (buffer);
2452       buffer = g_new (gchar, max_len + 1);
2453       *buffer = 0;
2454       dir = getcwd (buffer, max_len);
2455
2456       if (dir || errno != ERANGE)
2457         break;
2458
2459       max_len *= 2;
2460     }
2461
2462   if (!dir || !*buffer)
2463     {
2464       /* hm, should we g_error() out here?
2465        * this can happen if e.g. "./" has mode \0000
2466        */
2467       buffer[0] = G_DIR_SEPARATOR;
2468       buffer[1] = 0;
2469     }
2470
2471   dir = g_strdup (buffer);
2472   g_free (buffer);
2473
2474   return dir;
2475
2476 #endif /* !G_OS_WIN32 */
2477 }
2478
2479
2480 /* NOTE : Keep this part last to ensure nothing in this file uses thn
2481  * below binary compatibility versions.
2482  */
2483 #if defined (G_OS_WIN32) && !defined (_WIN64)
2484
2485 /* Binary compatibility versions. Will be called by code compiled
2486  * against quite old (pre-2.8, I think) headers only, not from more
2487  * recently compiled code.
2488  */
2489
2490 #undef g_file_test
2491
2492 gboolean
2493 g_file_test (const gchar *filename,
2494              GFileTest    test)
2495 {
2496   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
2497   gboolean retval;
2498
2499   if (utf8_filename == NULL)
2500     return FALSE;
2501
2502   retval = g_file_test_utf8 (utf8_filename, test);
2503
2504   g_free (utf8_filename);
2505
2506   return retval;
2507 }
2508
2509 #undef g_file_get_contents
2510
2511 gboolean
2512 g_file_get_contents (const gchar  *filename,
2513                      gchar       **contents,
2514                      gsize        *length,
2515                      GError      **error)
2516 {
2517   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2518   gboolean retval;
2519
2520   if (utf8_filename == NULL)
2521     return FALSE;
2522
2523   retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
2524
2525   g_free (utf8_filename);
2526
2527   return retval;
2528 }
2529
2530 #undef g_mkstemp
2531
2532 static gint
2533 wrap_libc_open (const gchar *filename,
2534                 int          flags,
2535                 int          mode)
2536 {
2537   return open (filename, flags, mode);
2538 }
2539
2540 gint
2541 g_mkstemp (gchar *tmpl)
2542 {
2543   /* This is the backward compatibility system codepage version,
2544    * thus use normal open().
2545    */
2546   return get_tmp_file (tmpl, wrap_libc_open,
2547                        O_RDWR | O_CREAT | O_EXCL, 0600);
2548 }
2549
2550 #undef g_file_open_tmp
2551
2552 gint
2553 g_file_open_tmp (const gchar  *tmpl,
2554                  gchar       **name_used,
2555                  GError      **error)
2556 {
2557   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2558   gchar *utf8_name_used;
2559   gint retval;
2560
2561   if (utf8_tmpl == NULL)
2562     return -1;
2563
2564   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2565   
2566   if (retval == -1)
2567     return -1;
2568
2569   if (name_used)
2570     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2571
2572   g_free (utf8_name_used);
2573
2574   return retval;
2575 }
2576
2577 #undef g_get_current_dir
2578
2579 gchar *
2580 g_get_current_dir (void)
2581 {
2582   gchar *utf8_dir = g_get_current_dir_utf8 ();
2583   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2584   g_free (utf8_dir);
2585   return dir;
2586 }
2587
2588 #endif
2589