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