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