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