[kdbus] KDBUS_ITEM_PAYLOAD_OFF items are (once again) relative to msg header
[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,
611                       int           saved_errno) 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                       int           saved_errno)
620 {
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                 int           saved_errno)
643 {
644   char *msg = format_error_message (filename, format_string, saved_errno);
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       int saved_errno = errno;
863       set_file_error (error,
864                       filename,
865                       _("Failed to open file '%s': %s"),
866                       saved_errno);
867
868       return FALSE;
869     }
870
871   /* I don't think this will ever fail, aside from ENOMEM, but. */
872   if (fstat (fd, &stat_buf) < 0)
873     {
874       int saved_errno = errno;
875       set_file_error (error,
876                       filename,
877                       _("Failed to get attributes of file '%s': fstat() failed: %s"),
878                       saved_errno);
879       close (fd);
880
881       return FALSE;
882     }
883
884   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
885     {
886       gboolean retval = get_contents_regfile (filename,
887                                               &stat_buf,
888                                               fd,
889                                               contents,
890                                               length,
891                                               error);
892
893       return retval;
894     }
895   else
896     {
897       FILE *f;
898       gboolean retval;
899
900       f = fdopen (fd, "r");
901       
902       if (f == NULL)
903         {
904           int saved_errno = errno;
905           set_file_error (error,
906                           filename,
907                           _("Failed to open file '%s': fdopen() failed: %s"),
908                           saved_errno);
909
910           return FALSE;
911         }
912   
913       retval = get_contents_stdio (filename, f, contents, length, error);
914
915       return retval;
916     }
917 }
918
919 #else  /* G_OS_WIN32 */
920
921 static gboolean
922 get_contents_win32 (const gchar  *filename,
923                     gchar       **contents,
924                     gsize        *length,
925                     GError      **error)
926 {
927   FILE *f;
928   gboolean retval;
929   
930   f = g_fopen (filename, "rb");
931
932   if (f == NULL)
933     {
934       int saved_errno = errno;
935       set_file_error (error,
936                       filename,
937                       _("Failed to open file '%s': %s"),
938                       saved_errno);
939
940       return FALSE;
941     }
942   
943   retval = get_contents_stdio (filename, f, contents, length, error);
944
945   return retval;
946 }
947
948 #endif
949
950 /**
951  * g_file_get_contents:
952  * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
953  * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
954  *     the returned string
955  * @length: (allow-none): location to store length in bytes of the contents, or %NULL
956  * @error: return location for a #GError, or %NULL
957  *
958  * Reads an entire file into allocated memory, with good error
959  * checking.
960  *
961  * If the call was successful, it returns %TRUE and sets @contents to the file
962  * contents and @length to the length of the file contents in bytes. The string
963  * stored in @contents will be nul-terminated, so for text files you can pass
964  * %NULL for the @length argument. If the call was not successful, it returns
965  * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
966  * codes are those in the #GFileError enumeration. In the error case,
967  * @contents is set to %NULL and @length is set to zero.
968  *
969  * Returns: %TRUE on success, %FALSE if an error occurred
970  **/
971 gboolean
972 g_file_get_contents (const gchar  *filename,
973                      gchar       **contents,
974                      gsize        *length,
975                      GError      **error)
976 {  
977   g_return_val_if_fail (filename != NULL, FALSE);
978   g_return_val_if_fail (contents != NULL, FALSE);
979
980   *contents = NULL;
981   if (length)
982     *length = 0;
983
984 #ifdef G_OS_WIN32
985   return get_contents_win32 (filename, contents, length, error);
986 #else
987   return get_contents_posix (filename, contents, length, error);
988 #endif
989 }
990
991 static gboolean
992 rename_file (const char  *old_name,
993              const char  *new_name,
994              GError     **err)
995 {
996   errno = 0;
997   if (g_rename (old_name, new_name) == -1)
998     {
999       int save_errno = errno;
1000       gchar *display_old_name = g_filename_display_name (old_name);
1001       gchar *display_new_name = g_filename_display_name (new_name);
1002
1003       g_set_error (err,
1004                    G_FILE_ERROR,
1005                    g_file_error_from_errno (save_errno),
1006                    _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
1007                    display_old_name,
1008                    display_new_name,
1009                    g_strerror (save_errno));
1010
1011       g_free (display_old_name);
1012       g_free (display_new_name);
1013       
1014       return FALSE;
1015     }
1016   
1017   return TRUE;
1018 }
1019
1020 static gchar *
1021 write_to_temp_file (const gchar  *contents,
1022                     gssize        length,
1023                     const gchar  *dest_file,
1024                     GError      **err)
1025 {
1026   gchar *tmp_name;
1027   gchar *retval;
1028   gint fd;
1029
1030   retval = NULL;
1031
1032   tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
1033
1034   errno = 0;
1035   fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
1036
1037   if (fd == -1)
1038     {
1039       int saved_errno = errno;
1040       set_file_error (err,
1041                       tmp_name, _("Failed to create file '%s': %s"),
1042                       saved_errno);
1043       goto out;
1044     }
1045
1046 #ifdef HAVE_FALLOCATE
1047   if (length > 0)
1048     {
1049       /* We do this on a 'best effort' basis... It may not be supported
1050        * on the underlying filesystem.
1051        */
1052       (void) fallocate (fd, 0, 0, length);
1053     }
1054 #endif
1055   while (length > 0)
1056     {
1057       gssize s;
1058
1059       s = write (fd, contents, length);
1060
1061       if (s < 0)
1062         {
1063           int saved_errno = errno;
1064           if (saved_errno == EINTR)
1065             continue;
1066
1067           set_file_error (err,
1068                           tmp_name, _("Failed to write file '%s': write() failed: %s"),
1069                           saved_errno);
1070           close (fd);
1071           g_unlink (tmp_name);
1072
1073           goto out;
1074         }
1075
1076       g_assert (s <= length);
1077
1078       contents += s;
1079       length -= s;
1080     }
1081
1082 #ifdef BTRFS_SUPER_MAGIC
1083   {
1084     struct statfs buf;
1085
1086     /* On Linux, on btrfs, skip the fsync since rename-over-existing is
1087      * guaranteed to be atomic and this is the only case in which we
1088      * would fsync() anyway.
1089      */
1090
1091     if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
1092       goto no_fsync;
1093   }
1094 #endif
1095
1096 #ifdef HAVE_FSYNC
1097   {
1098     struct stat statbuf;
1099
1100     errno = 0;
1101     /* If the final destination exists and is > 0 bytes, we want to sync the
1102      * newly written file to ensure the data is on disk when we rename over
1103      * the destination. Otherwise if we get a system crash we can lose both
1104      * the new and the old file on some filesystems. (I.E. those that don't
1105      * guarantee the data is written to the disk before the metadata.)
1106      */
1107     if (g_lstat (dest_file, &statbuf) == 0 && statbuf.st_size > 0 && fsync (fd) != 0)
1108       {
1109         int saved_errno = errno;
1110         set_file_error (err,
1111                         tmp_name, _("Failed to write file '%s': fsync() failed: %s"),
1112                         saved_errno);
1113         close (fd);
1114         g_unlink (tmp_name);
1115
1116         goto out;
1117       }
1118   }
1119 #endif
1120
1121 #ifdef BTRFS_SUPER_MAGIC
1122  no_fsync:
1123 #endif
1124
1125   errno = 0;
1126   if (!g_close (fd, err))
1127     {
1128       g_unlink (tmp_name);
1129
1130       goto out;
1131     }
1132
1133   retval = g_strdup (tmp_name);
1134
1135  out:
1136   g_free (tmp_name);
1137
1138   return retval;
1139 }
1140
1141 /**
1142  * g_file_set_contents:
1143  * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1144  *   encoding
1145  * @contents: (array length=length) (element-type guint8): string to write to the file
1146  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1147  * @error: return location for a #GError, or %NULL
1148  *
1149  * Writes all of @contents to a file named @filename, with good error checking.
1150  * If a file called @filename already exists it will be overwritten.
1151  *
1152  * This write is atomic in the sense that it is first written to a temporary
1153  * file which is then renamed to the final name. Notes:
1154  *
1155  * - On UNIX, if @filename already exists hard links to @filename will break.
1156  *   Also since the file is recreated, existing permissions, access control
1157  *   lists, metadata etc. may be lost. If @filename is a symbolic link,
1158  *   the link itself will be replaced, not the linked file.
1159  *
1160  * - On Windows renaming a file will not remove an existing file with the
1161  *   new name, so on Windows there is a race condition between the existing
1162  *   file being removed and the temporary file being renamed.
1163  *
1164  * - On Windows there is no way to remove a file that is open to some
1165  *   process, or mapped into memory. Thus, this function will fail if
1166  *   @filename already exists and is open.
1167  *
1168  * If the call was successful, it returns %TRUE. If the call was not successful,
1169  * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1170  * Possible error codes are those in the #GFileError enumeration.
1171  *
1172  * Note that the name for the temporary file is constructed by appending up
1173  * to 7 characters to @filename.
1174  *
1175  * Returns: %TRUE on success, %FALSE if an error occurred
1176  *
1177  * Since: 2.8
1178  */
1179 gboolean
1180 g_file_set_contents (const gchar  *filename,
1181                      const gchar  *contents,
1182                      gssize        length,
1183                      GError      **error)
1184 {
1185   gchar *tmp_filename;
1186   gboolean retval;
1187   GError *rename_error = NULL;
1188   
1189   g_return_val_if_fail (filename != NULL, FALSE);
1190   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1191   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1192   g_return_val_if_fail (length >= -1, FALSE);
1193   
1194   if (length == -1)
1195     length = strlen (contents);
1196
1197   tmp_filename = write_to_temp_file (contents, length, filename, error);
1198   
1199   if (!tmp_filename)
1200     {
1201       retval = FALSE;
1202       goto out;
1203     }
1204
1205   if (!rename_file (tmp_filename, filename, &rename_error))
1206     {
1207 #ifndef G_OS_WIN32
1208
1209       g_unlink (tmp_filename);
1210       g_propagate_error (error, rename_error);
1211       retval = FALSE;
1212       goto out;
1213
1214 #else /* G_OS_WIN32 */
1215       
1216       /* Renaming failed, but on Windows this may just mean
1217        * the file already exists. So if the target file
1218        * exists, try deleting it and do the rename again.
1219        */
1220       if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1221         {
1222           g_unlink (tmp_filename);
1223           g_propagate_error (error, rename_error);
1224           retval = FALSE;
1225           goto out;
1226         }
1227
1228       g_error_free (rename_error);
1229       
1230       if (g_unlink (filename) == -1)
1231         {
1232           int saved_errno = errno;
1233           set_file_error (error,
1234                           filename,
1235                           _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1236                           saved_errno);
1237           g_unlink (tmp_filename);
1238           retval = FALSE;
1239           goto out;
1240         }
1241       
1242       if (!rename_file (tmp_filename, filename, error))
1243         {
1244           g_unlink (tmp_filename);
1245           retval = FALSE;
1246           goto out;
1247         }
1248
1249 #endif
1250     }
1251
1252   retval = TRUE;
1253   
1254  out:
1255   g_free (tmp_filename);
1256   return retval;
1257 }
1258
1259 /*
1260  * get_tmp_file based on the mkstemp implementation from the GNU C library.
1261  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1262  */
1263 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1264
1265 static gint
1266 get_tmp_file (gchar            *tmpl,
1267               GTmpFileCallback  f,
1268               int               flags,
1269               int               mode)
1270 {
1271   char *XXXXXX;
1272   int count, fd;
1273   static const char letters[] =
1274     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1275   static const int NLETTERS = sizeof (letters) - 1;
1276   glong value;
1277   GTimeVal tv;
1278   static int counter = 0;
1279
1280   g_return_val_if_fail (tmpl != NULL, -1);
1281
1282   /* find the last occurrence of "XXXXXX" */
1283   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1284
1285   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1286     {
1287       errno = EINVAL;
1288       return -1;
1289     }
1290
1291   /* Get some more or less random data.  */
1292   g_get_current_time (&tv);
1293   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1294
1295   for (count = 0; count < 100; value += 7777, ++count)
1296     {
1297       glong v = value;
1298
1299       /* Fill in the random bits.  */
1300       XXXXXX[0] = letters[v % NLETTERS];
1301       v /= NLETTERS;
1302       XXXXXX[1] = letters[v % NLETTERS];
1303       v /= NLETTERS;
1304       XXXXXX[2] = letters[v % NLETTERS];
1305       v /= NLETTERS;
1306       XXXXXX[3] = letters[v % NLETTERS];
1307       v /= NLETTERS;
1308       XXXXXX[4] = letters[v % NLETTERS];
1309       v /= NLETTERS;
1310       XXXXXX[5] = letters[v % NLETTERS];
1311
1312       fd = f (tmpl, flags, mode);
1313
1314       if (fd >= 0)
1315         return fd;
1316       else if (errno != EEXIST)
1317         /* Any other error will apply also to other names we might
1318          *  try, and there are 2^32 or so of them, so give up now.
1319          */
1320         return -1;
1321     }
1322
1323   /* We got out of the loop because we ran out of combinations to try.  */
1324   errno = EEXIST;
1325   return -1;
1326 }
1327
1328 /* Some GTmpFileCallback implementations.
1329  *
1330  * Note: we cannot use open() or g_open() directly because even though
1331  * they appear compatible, they may be vararg functions and calling
1332  * varargs functions through a non-varargs type is undefined.
1333  */
1334 static gint
1335 wrap_g_mkdir (const gchar *filename,
1336               int          flags G_GNUC_UNUSED,
1337               int          mode)
1338 {
1339   /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1340   return g_mkdir (filename, mode);
1341 }
1342
1343 static gint
1344 wrap_g_open (const gchar *filename,
1345                 int          flags,
1346                 int          mode)
1347 {
1348   return g_open (filename, flags, mode);
1349 }
1350
1351 /**
1352  * g_mkdtemp_full:
1353  * @tmpl: (type filename): template directory name
1354  * @mode: permissions to create the temporary directory with
1355  *
1356  * Creates a temporary directory. See the mkdtemp() documentation
1357  * on most UNIX-like systems.
1358  *
1359  * The parameter is a string that should follow the rules for
1360  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1361  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1362  * sequence does not have to occur at the very end of the template
1363  * and you can pass a @mode. The X string will be modified to form
1364  * the name of a directory that didn't exist. The string should be
1365  * in the GLib file name encoding. Most importantly, on Windows it
1366  * should be in UTF-8.
1367  *
1368  * Returns: A pointer to @tmpl, which has been modified
1369  *     to hold the directory name. In case of errors, %NULL is
1370  *     returned, and %errno will be set.
1371  *
1372  * Since: 2.30
1373  */
1374 gchar *
1375 g_mkdtemp_full (gchar *tmpl,
1376                 gint   mode)
1377 {
1378   if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1379     return NULL;
1380   else
1381     return tmpl;
1382 }
1383
1384 /**
1385  * g_mkdtemp:
1386  * @tmpl: (type filename): template directory name
1387  *
1388  * Creates a temporary directory. See the mkdtemp() documentation
1389  * on most UNIX-like systems.
1390  *
1391  * The parameter is a string that should follow the rules for
1392  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1393  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1394  * sequence does not have to occur at the very end of the template
1395  * and you can pass a @mode and additional @flags. The X string will
1396  * be modified to form the name of a directory that didn't exist.
1397  * The string should be in the GLib file name encoding. Most importantly,
1398  * on Windows it should be in UTF-8.
1399  *
1400  * Returns: A pointer to @tmpl, which has been modified
1401  *     to hold the directory name.  In case of errors, %NULL is
1402  *     returned and %errno will be set.
1403  *
1404  * Since: 2.30
1405  */
1406 gchar *
1407 g_mkdtemp (gchar *tmpl)
1408 {
1409   return g_mkdtemp_full (tmpl, 0700);
1410 }
1411
1412 /**
1413  * g_mkstemp_full:
1414  * @tmpl: (type filename): template filename
1415  * @flags: flags to pass to an open() call in addition to O_EXCL
1416  *     and O_CREAT, which are passed automatically
1417  * @mode: permissions to create the temporary file with
1418  *
1419  * Opens a temporary file. See the mkstemp() documentation
1420  * on most UNIX-like systems.
1421  *
1422  * The parameter is a string that should follow the rules for
1423  * mkstemp() templates, i.e. contain the string "XXXXXX".
1424  * g_mkstemp_full() is slightly more flexible than mkstemp()
1425  * in that the sequence does not have to occur at the very end of the
1426  * template and you can pass a @mode and additional @flags. The X
1427  * string will be modified to form the name of a file that didn't exist.
1428  * The string should be in the GLib file name encoding. Most importantly,
1429  * on Windows it should be in UTF-8.
1430  *
1431  * Returns: A file handle (as from open()) to the file
1432  *     opened for reading and writing. The file handle should be
1433  *     closed with close(). In case of errors, -1 is returned
1434  *     and %errno will be set.
1435  *
1436  * Since: 2.22
1437  */
1438 gint
1439 g_mkstemp_full (gchar *tmpl,
1440                 gint   flags,
1441                 gint   mode)
1442 {
1443   /* tmpl is in UTF-8 on Windows, thus use g_open() */
1444   return get_tmp_file (tmpl, wrap_g_open,
1445                        flags | O_CREAT | O_EXCL, mode);
1446 }
1447
1448 /**
1449  * g_mkstemp:
1450  * @tmpl: (type filename): template filename
1451  *
1452  * Opens a temporary file. See the mkstemp() documentation
1453  * on most UNIX-like systems.
1454  *
1455  * The parameter is a string that should follow the rules for
1456  * mkstemp() templates, i.e. contain the string "XXXXXX".
1457  * g_mkstemp() is slightly more flexible than mkstemp() in that the
1458  * sequence does not have to occur at the very end of the template.
1459  * The X string will be modified to form the name of a file that
1460  * didn't exist. The string should be in the GLib file name encoding.
1461  * Most importantly, on Windows it should be in UTF-8.
1462  *
1463  * Returns: A file handle (as from open()) to the file
1464  *     opened for reading and writing. The file is opened in binary
1465  *     mode on platforms where there is a difference. The file handle
1466  *     should be closed with close(). In case of errors, -1 is
1467  *     returned and %errno will be set.
1468  */
1469 gint
1470 g_mkstemp (gchar *tmpl)
1471 {
1472   return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1473 }
1474
1475 static gint
1476 g_get_tmp_name (const gchar      *tmpl,
1477                 gchar           **name_used,
1478                 GTmpFileCallback  f,
1479                 gint              flags,
1480                 gint              mode,
1481                 GError          **error)
1482 {
1483   int retval;
1484   const char *tmpdir;
1485   const char *sep;
1486   char *fulltemplate;
1487   const char *slash;
1488
1489   if (tmpl == NULL)
1490     tmpl = ".XXXXXX";
1491
1492   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1493 #ifdef G_OS_WIN32
1494       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1495 #endif
1496       )
1497     {
1498       gchar *display_tmpl = g_filename_display_name (tmpl);
1499       char c[2];
1500       c[0] = *slash;
1501       c[1] = '\0';
1502
1503       g_set_error (error,
1504                    G_FILE_ERROR,
1505                    G_FILE_ERROR_FAILED,
1506                    _("Template '%s' invalid, should not contain a '%s'"),
1507                    display_tmpl, c);
1508       g_free (display_tmpl);
1509
1510       return -1;
1511     }
1512
1513   if (strstr (tmpl, "XXXXXX") == NULL)
1514     {
1515       gchar *display_tmpl = g_filename_display_name (tmpl);
1516       g_set_error (error,
1517                    G_FILE_ERROR,
1518                    G_FILE_ERROR_FAILED,
1519                    _("Template '%s' doesn't contain XXXXXX"),
1520                    display_tmpl);
1521       g_free (display_tmpl);
1522       return -1;
1523     }
1524
1525   tmpdir = g_get_tmp_dir ();
1526
1527   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1528     sep = "";
1529   else
1530     sep = G_DIR_SEPARATOR_S;
1531
1532   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1533
1534   retval = get_tmp_file (fulltemplate, f, flags, mode);
1535   if (retval == -1)
1536     {
1537       int saved_errno = errno;
1538       set_file_error (error,
1539                       fulltemplate,
1540                       _("Failed to create file '%s': %s"),
1541                       saved_errno);
1542       g_free (fulltemplate);
1543       return -1;
1544     }
1545
1546   *name_used = fulltemplate;
1547
1548   return retval;
1549 }
1550
1551 /**
1552  * g_file_open_tmp:
1553  * @tmpl: (type filename) (allow-none): Template for file name, as in
1554  *     g_mkstemp(), basename only, or %NULL for a default template
1555  * @name_used: (out) (type filename): location to store actual name used,
1556  *     or %NULL
1557  * @error: return location for a #GError
1558  *
1559  * Opens a file for writing in the preferred directory for temporary
1560  * files (as returned by g_get_tmp_dir()).
1561  *
1562  * @tmpl should be a string in the GLib file name encoding containing
1563  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1564  * However, unlike these functions, the template should only be a
1565  * basename, no directory components are allowed. If template is
1566  * %NULL, a default template is used.
1567  *
1568  * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1569  * modified, and might thus be a read-only literal string.
1570  *
1571  * Upon success, and if @name_used is non-%NULL, the actual name used
1572  * is returned in @name_used. This string should be freed with g_free()
1573  * when not needed any longer. The returned name is in the GLib file
1574  * name encoding.
1575  *
1576  * Returns: A file handle (as from open()) to the file opened for
1577  *     reading and writing. The file is opened in binary mode on platforms
1578  *     where there is a difference. The file handle should be closed with
1579  *     close(). In case of errors, -1 is returned and @error will be set.
1580  */
1581 gint
1582 g_file_open_tmp (const gchar  *tmpl,
1583                  gchar       **name_used,
1584                  GError      **error)
1585 {
1586   gchar *fulltemplate;
1587   gint result;
1588
1589   result = g_get_tmp_name (tmpl, &fulltemplate,
1590                            wrap_g_open,
1591                            O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1592                            0600,
1593                            error);
1594   if (result != -1)
1595     {
1596       if (name_used)
1597         *name_used = fulltemplate;
1598       else
1599         g_free (fulltemplate);
1600     }
1601
1602   return result;
1603 }
1604
1605 /**
1606  * g_dir_make_tmp:
1607  * @tmpl: (type filename) (allow-none): Template for directory name,
1608  *     as in g_mkdtemp(), basename only, or %NULL for a default template
1609  * @error: return location for a #GError
1610  *
1611  * Creates a subdirectory in the preferred directory for temporary
1612  * files (as returned by g_get_tmp_dir()).
1613  *
1614  * @tmpl should be a string in the GLib file name encoding containing
1615  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1616  * However, unlike these functions, the template should only be a
1617  * basename, no directory components are allowed. If template is
1618  * %NULL, a default template is used.
1619  *
1620  * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1621  * modified, and might thus be a read-only literal string.
1622  *
1623  * Returns: (type filename): The actual name used. This string
1624  *     should be freed with g_free() when not needed any longer and is
1625  *     is in the GLib file name encoding. In case of errors, %NULL is
1626  *     returned and @error will be set.
1627  *
1628  * Since: 2.30
1629  */
1630 gchar *
1631 g_dir_make_tmp (const gchar  *tmpl,
1632                 GError      **error)
1633 {
1634   gchar *fulltemplate;
1635
1636   if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1637     return NULL;
1638   else
1639     return fulltemplate;
1640 }
1641
1642 static gchar *
1643 g_build_path_va (const gchar  *separator,
1644                  const gchar  *first_element,
1645                  va_list      *args,
1646                  gchar       **str_array)
1647 {
1648   GString *result;
1649   gint separator_len = strlen (separator);
1650   gboolean is_first = TRUE;
1651   gboolean have_leading = FALSE;
1652   const gchar *single_element = NULL;
1653   const gchar *next_element;
1654   const gchar *last_trailing = NULL;
1655   gint i = 0;
1656
1657   result = g_string_new (NULL);
1658
1659   if (str_array)
1660     next_element = str_array[i++];
1661   else
1662     next_element = first_element;
1663
1664   while (TRUE)
1665     {
1666       const gchar *element;
1667       const gchar *start;
1668       const gchar *end;
1669
1670       if (next_element)
1671         {
1672           element = next_element;
1673           if (str_array)
1674             next_element = str_array[i++];
1675           else
1676             next_element = va_arg (*args, gchar *);
1677         }
1678       else
1679         break;
1680
1681       /* Ignore empty elements */
1682       if (!*element)
1683         continue;
1684       
1685       start = element;
1686
1687       if (separator_len)
1688         {
1689           while (strncmp (start, separator, separator_len) == 0)
1690             start += separator_len;
1691         }
1692
1693       end = start + strlen (start);
1694       
1695       if (separator_len)
1696         {
1697           while (end >= start + separator_len &&
1698                  strncmp (end - separator_len, separator, separator_len) == 0)
1699             end -= separator_len;
1700           
1701           last_trailing = end;
1702           while (last_trailing >= element + separator_len &&
1703                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1704             last_trailing -= separator_len;
1705
1706           if (!have_leading)
1707             {
1708               /* If the leading and trailing separator strings are in the
1709                * same element and overlap, the result is exactly that element
1710                */
1711               if (last_trailing <= start)
1712                 single_element = element;
1713                   
1714               g_string_append_len (result, element, start - element);
1715               have_leading = TRUE;
1716             }
1717           else
1718             single_element = NULL;
1719         }
1720
1721       if (end == start)
1722         continue;
1723
1724       if (!is_first)
1725         g_string_append (result, separator);
1726       
1727       g_string_append_len (result, start, end - start);
1728       is_first = FALSE;
1729     }
1730
1731   if (single_element)
1732     {
1733       g_string_free (result, TRUE);
1734       return g_strdup (single_element);
1735     }
1736   else
1737     {
1738       if (last_trailing)
1739         g_string_append (result, last_trailing);
1740   
1741       return g_string_free (result, FALSE);
1742     }
1743 }
1744
1745 /**
1746  * g_build_pathv:
1747  * @separator: a string used to separator the elements of the path.
1748  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1749  * 
1750  * Behaves exactly like g_build_path(), but takes the path elements 
1751  * as a string array, instead of varargs. This function is mainly
1752  * meant for language bindings.
1753  *
1754  * Returns: a newly-allocated string that must be freed with g_free().
1755  *
1756  * Since: 2.8
1757  */
1758 gchar *
1759 g_build_pathv (const gchar  *separator,
1760                gchar       **args)
1761 {
1762   if (!args)
1763     return NULL;
1764
1765   return g_build_path_va (separator, NULL, NULL, args);
1766 }
1767
1768
1769 /**
1770  * g_build_path:
1771  * @separator: a string used to separator the elements of the path.
1772  * @first_element: the first element in the path
1773  * @...: remaining elements in path, terminated by %NULL
1774  * 
1775  * Creates a path from a series of elements using @separator as the
1776  * separator between elements. At the boundary between two elements,
1777  * any trailing occurrences of separator in the first element, or
1778  * leading occurrences of separator in the second element are removed
1779  * and exactly one copy of the separator is inserted.
1780  *
1781  * Empty elements are ignored.
1782  *
1783  * The number of leading copies of the separator on the result is
1784  * the same as the number of leading copies of the separator on
1785  * the first non-empty element.
1786  *
1787  * The number of trailing copies of the separator on the result is
1788  * the same as the number of trailing copies of the separator on
1789  * the last non-empty element. (Determination of the number of
1790  * trailing copies is done without stripping leading copies, so
1791  * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
1792  *
1793  * However, if there is only a single non-empty element, and there
1794  * are no characters in that element not part of the leading or
1795  * trailing separators, then the result is exactly the original value
1796  * of that element.
1797  *
1798  * Other than for determination of the number of leading and trailing
1799  * copies of the separator, elements consisting only of copies
1800  * of the separator are ignored.
1801  * 
1802  * Returns: a newly-allocated string that must be freed with g_free().
1803  **/
1804 gchar *
1805 g_build_path (const gchar *separator,
1806               const gchar *first_element,
1807               ...)
1808 {
1809   gchar *str;
1810   va_list args;
1811
1812   g_return_val_if_fail (separator != NULL, NULL);
1813
1814   va_start (args, first_element);
1815   str = g_build_path_va (separator, first_element, &args, NULL);
1816   va_end (args);
1817
1818   return str;
1819 }
1820
1821 #ifdef G_OS_WIN32
1822
1823 static gchar *
1824 g_build_pathname_va (const gchar  *first_element,
1825                      va_list      *args,
1826                      gchar       **str_array)
1827 {
1828   /* Code copied from g_build_pathv(), and modified to use two
1829    * alternative single-character separators.
1830    */
1831   GString *result;
1832   gboolean is_first = TRUE;
1833   gboolean have_leading = FALSE;
1834   const gchar *single_element = NULL;
1835   const gchar *next_element;
1836   const gchar *last_trailing = NULL;
1837   gchar current_separator = '\\';
1838   gint i = 0;
1839
1840   result = g_string_new (NULL);
1841
1842   if (str_array)
1843     next_element = str_array[i++];
1844   else
1845     next_element = first_element;
1846   
1847   while (TRUE)
1848     {
1849       const gchar *element;
1850       const gchar *start;
1851       const gchar *end;
1852
1853       if (next_element)
1854         {
1855           element = next_element;
1856           if (str_array)
1857             next_element = str_array[i++];
1858           else
1859             next_element = va_arg (*args, gchar *);
1860         }
1861       else
1862         break;
1863
1864       /* Ignore empty elements */
1865       if (!*element)
1866         continue;
1867       
1868       start = element;
1869
1870       if (TRUE)
1871         {
1872           while (start &&
1873                  (*start == '\\' || *start == '/'))
1874             {
1875               current_separator = *start;
1876               start++;
1877             }
1878         }
1879
1880       end = start + strlen (start);
1881       
1882       if (TRUE)
1883         {
1884           while (end >= start + 1 &&
1885                  (end[-1] == '\\' || end[-1] == '/'))
1886             {
1887               current_separator = end[-1];
1888               end--;
1889             }
1890           
1891           last_trailing = end;
1892           while (last_trailing >= element + 1 &&
1893                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1894             last_trailing--;
1895
1896           if (!have_leading)
1897             {
1898               /* If the leading and trailing separator strings are in the
1899                * same element and overlap, the result is exactly that element
1900                */
1901               if (last_trailing <= start)
1902                 single_element = element;
1903                   
1904               g_string_append_len (result, element, start - element);
1905               have_leading = TRUE;
1906             }
1907           else
1908             single_element = NULL;
1909         }
1910
1911       if (end == start)
1912         continue;
1913
1914       if (!is_first)
1915         g_string_append_len (result, &current_separator, 1);
1916       
1917       g_string_append_len (result, start, end - start);
1918       is_first = FALSE;
1919     }
1920
1921   if (single_element)
1922     {
1923       g_string_free (result, TRUE);
1924       return g_strdup (single_element);
1925     }
1926   else
1927     {
1928       if (last_trailing)
1929         g_string_append (result, last_trailing);
1930   
1931       return g_string_free (result, FALSE);
1932     }
1933 }
1934
1935 #endif
1936
1937 /**
1938  * g_build_filenamev:
1939  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1940  * 
1941  * Behaves exactly like g_build_filename(), but takes the path elements 
1942  * as a string array, instead of varargs. This function is mainly
1943  * meant for language bindings.
1944  *
1945  * Returns: a newly-allocated string that must be freed with g_free().
1946  * 
1947  * Since: 2.8
1948  */
1949 gchar *
1950 g_build_filenamev (gchar **args)
1951 {
1952   gchar *str;
1953
1954 #ifndef G_OS_WIN32
1955   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1956 #else
1957   str = g_build_pathname_va (NULL, NULL, args);
1958 #endif
1959
1960   return str;
1961 }
1962
1963 /**
1964  * g_build_filename:
1965  * @first_element: the first element in the path
1966  * @...: remaining elements in path, terminated by %NULL
1967  * 
1968  * Creates a filename from a series of elements using the correct
1969  * separator for filenames.
1970  *
1971  * On Unix, this function behaves identically to `g_build_path
1972  * (G_DIR_SEPARATOR_S, first_element, ....)`.
1973  *
1974  * On Windows, it takes into account that either the backslash
1975  * (`\` or slash (`/`) can be used as separator in filenames, but
1976  * otherwise behaves as on UNIX. When file pathname separators need
1977  * to be inserted, the one that last previously occurred in the
1978  * parameters (reading from left to right) is used.
1979  *
1980  * No attempt is made to force the resulting filename to be an absolute
1981  * path. If the first element is a relative path, the result will
1982  * be a relative path. 
1983  * 
1984  * Returns: a newly-allocated string that must be freed with g_free().
1985  **/
1986 gchar *
1987 g_build_filename (const gchar *first_element, 
1988                   ...)
1989 {
1990   gchar *str;
1991   va_list args;
1992
1993   va_start (args, first_element);
1994 #ifndef G_OS_WIN32
1995   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1996 #else
1997   str = g_build_pathname_va (first_element, &args, NULL);
1998 #endif
1999   va_end (args);
2000
2001   return str;
2002 }
2003
2004 /**
2005  * g_file_read_link:
2006  * @filename: the symbolic link
2007  * @error: return location for a #GError
2008  *
2009  * Reads the contents of the symbolic link @filename like the POSIX
2010  * readlink() function.  The returned string is in the encoding used
2011  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2012  *
2013  * Returns: A newly-allocated string with the contents of the symbolic link, 
2014  *          or %NULL if an error occurred.
2015  *
2016  * Since: 2.4
2017  */
2018 gchar *
2019 g_file_read_link (const gchar  *filename,
2020                   GError      **error)
2021 {
2022 #ifdef HAVE_READLINK
2023   gchar *buffer;
2024   guint size;
2025   gint read_size;    
2026   
2027   size = 256; 
2028   buffer = g_malloc (size);
2029   
2030   while (TRUE) 
2031     {
2032       read_size = readlink (filename, buffer, size);
2033       if (read_size < 0)
2034         {
2035           int saved_errno = errno;
2036           set_file_error (error,
2037                           filename,
2038                           _("Failed to read the symbolic link '%s': %s"),
2039                           saved_errno);
2040           g_free (buffer);
2041           return NULL;
2042         }
2043     
2044       if (read_size < size) 
2045         {
2046           buffer[read_size] = 0;
2047           return buffer;
2048         }
2049       
2050       size *= 2;
2051       buffer = g_realloc (buffer, size);
2052     }
2053 #else
2054   g_set_error_literal (error,
2055                        G_FILE_ERROR,
2056                        G_FILE_ERROR_INVAL,
2057                        _("Symbolic links not supported"));
2058         
2059   return NULL;
2060 #endif
2061 }
2062
2063 /**
2064  * g_path_is_absolute:
2065  * @file_name: a file name
2066  *
2067  * Returns %TRUE if the given @file_name is an absolute file name.
2068  * Note that this is a somewhat vague concept on Windows.
2069  *
2070  * On POSIX systems, an absolute file name is well-defined. It always
2071  * starts from the single root directory. For example "/usr/local".
2072  *
2073  * On Windows, the concepts of current drive and drive-specific
2074  * current directory introduce vagueness. This function interprets as
2075  * an absolute file name one that either begins with a directory
2076  * separator such as "\Users\tml" or begins with the root on a drive,
2077  * for example "C:\Windows". The first case also includes UNC paths
2078  * such as "\\myserver\docs\foo". In all cases, either slashes or
2079  * backslashes are accepted.
2080  *
2081  * Note that a file name relative to the current drive root does not
2082  * truly specify a file uniquely over time and across processes, as
2083  * the current drive is a per-process value and can be changed.
2084  *
2085  * File names relative the current directory on some specific drive,
2086  * such as "D:foo/bar", are not interpreted as absolute by this
2087  * function, but they obviously are not relative to the normal current
2088  * directory as returned by getcwd() or g_get_current_dir()
2089  * either. Such paths should be avoided, or need to be handled using
2090  * Windows-specific code.
2091  *
2092  * Returns: %TRUE if @file_name is absolute
2093  */
2094 gboolean
2095 g_path_is_absolute (const gchar *file_name)
2096 {
2097   g_return_val_if_fail (file_name != NULL, FALSE);
2098
2099   if (G_IS_DIR_SEPARATOR (file_name[0]))
2100     return TRUE;
2101
2102 #ifdef G_OS_WIN32
2103   /* Recognize drive letter on native Windows */
2104   if (g_ascii_isalpha (file_name[0]) &&
2105       file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2106     return TRUE;
2107 #endif
2108
2109   return FALSE;
2110 }
2111
2112 /**
2113  * g_path_skip_root:
2114  * @file_name: a file name
2115  *
2116  * Returns a pointer into @file_name after the root component,
2117  * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2118  * is not an absolute path it returns %NULL.
2119  *
2120  * Returns: a pointer into @file_name after the root component
2121  */
2122 const gchar *
2123 g_path_skip_root (const gchar *file_name)
2124 {
2125   g_return_val_if_fail (file_name != NULL, NULL);
2126
2127 #ifdef G_PLATFORM_WIN32
2128   /* Skip \\server\share or //server/share */
2129   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2130       G_IS_DIR_SEPARATOR (file_name[1]) &&
2131       file_name[2] &&
2132       !G_IS_DIR_SEPARATOR (file_name[2]))
2133     {
2134       gchar *p;
2135       p = strchr (file_name + 2, G_DIR_SEPARATOR);
2136
2137 #ifdef G_OS_WIN32
2138       {
2139         gchar *q;
2140
2141         q = strchr (file_name + 2, '/');
2142         if (p == NULL || (q != NULL && q < p))
2143         p = q;
2144       }
2145 #endif
2146
2147       if (p && p > file_name + 2 && p[1])
2148         {
2149           file_name = p + 1;
2150
2151           while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2152             file_name++;
2153
2154           /* Possibly skip a backslash after the share name */
2155           if (G_IS_DIR_SEPARATOR (file_name[0]))
2156             file_name++;
2157
2158           return (gchar *)file_name;
2159         }
2160     }
2161 #endif
2162
2163   /* Skip initial slashes */
2164   if (G_IS_DIR_SEPARATOR (file_name[0]))
2165     {
2166       while (G_IS_DIR_SEPARATOR (file_name[0]))
2167         file_name++;
2168       return (gchar *)file_name;
2169     }
2170
2171 #ifdef G_OS_WIN32
2172   /* Skip X:\ */
2173   if (g_ascii_isalpha (file_name[0]) &&
2174       file_name[1] == ':' &&
2175       G_IS_DIR_SEPARATOR (file_name[2]))
2176     return (gchar *)file_name + 3;
2177 #endif
2178
2179   return NULL;
2180 }
2181
2182 /**
2183  * g_basename:
2184  * @file_name: the name of the file
2185  *
2186  * Gets the name of the file without any leading directory
2187  * components. It returns a pointer into the given file name
2188  * string.
2189  *
2190  * Returns: the name of the file without any leading
2191  *     directory components
2192  *
2193  * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2194  *     that g_path_get_basename() allocates new memory for the
2195  *     returned string, unlike this function which returns a pointer
2196  *     into the argument.
2197  */
2198 const gchar *
2199 g_basename (const gchar *file_name)
2200 {
2201   gchar *base;
2202
2203   g_return_val_if_fail (file_name != NULL, NULL);
2204
2205   base = strrchr (file_name, G_DIR_SEPARATOR);
2206
2207 #ifdef G_OS_WIN32
2208   {
2209     gchar *q;
2210     q = strrchr (file_name, '/');
2211     if (base == NULL || (q != NULL && q > base))
2212       base = q;
2213   }
2214 #endif
2215
2216   if (base)
2217     return base + 1;
2218
2219 #ifdef G_OS_WIN32
2220   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2221     return (gchar*) file_name + 2;
2222 #endif
2223
2224   return (gchar*) file_name;
2225 }
2226
2227 /**
2228  * g_path_get_basename:
2229  * @file_name: the name of the file
2230  *
2231  * Gets the last component of the filename.
2232  *
2233  * If @file_name ends with a directory separator it gets the component
2234  * before the last slash. If @file_name consists only of directory
2235  * separators (and on Windows, possibly a drive letter), a single
2236  * separator is returned. If @file_name is empty, it gets ".".
2237  *
2238  * Returns: a newly allocated string containing the last
2239  *    component of the filename
2240  */
2241 gchar *
2242 g_path_get_basename (const gchar *file_name)
2243 {
2244   gssize base;
2245   gssize last_nonslash;
2246   gsize len;
2247   gchar *retval;
2248
2249   g_return_val_if_fail (file_name != NULL, NULL);
2250
2251   if (file_name[0] == '\0')
2252     return g_strdup (".");
2253
2254   last_nonslash = strlen (file_name) - 1;
2255
2256   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2257     last_nonslash--;
2258
2259   if (last_nonslash == -1)
2260     /* string only containing slashes */
2261     return g_strdup (G_DIR_SEPARATOR_S);
2262
2263 #ifdef G_OS_WIN32
2264   if (last_nonslash == 1 &&
2265       g_ascii_isalpha (file_name[0]) &&
2266       file_name[1] == ':')
2267     /* string only containing slashes and a drive */
2268     return g_strdup (G_DIR_SEPARATOR_S);
2269 #endif
2270   base = last_nonslash;
2271
2272   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2273     base--;
2274
2275 #ifdef G_OS_WIN32
2276   if (base == -1 &&
2277       g_ascii_isalpha (file_name[0]) &&
2278       file_name[1] == ':')
2279     base = 1;
2280 #endif /* G_OS_WIN32 */
2281
2282   len = last_nonslash - base;
2283   retval = g_malloc (len + 1);
2284   memcpy (retval, file_name + base + 1, len);
2285   retval [len] = '\0';
2286
2287   return retval;
2288 }
2289
2290 /**
2291  * g_dirname:
2292  * @file_name: the name of the file
2293  *
2294  * Gets the directory components of a file name.
2295  *
2296  * If the file name has no directory components "." is returned.
2297  * The returned string should be freed when no longer needed.
2298  *
2299  * Returns: the directory components of the file
2300  *
2301  * Deprecated: use g_path_get_dirname() instead
2302  */
2303
2304 /**
2305  * g_path_get_dirname:
2306  * @file_name: the name of the file
2307  *
2308  * Gets the directory components of a file name.
2309  *
2310  * If the file name has no directory components "." is returned.
2311  * The returned string should be freed when no longer needed.
2312  *
2313  * Returns: the directory components of the file
2314  */
2315 gchar *
2316 g_path_get_dirname (const gchar *file_name)
2317 {
2318   gchar *base;
2319   gsize len;
2320
2321   g_return_val_if_fail (file_name != NULL, NULL);
2322
2323   base = strrchr (file_name, G_DIR_SEPARATOR);
2324
2325 #ifdef G_OS_WIN32
2326   {
2327     gchar *q;
2328     q = strrchr (file_name, '/');
2329     if (base == NULL || (q != NULL && q > base))
2330       base = q;
2331   }
2332 #endif
2333
2334   if (!base)
2335     {
2336 #ifdef G_OS_WIN32
2337       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2338         {
2339           gchar drive_colon_dot[4];
2340
2341           drive_colon_dot[0] = file_name[0];
2342           drive_colon_dot[1] = ':';
2343           drive_colon_dot[2] = '.';
2344           drive_colon_dot[3] = '\0';
2345
2346           return g_strdup (drive_colon_dot);
2347         }
2348 #endif
2349     return g_strdup (".");
2350     }
2351
2352   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2353     base--;
2354
2355 #ifdef G_OS_WIN32
2356   /* base points to the char before the last slash.
2357    *
2358    * In case file_name is the root of a drive (X:\) or a child of the
2359    * root of a drive (X:\foo), include the slash.
2360    *
2361    * In case file_name is the root share of an UNC path
2362    * (\\server\share), add a slash, returning \\server\share\ .
2363    *
2364    * In case file_name is a direct child of a share in an UNC path
2365    * (\\server\share\foo), include the slash after the share name,
2366    * returning \\server\share\ .
2367    */
2368   if (base == file_name + 1 &&
2369       g_ascii_isalpha (file_name[0]) &&
2370       file_name[1] == ':')
2371     base++;
2372   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2373            G_IS_DIR_SEPARATOR (file_name[1]) &&
2374            file_name[2] &&
2375            !G_IS_DIR_SEPARATOR (file_name[2]) &&
2376            base >= file_name + 2)
2377     {
2378       const gchar *p = file_name + 2;
2379       while (*p && !G_IS_DIR_SEPARATOR (*p))
2380         p++;
2381       if (p == base + 1)
2382         {
2383           len = (guint) strlen (file_name) + 1;
2384           base = g_new (gchar, len + 1);
2385           strcpy (base, file_name);
2386           base[len-1] = G_DIR_SEPARATOR;
2387           base[len] = 0;
2388           return base;
2389         }
2390       if (G_IS_DIR_SEPARATOR (*p))
2391         {
2392           p++;
2393           while (*p && !G_IS_DIR_SEPARATOR (*p))
2394             p++;
2395           if (p == base + 1)
2396             base++;
2397         }
2398     }
2399 #endif
2400
2401   len = (guint) 1 + base - file_name;
2402   base = g_new (gchar, len + 1);
2403   memmove (base, file_name, len);
2404   base[len] = 0;
2405
2406   return base;
2407 }
2408
2409 #if defined(MAXPATHLEN)
2410 #define G_PATH_LENGTH MAXPATHLEN
2411 #elif defined(PATH_MAX)
2412 #define G_PATH_LENGTH PATH_MAX
2413 #elif defined(_PC_PATH_MAX)
2414 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2415 #else
2416 #define G_PATH_LENGTH 2048
2417 #endif
2418
2419 /**
2420  * g_get_current_dir:
2421  *
2422  * Gets the current directory.
2423  *
2424  * The returned string should be freed when no longer needed.
2425  * The encoding of the returned string is system defined.
2426  * On Windows, it is always UTF-8.
2427  *
2428  * Since GLib 2.40, this function will return the value of the "PWD"
2429  * environment variable if it is set and it happens to be the same as
2430  * the current directory.  This can make a difference in the case that
2431  * the current directory is the target of a symbolic link.
2432  *
2433  * Returns: the current directory
2434  */
2435 gchar *
2436 g_get_current_dir (void)
2437 {
2438 #ifdef G_OS_WIN32
2439
2440   gchar *dir = NULL;
2441   wchar_t dummy[2], *wdir;
2442   int len;
2443
2444   len = GetCurrentDirectoryW (2, dummy);
2445   wdir = g_new (wchar_t, len);
2446
2447   if (GetCurrentDirectoryW (len, wdir) == len - 1)
2448     dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2449
2450   g_free (wdir);
2451
2452   if (dir == NULL)
2453     dir = g_strdup ("\\");
2454
2455   return dir;
2456
2457 #else
2458   const gchar *pwd;
2459   gchar *buffer = NULL;
2460   gchar *dir = NULL;
2461   static gulong max_len = 0;
2462   struct stat pwdbuf, dotbuf;
2463
2464   pwd = g_getenv ("PWD");
2465   if (pwd != NULL &&
2466       g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2467       dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2468     return g_strdup (pwd);
2469
2470   if (max_len == 0)
2471     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2472
2473   while (max_len < G_MAXULONG / 2)
2474     {
2475       g_free (buffer);
2476       buffer = g_new (gchar, max_len + 1);
2477       *buffer = 0;
2478       dir = getcwd (buffer, max_len);
2479
2480       if (dir || errno != ERANGE)
2481         break;
2482
2483       max_len *= 2;
2484     }
2485
2486   if (!dir || !*buffer)
2487     {
2488       /* hm, should we g_error() out here?
2489        * this can happen if e.g. "./" has mode \0000
2490        */
2491       buffer[0] = G_DIR_SEPARATOR;
2492       buffer[1] = 0;
2493     }
2494
2495   dir = g_strdup (buffer);
2496   g_free (buffer);
2497
2498   return dir;
2499
2500 #endif /* !G_OS_WIN32 */
2501 }
2502
2503
2504 /* NOTE : Keep this part last to ensure nothing in this file uses thn
2505  * below binary compatibility versions.
2506  */
2507 #if defined (G_OS_WIN32) && !defined (_WIN64)
2508
2509 /* Binary compatibility versions. Will be called by code compiled
2510  * against quite old (pre-2.8, I think) headers only, not from more
2511  * recently compiled code.
2512  */
2513
2514 #undef g_file_test
2515
2516 gboolean
2517 g_file_test (const gchar *filename,
2518              GFileTest    test)
2519 {
2520   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
2521   gboolean retval;
2522
2523   if (utf8_filename == NULL)
2524     return FALSE;
2525
2526   retval = g_file_test_utf8 (utf8_filename, test);
2527
2528   g_free (utf8_filename);
2529
2530   return retval;
2531 }
2532
2533 #undef g_file_get_contents
2534
2535 gboolean
2536 g_file_get_contents (const gchar  *filename,
2537                      gchar       **contents,
2538                      gsize        *length,
2539                      GError      **error)
2540 {
2541   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2542   gboolean retval;
2543
2544   if (utf8_filename == NULL)
2545     return FALSE;
2546
2547   retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
2548
2549   g_free (utf8_filename);
2550
2551   return retval;
2552 }
2553
2554 #undef g_mkstemp
2555
2556 static gint
2557 wrap_libc_open (const gchar *filename,
2558                 int          flags,
2559                 int          mode)
2560 {
2561   return open (filename, flags, mode);
2562 }
2563
2564 gint
2565 g_mkstemp (gchar *tmpl)
2566 {
2567   /* This is the backward compatibility system codepage version,
2568    * thus use normal open().
2569    */
2570   return get_tmp_file (tmpl, wrap_libc_open,
2571                        O_RDWR | O_CREAT | O_EXCL, 0600);
2572 }
2573
2574 #undef g_file_open_tmp
2575
2576 gint
2577 g_file_open_tmp (const gchar  *tmpl,
2578                  gchar       **name_used,
2579                  GError      **error)
2580 {
2581   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2582   gchar *utf8_name_used;
2583   gint retval;
2584
2585   if (utf8_tmpl == NULL)
2586     return -1;
2587
2588   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2589   
2590   if (retval == -1)
2591     return -1;
2592
2593   if (name_used)
2594     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2595
2596   g_free (utf8_name_used);
2597
2598   return retval;
2599 }
2600
2601 #undef g_get_current_dir
2602
2603 gchar *
2604 g_get_current_dir (void)
2605 {
2606   gchar *utf8_dir = g_get_current_dir_utf8 ();
2607   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2608   g_free (utf8_dir);
2609   return dir;
2610 }
2611
2612 #endif
2613