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