gfileutils: fix docs/annotations for temp file methods
[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  no_fsync:
1018   
1019   errno = 0;
1020   if (fclose (file) == EOF)
1021     { 
1022       save_errno = errno;
1023       
1024       g_set_error (err,
1025                    G_FILE_ERROR,
1026                    g_file_error_from_errno (save_errno),
1027                    _("Failed to close file '%s': fclose() failed: %s"),
1028                    display_name, 
1029                    g_strerror (save_errno));
1030
1031       fclose (file);
1032       g_unlink (tmp_name);
1033       
1034       goto out;
1035     }
1036
1037   retval = g_strdup (tmp_name);
1038   
1039  out:
1040   g_free (tmp_name);
1041   g_free (display_name);
1042   
1043   return retval;
1044 }
1045
1046 /**
1047  * g_file_set_contents:
1048  * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1049  *   encoding
1050  * @contents: (array length=length) (element-type guint8): string to write to the file
1051  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1052  * @error: return location for a #GError, or %NULL
1053  *
1054  * Writes all of @contents to a file named @filename, with good error checking.
1055  * If a file called @filename already exists it will be overwritten.
1056  *
1057  * This write is atomic in the sense that it is first written to a temporary
1058  * file which is then renamed to the final name. Notes:
1059  * <itemizedlist>
1060  * <listitem>
1061  *    On Unix, if @filename already exists hard links to @filename will break.
1062  *    Also since the file is recreated, existing permissions, access control
1063  *    lists, metadata etc. may be lost. If @filename is a symbolic link,
1064  *    the link itself will be replaced, not the linked file.
1065  * </listitem>
1066  * <listitem>
1067  *   On Windows renaming a file will not remove an existing file with the
1068  *   new name, so on Windows there is a race condition between the existing
1069  *   file being removed and the temporary file being renamed.
1070  * </listitem>
1071  * <listitem>
1072  *   On Windows there is no way to remove a file that is open to some
1073  *   process, or mapped into memory. Thus, this function will fail if
1074  *   @filename already exists and is open.
1075  * </listitem>
1076  * </itemizedlist>
1077  *
1078  * If the call was sucessful, it returns %TRUE. If the call was not successful,
1079  * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1080  * Possible error codes are those in the #GFileError enumeration.
1081  *
1082  * Note that the name for the temporary file is constructed by appending up
1083  * to 7 characters to @filename.
1084  *
1085  * Return value: %TRUE on success, %FALSE if an error occurred
1086  *
1087  * Since: 2.8
1088  **/
1089 gboolean
1090 g_file_set_contents (const gchar  *filename,
1091                      const gchar  *contents,
1092                      gssize        length,
1093                      GError      **error)
1094 {
1095   gchar *tmp_filename;
1096   gboolean retval;
1097   GError *rename_error = NULL;
1098   
1099   g_return_val_if_fail (filename != NULL, FALSE);
1100   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1101   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1102   g_return_val_if_fail (length >= -1, FALSE);
1103   
1104   if (length == -1)
1105     length = strlen (contents);
1106
1107   tmp_filename = write_to_temp_file (contents, length, filename, error);
1108   
1109   if (!tmp_filename)
1110     {
1111       retval = FALSE;
1112       goto out;
1113     }
1114
1115   if (!rename_file (tmp_filename, filename, &rename_error))
1116     {
1117 #ifndef G_OS_WIN32
1118
1119       g_unlink (tmp_filename);
1120       g_propagate_error (error, rename_error);
1121       retval = FALSE;
1122       goto out;
1123
1124 #else /* G_OS_WIN32 */
1125       
1126       /* Renaming failed, but on Windows this may just mean
1127        * the file already exists. So if the target file
1128        * exists, try deleting it and do the rename again.
1129        */
1130       if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1131         {
1132           g_unlink (tmp_filename);
1133           g_propagate_error (error, rename_error);
1134           retval = FALSE;
1135           goto out;
1136         }
1137
1138       g_error_free (rename_error);
1139       
1140       if (g_unlink (filename) == -1)
1141         {
1142           gchar *display_filename = g_filename_display_name (filename);
1143
1144           int save_errno = errno;
1145           
1146           g_set_error (error,
1147                        G_FILE_ERROR,
1148                        g_file_error_from_errno (save_errno),
1149                        _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1150                        display_filename,
1151                        g_strerror (save_errno));
1152
1153           g_free (display_filename);
1154           g_unlink (tmp_filename);
1155           retval = FALSE;
1156           goto out;
1157         }
1158       
1159       if (!rename_file (tmp_filename, filename, error))
1160         {
1161           g_unlink (tmp_filename);
1162           retval = FALSE;
1163           goto out;
1164         }
1165
1166 #endif
1167     }
1168
1169   retval = TRUE;
1170   
1171  out:
1172   g_free (tmp_filename);
1173   return retval;
1174 }
1175
1176 /*
1177  * get_tmp_file based on the mkstemp implementation from the GNU C library.
1178  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1179  */
1180 typedef gint (*GTmpFileCallback) (gchar *, gint, gint);
1181
1182 static gint
1183 get_tmp_file (gchar            *tmpl,
1184               GTmpFileCallback  f,
1185               int               flags,
1186               int               mode)
1187 {
1188   char *XXXXXX;
1189   int count, fd;
1190   static const char letters[] =
1191     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1192   static const int NLETTERS = sizeof (letters) - 1;
1193   glong value;
1194   GTimeVal tv;
1195   static int counter = 0;
1196
1197   g_return_val_if_fail (tmpl != NULL, -1);
1198
1199   /* find the last occurrence of "XXXXXX" */
1200   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1201
1202   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1203     {
1204       errno = EINVAL;
1205       return -1;
1206     }
1207
1208   /* Get some more or less random data.  */
1209   g_get_current_time (&tv);
1210   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1211
1212   for (count = 0; count < 100; value += 7777, ++count)
1213     {
1214       glong v = value;
1215
1216       /* Fill in the random bits.  */
1217       XXXXXX[0] = letters[v % NLETTERS];
1218       v /= NLETTERS;
1219       XXXXXX[1] = letters[v % NLETTERS];
1220       v /= NLETTERS;
1221       XXXXXX[2] = letters[v % NLETTERS];
1222       v /= NLETTERS;
1223       XXXXXX[3] = letters[v % NLETTERS];
1224       v /= NLETTERS;
1225       XXXXXX[4] = letters[v % NLETTERS];
1226       v /= NLETTERS;
1227       XXXXXX[5] = letters[v % NLETTERS];
1228
1229       fd = f (tmpl, flags, mode);
1230
1231       if (fd >= 0)
1232         return fd;
1233       else if (errno != EEXIST)
1234         /* Any other error will apply also to other names we might
1235          *  try, and there are 2^32 or so of them, so give up now.
1236          */
1237         return -1;
1238     }
1239
1240   /* We got out of the loop because we ran out of combinations to try.  */
1241   errno = EEXIST;
1242   return -1;
1243 }
1244
1245 gint
1246 wrap_mkdir (gchar *tmpl,
1247             int    flags G_GNUC_UNUSED,
1248             int    mode)
1249 {
1250   /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1251   return g_mkdir (tmpl, mode);
1252 }
1253
1254 /**
1255  * g_mkdtemp_full:
1256  * @tmpl: (type filename): template directory name
1257  * @mode: permissions to create the temporary directory with
1258  *
1259  * Creates a temporary directory. See the mkdtemp() documentation
1260  * on most UNIX-like systems.
1261  *
1262  * The parameter is a string that should follow the rules for
1263  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1264  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1265  * sequence does not have to occur at the very end of the template
1266  * and you can pass a @mode. The X string will be modified to form
1267  * the name of a directory that didn't exist. The string should be
1268  * in the GLib file name encoding. Most importantly, on Windows it
1269  * should be in UTF-8.
1270  *
1271  * Return value: A pointer to @tmpl, which has been modified
1272  *     to hold the directory name. In case of errors, %NULL is
1273  *     returned, and %errno will be set.
1274  *
1275  * Since: 2.26
1276  */
1277 gchar *
1278 g_mkdtemp_full (gchar *tmpl,
1279                 gint   mode)
1280 {
1281   if (get_tmp_file (tmpl, wrap_mkdir, 0, mode) == -1)
1282     return NULL;
1283   else
1284     return tmpl;
1285 }
1286
1287 /**
1288  * g_mkdtemp:
1289  * @tmpl: (type filename): template directory name
1290  *
1291  * Creates a temporary directory. See the mkdtemp() documentation
1292  * on most UNIX-like systems.
1293  *
1294  * The parameter is a string that should follow the rules for
1295  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1296  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1297  * sequence does not have to occur at the very end of the template
1298  * and you can pass a @mode and additional @flags. The X string will
1299  * be modified to form the name of a directory that didn't exist.
1300  * The string should be in the GLib file name encoding. Most importantly,
1301  * on Windows it should be in UTF-8.
1302  *
1303  * Return value: A pointer to @tmpl, which has been modified
1304  *     to hold the directory name.  In case of errors, %NULL is
1305  *     returned and %errno will be set.
1306  *
1307  * Since: 2.26
1308  */
1309 gchar *
1310 g_mkdtemp (gchar *tmpl)
1311 {
1312   return g_mkdtemp_full (tmpl, 0700);
1313 }
1314
1315 /**
1316  * g_mkstemp_full:
1317  * @tmpl: (type filename): template filename
1318  * @flags: flags to pass to an open() call in addition to O_EXCL
1319  *     and O_CREAT, which are passed automatically
1320  * @mode: permissions to create the temporary file with
1321  *
1322  * Opens a temporary file. See the mkstemp() documentation
1323  * on most UNIX-like systems.
1324  *
1325  * The parameter is a string that should follow the rules for
1326  * mkstemp() templates, i.e. contain the string "XXXXXX".
1327  * g_mkstemp_full() is slightly more flexible than mkstemp()
1328  * in that the sequence does not have to occur at the very end of the
1329  * template and you can pass a @mode and additional @flags. The X
1330  * string will be modified to form the name of a file that didn't exist.
1331  * The string should be in the GLib file name encoding. Most importantly,
1332  * on Windows it should be in UTF-8.
1333  *
1334  * Return value: A file handle (as from open()) to the file
1335  *     opened for reading and writing. The file handle should be
1336  *     closed with close(). In case of errors, -1 is returned
1337  *     and %errno will be set.
1338  *
1339  * Since: 2.22
1340  */
1341 gint
1342 g_mkstemp_full (gchar *tmpl,
1343                 gint   flags,
1344                 gint   mode)
1345 {
1346   /* tmpl is in UTF-8 on Windows, thus use g_open() */
1347   return get_tmp_file (tmpl, (GTmpFileCallback) g_open,
1348                        flags | O_CREAT | O_EXCL, mode);
1349 }
1350
1351 /**
1352  * g_mkstemp:
1353  * @tmpl: (type filename): template filename
1354  *
1355  * Opens a temporary file. See the mkstemp() documentation
1356  * on most UNIX-like systems.
1357  *
1358  * The parameter is a string that should follow the rules for
1359  * mkstemp() templates, i.e. contain the string "XXXXXX".
1360  * g_mkstemp() is slightly more flexible than mkstemp() in that the
1361  * sequence does not have to occur at the very end of the template.
1362  * The X string will be modified to form the name of a file that
1363  * didn't exist. The string should be in the GLib file name encoding.
1364  * Most importantly, on Windows it should be in UTF-8.
1365  *
1366  * Return value: A file handle (as from open()) to the file
1367  *     opened for reading and writing. The file is opened in binary
1368  *     mode on platforms where there is a difference. The file handle
1369  *     should be closed with close(). In case of errors, -1 is
1370  *     returned and %errno will be set.
1371  */
1372 gint
1373 g_mkstemp (gchar *tmpl)
1374 {
1375   return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1376 }
1377
1378 static gint
1379 g_get_tmp_name (const gchar      *tmpl,
1380                 gchar           **name_used,
1381                 GTmpFileCallback  f,
1382                 gint              flags,
1383                 gint              mode,
1384                 GError          **error)
1385 {
1386   int retval;
1387   const char *tmpdir;
1388   const char *sep;
1389   char *fulltemplate;
1390   const char *slash;
1391
1392   if (tmpl == NULL)
1393     tmpl = ".XXXXXX";
1394
1395   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1396 #ifdef G_OS_WIN32
1397       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1398 #endif
1399       )
1400     {
1401       gchar *display_tmpl = g_filename_display_name (tmpl);
1402       char c[2];
1403       c[0] = *slash;
1404       c[1] = '\0';
1405
1406       g_set_error (error,
1407                    G_FILE_ERROR,
1408                    G_FILE_ERROR_FAILED,
1409                    _("Template '%s' invalid, should not contain a '%s'"),
1410                    display_tmpl, c);
1411       g_free (display_tmpl);
1412
1413       return -1;
1414     }
1415
1416   if (strstr (tmpl, "XXXXXX") == NULL)
1417     {
1418       gchar *display_tmpl = g_filename_display_name (tmpl);
1419       g_set_error (error,
1420                    G_FILE_ERROR,
1421                    G_FILE_ERROR_FAILED,
1422                    _("Template '%s' doesn't contain XXXXXX"),
1423                    display_tmpl);
1424       g_free (display_tmpl);
1425       return -1;
1426     }
1427
1428   tmpdir = g_get_tmp_dir ();
1429
1430   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1431     sep = "";
1432   else
1433     sep = G_DIR_SEPARATOR_S;
1434
1435   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1436
1437   retval = get_tmp_file (fulltemplate, f, flags, mode);
1438   if (retval == -1)
1439     {
1440       int save_errno = errno;
1441       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1442
1443       g_set_error (error,
1444                    G_FILE_ERROR,
1445                    g_file_error_from_errno (save_errno),
1446                    _("Failed to create file '%s': %s"),
1447                    display_fulltemplate, g_strerror (save_errno));
1448       g_free (display_fulltemplate);
1449       g_free (fulltemplate);
1450       return -1;
1451     }
1452
1453   *name_used = fulltemplate;
1454
1455   return retval;
1456 }
1457
1458 /**
1459  * g_file_open_tmp:
1460  * @tmpl: (type filename) (allow-none): Template for file name, as in
1461  *     g_mkstemp(), basename only, or %NULL for a default template
1462  * @name_used: (out) (type filename): location to store actual name used,
1463  *     or %NULL
1464  * @error: return location for a #GError
1465  *
1466  * Opens a file for writing in the preferred directory for temporary
1467  * files (as returned by g_get_tmp_dir()).
1468  *
1469  * @tmpl should be a string in the GLib file name encoding containing
1470  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1471  * However, unlike these functions, the template should only be a
1472  * basename, no directory components are allowed. If template is
1473  * %NULL, a default template is used.
1474  *
1475  * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1476  * modified, and might thus be a read-only literal string.
1477  *
1478  * Upon success, and if @name_used is non-%NULL, the actual name used
1479  * is returned in @name_used. This string should be freed with g_free()
1480  * when not needed any longer. The returned name is in the GLib file
1481  * name encoding.
1482  *
1483  * Return value: A file handle (as from open()) to the file opened for
1484  *     reading and writing. The file is opened in binary mode on platforms
1485  *     where there is a difference. The file handle should be closed with
1486  *     close(). In case of errors, -1 is returned and @error will be set.
1487  */
1488 gint
1489 g_file_open_tmp (const gchar  *tmpl,
1490                  gchar       **name_used,
1491                  GError      **error)
1492 {
1493   gchar *fulltemplate;
1494   gint result;
1495
1496   result = g_get_tmp_name (tmpl, &fulltemplate,
1497                            (GTmpFileCallback) g_open,
1498                            O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1499                            0600,
1500                            error);
1501   if (result != -1)
1502     {
1503       if (name_used)
1504         *name_used = fulltemplate;
1505       else
1506         g_free (fulltemplate);
1507     }
1508
1509   return result;
1510 }
1511
1512 /**
1513  * g_dir_make_tmp:
1514  * @tmpl: (type filename) (allow-none): Template for directory name,
1515  *     as in g_mkdtemp(), basename only, or %NULL for a default template
1516  * @error: return location for a #GError
1517  *
1518  * Creates a subdirectory in the preferred directory for temporary
1519  * files (as returned by g_get_tmp_dir()).
1520  *
1521  * @tmpl should be a string in the GLib file name encoding containing
1522  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1523  * However, unlike these functions, the template should only be a
1524  * basename, no directory components are allowed. If template is
1525  * %NULL, a default template is used.
1526  *
1527  * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1528  * modified, and might thus be a read-only literal string.
1529  *
1530  * Return value: (type filename): The actual name used. This string
1531  *     should be freed with g_free() when not needed any longer and is
1532  *     is in the GLib file name encoding. In case of errors, %NULL is
1533  *     returned and @error will be set.
1534  *
1535  * Since: 2.30
1536  */
1537 gchar *
1538 g_dir_make_tmp (const gchar  *tmpl,
1539                 GError      **error)
1540 {
1541   gchar *fulltemplate;
1542
1543   if (g_get_tmp_name (tmpl, &fulltemplate, wrap_mkdir, 0, 0700, error) == -1)
1544     return NULL;
1545   else
1546     return fulltemplate;
1547 }
1548
1549 static gchar *
1550 g_build_path_va (const gchar  *separator,
1551                  const gchar  *first_element,
1552                  va_list      *args,
1553                  gchar       **str_array)
1554 {
1555   GString *result;
1556   gint separator_len = strlen (separator);
1557   gboolean is_first = TRUE;
1558   gboolean have_leading = FALSE;
1559   const gchar *single_element = NULL;
1560   const gchar *next_element;
1561   const gchar *last_trailing = NULL;
1562   gint i = 0;
1563
1564   result = g_string_new (NULL);
1565
1566   if (str_array)
1567     next_element = str_array[i++];
1568   else
1569     next_element = first_element;
1570
1571   while (TRUE)
1572     {
1573       const gchar *element;
1574       const gchar *start;
1575       const gchar *end;
1576
1577       if (next_element)
1578         {
1579           element = next_element;
1580           if (str_array)
1581             next_element = str_array[i++];
1582           else
1583             next_element = va_arg (*args, gchar *);
1584         }
1585       else
1586         break;
1587
1588       /* Ignore empty elements */
1589       if (!*element)
1590         continue;
1591       
1592       start = element;
1593
1594       if (separator_len)
1595         {
1596           while (strncmp (start, separator, separator_len) == 0)
1597             start += separator_len;
1598         }
1599
1600       end = start + strlen (start);
1601       
1602       if (separator_len)
1603         {
1604           while (end >= start + separator_len &&
1605                  strncmp (end - separator_len, separator, separator_len) == 0)
1606             end -= separator_len;
1607           
1608           last_trailing = end;
1609           while (last_trailing >= element + separator_len &&
1610                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1611             last_trailing -= separator_len;
1612
1613           if (!have_leading)
1614             {
1615               /* If the leading and trailing separator strings are in the
1616                * same element and overlap, the result is exactly that element
1617                */
1618               if (last_trailing <= start)
1619                 single_element = element;
1620                   
1621               g_string_append_len (result, element, start - element);
1622               have_leading = TRUE;
1623             }
1624           else
1625             single_element = NULL;
1626         }
1627
1628       if (end == start)
1629         continue;
1630
1631       if (!is_first)
1632         g_string_append (result, separator);
1633       
1634       g_string_append_len (result, start, end - start);
1635       is_first = FALSE;
1636     }
1637
1638   if (single_element)
1639     {
1640       g_string_free (result, TRUE);
1641       return g_strdup (single_element);
1642     }
1643   else
1644     {
1645       if (last_trailing)
1646         g_string_append (result, last_trailing);
1647   
1648       return g_string_free (result, FALSE);
1649     }
1650 }
1651
1652 /**
1653  * g_build_pathv:
1654  * @separator: a string used to separator the elements of the path.
1655  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1656  * 
1657  * Behaves exactly like g_build_path(), but takes the path elements 
1658  * as a string array, instead of varargs. This function is mainly
1659  * meant for language bindings.
1660  *
1661  * Return value: a newly-allocated string that must be freed with g_free().
1662  *
1663  * Since: 2.8
1664  */
1665 gchar *
1666 g_build_pathv (const gchar  *separator,
1667                gchar       **args)
1668 {
1669   if (!args)
1670     return NULL;
1671
1672   return g_build_path_va (separator, NULL, NULL, args);
1673 }
1674
1675
1676 /**
1677  * g_build_path:
1678  * @separator: a string used to separator the elements of the path.
1679  * @first_element: the first element in the path
1680  * @...: remaining elements in path, terminated by %NULL
1681  * 
1682  * Creates a path from a series of elements using @separator as the
1683  * separator between elements. At the boundary between two elements,
1684  * any trailing occurrences of separator in the first element, or
1685  * leading occurrences of separator in the second element are removed
1686  * and exactly one copy of the separator is inserted.
1687  *
1688  * Empty elements are ignored.
1689  *
1690  * The number of leading copies of the separator on the result is
1691  * the same as the number of leading copies of the separator on
1692  * the first non-empty element.
1693  *
1694  * The number of trailing copies of the separator on the result is
1695  * the same as the number of trailing copies of the separator on
1696  * the last non-empty element. (Determination of the number of
1697  * trailing copies is done without stripping leading copies, so
1698  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1699  * has 1 trailing copy.)
1700  *
1701  * However, if there is only a single non-empty element, and there
1702  * are no characters in that element not part of the leading or
1703  * trailing separators, then the result is exactly the original value
1704  * of that element.
1705  *
1706  * Other than for determination of the number of leading and trailing
1707  * copies of the separator, elements consisting only of copies
1708  * of the separator are ignored.
1709  * 
1710  * Return value: a newly-allocated string that must be freed with g_free().
1711  **/
1712 gchar *
1713 g_build_path (const gchar *separator,
1714               const gchar *first_element,
1715               ...)
1716 {
1717   gchar *str;
1718   va_list args;
1719
1720   g_return_val_if_fail (separator != NULL, NULL);
1721
1722   va_start (args, first_element);
1723   str = g_build_path_va (separator, first_element, &args, NULL);
1724   va_end (args);
1725
1726   return str;
1727 }
1728
1729 #ifdef G_OS_WIN32
1730
1731 static gchar *
1732 g_build_pathname_va (const gchar  *first_element,
1733                      va_list      *args,
1734                      gchar       **str_array)
1735 {
1736   /* Code copied from g_build_pathv(), and modified to use two
1737    * alternative single-character separators.
1738    */
1739   GString *result;
1740   gboolean is_first = TRUE;
1741   gboolean have_leading = FALSE;
1742   const gchar *single_element = NULL;
1743   const gchar *next_element;
1744   const gchar *last_trailing = NULL;
1745   gchar current_separator = '\\';
1746   gint i = 0;
1747
1748   result = g_string_new (NULL);
1749
1750   if (str_array)
1751     next_element = str_array[i++];
1752   else
1753     next_element = first_element;
1754   
1755   while (TRUE)
1756     {
1757       const gchar *element;
1758       const gchar *start;
1759       const gchar *end;
1760
1761       if (next_element)
1762         {
1763           element = next_element;
1764           if (str_array)
1765             next_element = str_array[i++];
1766           else
1767             next_element = va_arg (*args, gchar *);
1768         }
1769       else
1770         break;
1771
1772       /* Ignore empty elements */
1773       if (!*element)
1774         continue;
1775       
1776       start = element;
1777
1778       if (TRUE)
1779         {
1780           while (start &&
1781                  (*start == '\\' || *start == '/'))
1782             {
1783               current_separator = *start;
1784               start++;
1785             }
1786         }
1787
1788       end = start + strlen (start);
1789       
1790       if (TRUE)
1791         {
1792           while (end >= start + 1 &&
1793                  (end[-1] == '\\' || end[-1] == '/'))
1794             {
1795               current_separator = end[-1];
1796               end--;
1797             }
1798           
1799           last_trailing = end;
1800           while (last_trailing >= element + 1 &&
1801                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1802             last_trailing--;
1803
1804           if (!have_leading)
1805             {
1806               /* If the leading and trailing separator strings are in the
1807                * same element and overlap, the result is exactly that element
1808                */
1809               if (last_trailing <= start)
1810                 single_element = element;
1811                   
1812               g_string_append_len (result, element, start - element);
1813               have_leading = TRUE;
1814             }
1815           else
1816             single_element = NULL;
1817         }
1818
1819       if (end == start)
1820         continue;
1821
1822       if (!is_first)
1823         g_string_append_len (result, &current_separator, 1);
1824       
1825       g_string_append_len (result, start, end - start);
1826       is_first = FALSE;
1827     }
1828
1829   if (single_element)
1830     {
1831       g_string_free (result, TRUE);
1832       return g_strdup (single_element);
1833     }
1834   else
1835     {
1836       if (last_trailing)
1837         g_string_append (result, last_trailing);
1838   
1839       return g_string_free (result, FALSE);
1840     }
1841 }
1842
1843 #endif
1844
1845 /**
1846  * g_build_filenamev:
1847  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1848  * 
1849  * Behaves exactly like g_build_filename(), but takes the path elements 
1850  * as a string array, instead of varargs. This function is mainly
1851  * meant for language bindings.
1852  *
1853  * Return value: a newly-allocated string that must be freed with g_free().
1854  * 
1855  * Since: 2.8
1856  */
1857 gchar *
1858 g_build_filenamev (gchar **args)
1859 {
1860   gchar *str;
1861
1862 #ifndef G_OS_WIN32
1863   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1864 #else
1865   str = g_build_pathname_va (NULL, NULL, args);
1866 #endif
1867
1868   return str;
1869 }
1870
1871 /**
1872  * g_build_filename:
1873  * @first_element: the first element in the path
1874  * @...: remaining elements in path, terminated by %NULL
1875  * 
1876  * Creates a filename from a series of elements using the correct
1877  * separator for filenames.
1878  *
1879  * On Unix, this function behaves identically to <literal>g_build_path
1880  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1881  *
1882  * On Windows, it takes into account that either the backslash
1883  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1884  * as separator in filenames, but otherwise behaves as on Unix. When
1885  * file pathname separators need to be inserted, the one that last
1886  * previously occurred in the parameters (reading from left to right)
1887  * is used.
1888  *
1889  * No attempt is made to force the resulting filename to be an absolute
1890  * path. If the first element is a relative path, the result will
1891  * be a relative path. 
1892  * 
1893  * Return value: a newly-allocated string that must be freed with g_free().
1894  **/
1895 gchar *
1896 g_build_filename (const gchar *first_element, 
1897                   ...)
1898 {
1899   gchar *str;
1900   va_list args;
1901
1902   va_start (args, first_element);
1903 #ifndef G_OS_WIN32
1904   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1905 #else
1906   str = g_build_pathname_va (first_element, &args, NULL);
1907 #endif
1908   va_end (args);
1909
1910   return str;
1911 }
1912
1913 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
1914 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
1915 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
1916 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
1917 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
1918 #define EXABYTE_FACTOR  (PETABYTE_FACTOR * KILOBYTE_FACTOR)
1919
1920 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
1921 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
1922 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
1923 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
1924 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
1925 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
1926
1927 /**
1928  * g_format_size:
1929  * @size: a size in bytes
1930  *
1931  * Formats a size (for example the size of a file) into a human readable
1932  * string.  Sizes are rounded to the nearest size prefix (kB, MB, GB)
1933  * and are displayed rounded to the nearest tenth. E.g. the file size
1934  * 3292528 bytes will be converted into the string "3.2 MB".
1935  *
1936  * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
1937  *
1938  * This string should be freed with g_free() when not needed any longer.
1939  *
1940  * See g_format_size_full() for more options about how the size might be
1941  * formatted.
1942  *
1943  * Returns: a newly-allocated formatted string containing a human readable
1944  *          file size.
1945  *
1946  * Since: 2.30
1947  **/
1948 gchar *
1949 g_format_size (guint64 size)
1950 {
1951   return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
1952 }
1953
1954 /**
1955  * g_format_size_full:
1956  * @size: a size in bytes
1957  * @flags: #GFormatSizeFlags to modify the output
1958  *
1959  * Formats a size.
1960  *
1961  * This function is similar to g_format_size() but allows for flags that
1962  * modify the output.  See #GFormatSizeFlags.
1963  *
1964  * Returns: a newly-allocated formatted string containing a human
1965  *          readable file size.
1966  *
1967  * Since: 2.30
1968  **/
1969 /**
1970  * GFormatSizeFlags:
1971  * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
1972  * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
1973  *                             of the returned string.  For example,
1974  *                             "45.6 kB (45,612 bytes)".
1975  * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
1976  *                           suffixes.  IEC units should only be used
1977  *                           for reporting things with a strong "power
1978  *                           of 2" basis, like RAM sizes or RAID stripe
1979  *                           sizes.  Network and storage sizes should
1980  *                           be reported in the normal SI units.
1981  *
1982  * Flags to modify the format of the string returned by
1983  * g_format_size_full().
1984  **/
1985 gchar *
1986 g_format_size_full (guint64          size,
1987                     GFormatSizeFlags flags)
1988 {
1989   GString *string;
1990
1991   string = g_string_new (NULL);
1992
1993   if (flags & G_FORMAT_SIZE_IEC_UNITS)
1994     {
1995       if (size < KIBIBYTE_FACTOR)
1996         {
1997           g_string_printf (string,
1998                            g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
1999                            (guint) size);
2000           flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2001         }
2002
2003       else if (size < MEBIBYTE_FACTOR)
2004         g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2005
2006       else if (size < GIBIBYTE_FACTOR)
2007         g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2008
2009       else if (size < TEBIBYTE_FACTOR)
2010         g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2011
2012       else if (size < PEBIBYTE_FACTOR)
2013         g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2014
2015       else if (size < EXBIBYTE_FACTOR)
2016         g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2017
2018       else
2019         g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2020     }
2021   else
2022     {
2023       if (size < KILOBYTE_FACTOR)
2024         {
2025           g_string_printf (string,
2026                            g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2027                            (guint) size);
2028           flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2029         }
2030
2031       else if (size < MEGABYTE_FACTOR)
2032         g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2033
2034       else if (size < GIGABYTE_FACTOR)
2035         g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2036
2037       else if (size < TERABYTE_FACTOR)
2038         g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2039
2040       else if (size < PETABYTE_FACTOR)
2041         g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2042
2043       else if (size < EXABYTE_FACTOR)
2044         g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2045
2046       else
2047         g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2048     }
2049
2050   if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2051     {
2052       /* First problem: we need to use the number of bytes to decide on
2053        * the plural form that is used for display, but the number of
2054        * bytes potentially exceeds the size of a guint (which is what
2055        * ngettext() takes).
2056        *
2057        * From a pragmatic standpoint, it seems that all known languages
2058        * base plural forms on one or both of the following:
2059        *
2060        *   - the lowest digits of the number
2061        *
2062        *   - if the number if greater than some small value
2063        *
2064        * Here's how we fake it:  Draw an arbitrary line at one thousand.
2065        * If the number is below that, then fine.  If it is above it,
2066        * then we take the modulus of the number by one thousand (in
2067        * order to keep the lowest digits) and add one thousand to that
2068        * (in order to ensure that 1001 is not treated the same as 1).
2069        */
2070       guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2071
2072       /* Second problem: we need to translate the string "%u byte" and
2073        * "%u bytes" for pluralisation, but the correct number format to
2074        * use for a gsize is different depending on which architecture
2075        * we're on.
2076        *
2077        * Solution: format the number separately and use "%s bytes" on
2078        * all platforms.
2079        */
2080       const gchar *translated_format;
2081       gchar *formatted_number;
2082
2083       /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2084       translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2085
2086       /* XXX: Windows doesn't support the "'" format modifier, so we
2087        * must not use it there.  Instead, just display the number
2088        * without separation.  Bug #655336 is open until a solution is
2089        * found.
2090        */
2091 #ifndef G_OS_WIN32
2092       formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2093 #else
2094       formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2095 #endif
2096
2097       g_string_append (string, " (");
2098       g_string_append_printf (string, translated_format, formatted_number);
2099       g_free (formatted_number);
2100       g_string_append (string, ")");
2101     }
2102
2103   return g_string_free (string, FALSE);
2104 }
2105
2106 /**
2107  * g_format_size_for_display:
2108  * @size: a size in bytes.
2109  * 
2110  * Formats a size (for example the size of a file) into a human readable string.
2111  * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed 
2112  * rounded to the nearest  tenth. E.g. the file size 3292528 bytes will be
2113  * converted into the string "3.1 MB".
2114  *
2115  * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2116  *
2117  * This string should be freed with g_free() when not needed any longer.
2118  *
2119  * Returns: a newly-allocated formatted string containing a human readable
2120  *          file size.
2121  *
2122  * Deprecated:2.30: This function is broken due to its use of SI
2123  *                  suffixes to denote IEC units.  Use g_format_size()
2124  *                  instead.
2125  * Since: 2.16
2126  **/
2127 char *
2128 g_format_size_for_display (goffset size)
2129 {
2130   if (size < (goffset) KIBIBYTE_FACTOR)
2131     return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2132   else
2133     {
2134       gdouble displayed_size;
2135       
2136       if (size < (goffset) MEBIBYTE_FACTOR)
2137         {
2138           displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2139           return g_strdup_printf (_("%.1f KB"), displayed_size);
2140         }
2141       else if (size < (goffset) GIBIBYTE_FACTOR)
2142         {
2143           displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2144           return g_strdup_printf (_("%.1f MB"), displayed_size);
2145         }
2146       else if (size < (goffset) TEBIBYTE_FACTOR)
2147         {
2148           displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2149           return g_strdup_printf (_("%.1f GB"), displayed_size);
2150         }
2151       else if (size < (goffset) PEBIBYTE_FACTOR)
2152         {
2153           displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2154           return g_strdup_printf (_("%.1f TB"), displayed_size);
2155         }
2156       else if (size < (goffset) EXBIBYTE_FACTOR)
2157         {
2158           displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2159           return g_strdup_printf (_("%.1f PB"), displayed_size);
2160         }
2161       else
2162         {
2163           displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2164           return g_strdup_printf (_("%.1f EB"), displayed_size);
2165         }
2166     }
2167 }
2168
2169
2170 /**
2171  * g_file_read_link:
2172  * @filename: the symbolic link
2173  * @error: return location for a #GError
2174  *
2175  * Reads the contents of the symbolic link @filename like the POSIX
2176  * readlink() function.  The returned string is in the encoding used
2177  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2178  *
2179  * Returns: A newly-allocated string with the contents of the symbolic link, 
2180  *          or %NULL if an error occurred.
2181  *
2182  * Since: 2.4
2183  */
2184 gchar *
2185 g_file_read_link (const gchar  *filename,
2186                   GError      **error)
2187 {
2188 #ifdef HAVE_READLINK
2189   gchar *buffer;
2190   guint size;
2191   gint read_size;    
2192   
2193   size = 256; 
2194   buffer = g_malloc (size);
2195   
2196   while (TRUE) 
2197     {
2198       read_size = readlink (filename, buffer, size);
2199       if (read_size < 0) {
2200         int save_errno = errno;
2201         gchar *display_filename = g_filename_display_name (filename);
2202
2203         g_free (buffer);
2204         g_set_error (error,
2205                      G_FILE_ERROR,
2206                      g_file_error_from_errno (save_errno),
2207                      _("Failed to read the symbolic link '%s': %s"),
2208                      display_filename, 
2209                      g_strerror (save_errno));
2210         g_free (display_filename);
2211         
2212         return NULL;
2213       }
2214     
2215       if (read_size < size) 
2216         {
2217           buffer[read_size] = 0;
2218           return buffer;
2219         }
2220       
2221       size *= 2;
2222       buffer = g_realloc (buffer, size);
2223     }
2224 #else
2225   g_set_error_literal (error,
2226                        G_FILE_ERROR,
2227                        G_FILE_ERROR_INVAL,
2228                        _("Symbolic links not supported"));
2229         
2230   return NULL;
2231 #endif
2232 }
2233
2234 /* NOTE : Keep this part last to ensure nothing in this file uses the
2235  * below binary compatibility versions.
2236  */
2237 #if defined (G_OS_WIN32) && !defined (_WIN64)
2238
2239 /* Binary compatibility versions. Will be called by code compiled
2240  * against quite old (pre-2.8, I think) headers only, not from more
2241  * recently compiled code.
2242  */
2243
2244 #undef g_file_test
2245
2246 gboolean
2247 g_file_test (const gchar *filename,
2248              GFileTest    test)
2249 {
2250   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
2251   gboolean retval;
2252
2253   if (utf8_filename == NULL)
2254     return FALSE;
2255
2256   retval = g_file_test_utf8 (utf8_filename, test);
2257
2258   g_free (utf8_filename);
2259
2260   return retval;
2261 }
2262
2263 #undef g_file_get_contents
2264
2265 gboolean
2266 g_file_get_contents (const gchar  *filename,
2267                      gchar       **contents,
2268                      gsize        *length,
2269                      GError      **error)
2270 {
2271   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2272   gboolean retval;
2273
2274   if (utf8_filename == NULL)
2275     return FALSE;
2276
2277   retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
2278
2279   g_free (utf8_filename);
2280
2281   return retval;
2282 }
2283
2284 #undef g_mkstemp
2285
2286 gint
2287 g_mkstemp (gchar *tmpl)
2288 {
2289   /* This is the backward compatibility system codepage version,
2290    * thus use normal open().
2291    */
2292   return get_tmp_file (tmpl, (GTmpFileCallback) open,
2293                        O_RDWR | O_CREAT | O_EXCL, 0600);
2294 }
2295
2296 #undef g_file_open_tmp
2297
2298 gint
2299 g_file_open_tmp (const gchar  *tmpl,
2300                  gchar       **name_used,
2301                  GError      **error)
2302 {
2303   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2304   gchar *utf8_name_used;
2305   gint retval;
2306
2307   if (utf8_tmpl == NULL)
2308     return -1;
2309
2310   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2311   
2312   if (retval == -1)
2313     return -1;
2314
2315   if (name_used)
2316     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2317
2318   g_free (utf8_name_used);
2319
2320   return retval;
2321 }
2322
2323 #endif