Coverage Report

Created: 2025-11-24 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/glib/glib/gfileutils.c
Line
Count
Source
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
0
#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
222
g_mkdir_with_parents (const gchar *pathname,
223
          int          mode)
224
0
{
225
0
  gchar *fn, *p;
226
227
0
  if (pathname == NULL || *pathname == '\0')
228
0
    {
229
0
      errno = EINVAL;
230
0
      return -1;
231
0
    }
232
233
  /* try to create the full path first */
234
0
  if (g_mkdir (pathname, mode) == 0)
235
0
    return 0;
236
0
  else if (errno == EEXIST)
237
0
    {
238
0
      if (!g_file_test (pathname, G_FILE_TEST_IS_DIR))
239
0
        {
240
0
          errno = ENOTDIR;
241
0
          return -1;
242
0
        }
243
0
      return 0;
244
0
    }
245
246
  /* walk the full path and try creating each element */
247
0
  fn = g_strdup (pathname);
248
249
0
  if (g_path_is_absolute (fn))
250
0
    p = (gchar *) g_path_skip_root (fn);
251
0
  else
252
0
    p = fn;
253
254
0
  do
255
0
    {
256
0
      while (*p && !G_IS_DIR_SEPARATOR (*p))
257
0
  p++;
258
      
259
0
      if (!*p)
260
0
  p = NULL;
261
0
      else
262
0
  *p = '\0';
263
      
264
0
      if (!g_file_test (fn, G_FILE_TEST_EXISTS))
265
0
  {
266
0
    if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
267
0
      {
268
0
        int errno_save = errno;
269
0
        if (errno != ENOENT || !p)
270
0
                {
271
0
            g_free (fn);
272
0
            errno = errno_save;
273
0
            return -1;
274
0
    }
275
0
      }
276
0
  }
277
0
      else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
278
0
  {
279
0
    g_free (fn);
280
0
    errno = ENOTDIR;
281
0
    return -1;
282
0
  }
283
0
      if (p)
284
0
  {
285
0
    *p++ = G_DIR_SEPARATOR;
286
0
    while (*p && G_IS_DIR_SEPARATOR (*p))
287
0
      p++;
288
0
  }
289
0
    }
290
0
  while (p);
291
292
0
  g_free (fn);
293
294
0
  return 0;
295
0
}
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
348
g_file_test (const gchar *filename,
349
             GFileTest    test)
350
0
{
351
#ifdef G_OS_WIN32
352
  int attributes;
353
  wchar_t *wfilename;
354
#endif
355
356
0
  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
0
  if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
447
0
    return TRUE;
448
  
449
0
  if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
450
0
    {
451
0
      if (getuid () != 0)
452
0
  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
0
    }
459
0
  else
460
0
    test &= ~G_FILE_TEST_IS_EXECUTABLE;
461
462
0
  if (test & G_FILE_TEST_IS_SYMLINK)
463
0
    {
464
0
      struct stat s;
465
466
0
      if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
467
0
        return TRUE;
468
0
    }
469
  
470
0
  if (test & (G_FILE_TEST_IS_REGULAR |
471
0
        G_FILE_TEST_IS_DIR |
472
0
        G_FILE_TEST_IS_EXECUTABLE))
473
0
    {
474
0
      struct stat s;
475
      
476
0
      if (stat (filename, &s) == 0)
477
0
  {
478
0
    if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
479
0
      return TRUE;
480
    
481
0
    if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
482
0
      return TRUE;
483
484
    /* The extra test for root when access (file, X_OK) succeeds.
485
     */
486
0
    if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
487
0
        ((s.st_mode & S_IXOTH) ||
488
0
         (s.st_mode & S_IXUSR) ||
489
0
         (s.st_mode & S_IXGRP)))
490
0
      return TRUE;
491
0
  }
492
0
    }
493
494
0
  return FALSE;
495
0
#endif
496
0
}
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
516
g_file_error_from_errno (gint err_no)
517
0
{
518
0
  switch (err_no)
519
0
    {
520
0
#ifdef EEXIST
521
0
    case EEXIST:
522
0
      return G_FILE_ERROR_EXIST;
523
0
#endif
524
525
0
#ifdef EISDIR
526
0
    case EISDIR:
527
0
      return G_FILE_ERROR_ISDIR;
528
0
#endif
529
530
0
#ifdef EACCES
531
0
    case EACCES:
532
0
      return G_FILE_ERROR_ACCES;
533
0
#endif
534
535
0
#ifdef ENAMETOOLONG
536
0
    case ENAMETOOLONG:
537
0
      return G_FILE_ERROR_NAMETOOLONG;
538
0
#endif
539
540
0
#ifdef ENOENT
541
0
    case ENOENT:
542
0
      return G_FILE_ERROR_NOENT;
543
0
#endif
544
545
0
#ifdef ENOTDIR
546
0
    case ENOTDIR:
547
0
      return G_FILE_ERROR_NOTDIR;
548
0
#endif
549
550
0
#ifdef ENXIO
551
0
    case ENXIO:
552
0
      return G_FILE_ERROR_NXIO;
553
0
#endif
554
555
0
#ifdef ENODEV
556
0
    case ENODEV:
557
0
      return G_FILE_ERROR_NODEV;
558
0
#endif
559
560
0
#ifdef EROFS
561
0
    case EROFS:
562
0
      return G_FILE_ERROR_ROFS;
563
0
#endif
564
565
0
#ifdef ETXTBSY
566
0
    case ETXTBSY:
567
0
      return G_FILE_ERROR_TXTBSY;
568
0
#endif
569
570
0
#ifdef EFAULT
571
0
    case EFAULT:
572
0
      return G_FILE_ERROR_FAULT;
573
0
#endif
574
575
0
#ifdef ELOOP
576
0
    case ELOOP:
577
0
      return G_FILE_ERROR_LOOP;
578
0
#endif
579
580
0
#ifdef ENOSPC
581
0
    case ENOSPC:
582
0
      return G_FILE_ERROR_NOSPC;
583
0
#endif
584
585
0
#ifdef ENOMEM
586
0
    case ENOMEM:
587
0
      return G_FILE_ERROR_NOMEM;
588
0
#endif
589
590
0
#ifdef EMFILE
591
0
    case EMFILE:
592
0
      return G_FILE_ERROR_MFILE;
593
0
#endif
594
595
0
#ifdef ENFILE
596
0
    case ENFILE:
597
0
      return G_FILE_ERROR_NFILE;
598
0
#endif
599
600
0
#ifdef EBADF
601
0
    case EBADF:
602
0
      return G_FILE_ERROR_BADF;
603
0
#endif
604
605
0
#ifdef EINVAL
606
0
    case EINVAL:
607
0
      return G_FILE_ERROR_INVAL;
608
0
#endif
609
610
0
#ifdef EPIPE
611
0
    case EPIPE:
612
0
      return G_FILE_ERROR_PIPE;
613
0
#endif
614
615
0
#ifdef EAGAIN
616
0
    case EAGAIN:
617
0
      return G_FILE_ERROR_AGAIN;
618
0
#endif
619
620
0
#ifdef EINTR
621
0
    case EINTR:
622
0
      return G_FILE_ERROR_INTR;
623
0
#endif
624
625
0
#ifdef EIO
626
0
    case EIO:
627
0
      return G_FILE_ERROR_IO;
628
0
#endif
629
630
0
#ifdef EPERM
631
0
    case EPERM:
632
0
      return G_FILE_ERROR_PERM;
633
0
#endif
634
635
0
#ifdef ENOSYS
636
0
    case ENOSYS:
637
0
      return G_FILE_ERROR_NOSYS;
638
0
#endif
639
640
0
    default:
641
0
      return G_FILE_ERROR_FAILED;
642
0
    }
643
0
}
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 *
654
format_error_message (const gchar  *filename,
655
                      const gchar  *format_string,
656
                      int           saved_errno)
657
0
{
658
0
  gchar *display_name;
659
0
  gchar *msg;
660
661
0
  display_name = g_filename_display_name (filename);
662
0
  msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
663
0
  g_free (display_name);
664
665
0
  return msg;
666
0
}
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
676
set_file_error (GError      **error,
677
                const gchar  *filename,
678
                const gchar  *format_string,
679
                int           saved_errno)
680
0
{
681
0
  char *msg = format_error_message (filename, format_string, saved_errno);
682
683
0
  g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
684
0
                       msg);
685
0
  g_free (msg);
686
0
}
687
688
static gboolean
689
get_contents_stdio (const gchar  *filename,
690
                    FILE         *f,
691
                    gchar       **contents,
692
                    gsize        *length,
693
                    GError      **error)
694
0
{
695
0
  gchar buf[4096];
696
0
  gsize bytes;  /* always <= sizeof(buf) */
697
0
  gchar *str = NULL;
698
0
  gsize total_bytes = 0;
699
0
  gsize total_allocated = 0;
700
0
  gchar *tmp;
701
0
  gchar *display_filename;
702
703
0
  g_assert (f != NULL);
704
705
0
  while (!feof (f))
706
0
    {
707
0
      gint save_errno;
708
709
0
      bytes = fread (buf, 1, sizeof (buf), f);
710
0
      save_errno = errno;
711
712
0
      if (total_bytes > G_MAXSIZE - bytes)
713
0
          goto file_too_large;
714
715
      /* Possibility of overflow eliminated above. */
716
0
      while (total_bytes + bytes >= total_allocated)
717
0
        {
718
0
          if (str)
719
0
            {
720
0
              if (total_allocated > G_MAXSIZE / 2)
721
0
                  goto file_too_large;
722
0
              total_allocated *= 2;
723
0
            }
724
0
          else
725
0
            {
726
0
              total_allocated = MIN (bytes + 1, sizeof (buf));
727
0
            }
728
729
0
          tmp = g_try_realloc (str, total_allocated);
730
731
0
          if (tmp == NULL)
732
0
            {
733
0
              display_filename = g_filename_display_name (filename);
734
0
              g_set_error (error,
735
0
                           G_FILE_ERROR,
736
0
                           G_FILE_ERROR_NOMEM,
737
0
                           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
0
                           (gulong) total_allocated,
739
0
         display_filename);
740
0
              g_free (display_filename);
741
742
0
              goto error;
743
0
            }
744
745
0
    str = tmp;
746
0
        }
747
748
0
      if (ferror (f))
749
0
        {
750
0
          display_filename = g_filename_display_name (filename);
751
0
          g_set_error (error,
752
0
                       G_FILE_ERROR,
753
0
                       g_file_error_from_errno (save_errno),
754
0
                       _("Error reading file “%s”: %s"),
755
0
                       display_filename,
756
0
           g_strerror (save_errno));
757
0
          g_free (display_filename);
758
759
0
          goto error;
760
0
        }
761
762
0
      g_assert (str != NULL);
763
0
      memcpy (str + total_bytes, buf, bytes);
764
765
0
      total_bytes += bytes;
766
0
    }
767
768
0
  fclose (f);
769
770
0
  if (total_allocated == 0)
771
0
    {
772
0
      str = g_new (gchar, 1);
773
0
      total_bytes = 0;
774
0
    }
775
776
0
  str[total_bytes] = '\0';
777
778
0
  if (length)
779
0
    *length = total_bytes;
780
781
0
  *contents = str;
782
783
0
  return TRUE;
784
785
0
 file_too_large:
786
0
  display_filename = g_filename_display_name (filename);
787
0
  g_set_error (error,
788
0
               G_FILE_ERROR,
789
0
               G_FILE_ERROR_FAILED,
790
0
               _("File “%s” is too large"),
791
0
               display_filename);
792
0
  g_free (display_filename);
793
794
0
 error:
795
796
0
  g_free (str);
797
0
  fclose (f);
798
799
0
  return FALSE;
800
0
}
801
802
#ifndef G_OS_WIN32
803
804
static gboolean
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
0
{
812
0
  gchar *buf;
813
0
  gsize bytes_read;
814
0
  gsize size;
815
0
  gsize alloc_size;
816
0
  gchar *display_filename;
817
  
818
0
  size = stat_buf->st_size;
819
820
0
  alloc_size = size + 1;
821
0
  buf = g_try_malloc (alloc_size);
822
823
0
  if (buf == NULL)
824
0
    {
825
0
      display_filename = g_filename_display_name (filename);
826
0
      g_set_error (error,
827
0
                   G_FILE_ERROR,
828
0
                   G_FILE_ERROR_NOMEM,
829
0
                           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
0
                   (gulong) alloc_size, 
831
0
       display_filename);
832
0
      g_free (display_filename);
833
0
      goto error;
834
0
    }
835
  
836
0
  bytes_read = 0;
837
0
  while (bytes_read < size)
838
0
    {
839
0
      gssize rc;
840
          
841
0
      rc = read (fd, buf + bytes_read, size - bytes_read);
842
843
0
      if (rc < 0)
844
0
        {
845
0
          if (errno != EINTR) 
846
0
            {
847
0
        int save_errno = errno;
848
849
0
              g_free (buf);
850
0
              display_filename = g_filename_display_name (filename);
851
0
              g_set_error (error,
852
0
                           G_FILE_ERROR,
853
0
                           g_file_error_from_errno (save_errno),
854
0
                           _("Failed to read from file “%s”: %s"),
855
0
                           display_filename, 
856
0
         g_strerror (save_errno));
857
0
              g_free (display_filename);
858
0
        goto error;
859
0
            }
860
0
        }
861
0
      else if (rc == 0)
862
0
        break;
863
0
      else
864
0
        bytes_read += rc;
865
0
    }
866
      
867
0
  buf[bytes_read] = '\0';
868
869
0
  if (length)
870
0
    *length = bytes_read;
871
  
872
0
  *contents = buf;
873
874
0
  close (fd);
875
876
0
  return TRUE;
877
878
0
 error:
879
880
0
  close (fd);
881
  
882
0
  return FALSE;
883
0
}
884
885
static gboolean
886
get_contents_posix (const gchar  *filename,
887
                    gchar       **contents,
888
                    gsize        *length,
889
                    GError      **error)
890
0
{
891
0
  struct stat stat_buf;
892
0
  gint fd;
893
894
  /* O_BINARY useful on Cygwin */
895
0
  fd = open (filename, O_RDONLY|O_BINARY);
896
897
0
  if (fd < 0)
898
0
    {
899
0
      int saved_errno = errno;
900
901
0
      if (error)
902
0
        set_file_error (error,
903
0
                        filename,
904
0
                        _("Failed to open file “%s”: %s"),
905
0
                        saved_errno);
906
907
0
      return FALSE;
908
0
    }
909
910
  /* I don't think this will ever fail, aside from ENOMEM, but. */
911
0
  if (fstat (fd, &stat_buf) < 0)
912
0
    {
913
0
      int saved_errno = errno;
914
0
      if (error)
915
0
        set_file_error (error,
916
0
                        filename,
917
0
                        _("Failed to get attributes of file “%s”: fstat() failed: %s"),
918
0
                        saved_errno);
919
0
      close (fd);
920
921
0
      return FALSE;
922
0
    }
923
924
0
  if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
925
0
    {
926
0
      gboolean retval = get_contents_regfile (filename,
927
0
                &stat_buf,
928
0
                fd,
929
0
                contents,
930
0
                length,
931
0
                error);
932
933
0
      return retval;
934
0
    }
935
0
  else
936
0
    {
937
0
      FILE *f;
938
0
      gboolean retval;
939
940
0
      f = fdopen (fd, "r");
941
      
942
0
      if (f == NULL)
943
0
        {
944
0
          int saved_errno = errno;
945
0
          if (error)
946
0
            set_file_error (error,
947
0
                            filename,
948
0
                            _("Failed to open file “%s”: fdopen() failed: %s"),
949
0
                            saved_errno);
950
951
0
          return FALSE;
952
0
        }
953
  
954
0
      retval = get_contents_stdio (filename, f, contents, length, error);
955
956
0
      return retval;
957
0
    }
958
0
}
959
960
#else  /* G_OS_WIN32 */
961
962
static gboolean
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
1014
g_file_get_contents (const gchar  *filename,
1015
                     gchar       **contents,
1016
                     gsize        *length,
1017
                     GError      **error)
1018
0
{  
1019
0
  g_return_val_if_fail (filename != NULL, FALSE);
1020
0
  g_return_val_if_fail (contents != NULL, FALSE);
1021
1022
0
  *contents = NULL;
1023
0
  if (length)
1024
0
    *length = 0;
1025
1026
#ifdef G_OS_WIN32
1027
  return get_contents_win32 (filename, contents, length, error);
1028
#else
1029
0
  return get_contents_posix (filename, contents, length, error);
1030
0
#endif
1031
0
}
1032
1033
static gboolean
1034
rename_file (const char  *old_name,
1035
             const char  *new_name,
1036
             gboolean     do_fsync,
1037
             GError     **err)
1038
0
{
1039
0
  errno = 0;
1040
0
  if (g_rename (old_name, new_name) == -1)
1041
0
    {
1042
0
      int save_errno = errno;
1043
0
      gchar *display_old_name = g_filename_display_name (old_name);
1044
0
      gchar *display_new_name = g_filename_display_name (new_name);
1045
1046
0
      g_set_error (err,
1047
0
       G_FILE_ERROR,
1048
0
       g_file_error_from_errno (save_errno),
1049
0
       _("Failed to rename file “%s” to “%s”: g_rename() failed: %s"),
1050
0
       display_old_name,
1051
0
       display_new_name,
1052
0
       g_strerror (save_errno));
1053
1054
0
      g_free (display_old_name);
1055
0
      g_free (display_new_name);
1056
      
1057
0
      return FALSE;
1058
0
    }
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
0
#ifdef HAVE_FSYNC
1067
0
  if (do_fsync)
1068
0
    {
1069
0
      gchar *dir = g_path_get_dirname (new_name);
1070
0
      int dir_fd = g_open (dir, O_RDONLY, 0);
1071
1072
0
      if (dir_fd >= 0)
1073
0
        {
1074
0
          g_fsync (dir_fd);
1075
0
          g_close (dir_fd, NULL);
1076
0
        }
1077
1078
0
      g_free (dir);
1079
0
    }
1080
0
#endif  /* HAVE_FSYNC */
1081
1082
0
  return TRUE;
1083
0
}
1084
1085
static gboolean
1086
fd_should_be_fsynced (int                    fd,
1087
                      const gchar           *test_file,
1088
                      GFileSetContentsFlags  flags)
1089
0
{
1090
0
#ifdef HAVE_FSYNC
1091
0
  struct stat statbuf;
1092
1093
0
#ifdef BTRFS_SUPER_MAGIC
1094
0
  {
1095
0
    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
0
    if ((flags & G_FILE_SET_CONTENTS_CONSISTENT) &&
1105
0
        fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
1106
0
      return FALSE;
1107
0
  }
1108
0
#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
0
  if ((flags & (G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE)) &&
1124
0
      (flags & G_FILE_SET_CONTENTS_ONLY_EXISTING))
1125
0
    {
1126
0
      errno = 0;
1127
0
      if (g_lstat (test_file, &statbuf) == 0)
1128
0
        return (statbuf.st_size > 0);
1129
0
      else if (errno == ENOENT)
1130
0
        return FALSE;
1131
0
      else
1132
0
        return TRUE;  /* lstat() failed; be cautious */
1133
0
    }
1134
0
  else
1135
0
    {
1136
0
      return (flags & (G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE));
1137
0
    }
1138
#else  /* if !HAVE_FSYNC */
1139
  return FALSE;
1140
#endif  /* !HAVE_FSYNC */
1141
0
}
1142
1143
/* closes @fd once it’s finished (on success or error) */
1144
static gboolean
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
0
{
1152
0
#ifdef HAVE_FALLOCATE
1153
0
  if (length > 0)
1154
0
    {
1155
      /* We do this on a 'best effort' basis... It may not be supported
1156
       * on the underlying filesystem.
1157
       */
1158
0
      (void) fallocate (fd, 0, 0, length);
1159
0
    }
1160
0
#endif
1161
0
  while (length > 0)
1162
0
    {
1163
0
      gssize s;
1164
1165
0
      s = write (fd, contents, MIN (length, G_MAXSSIZE));
1166
1167
0
      if (s < 0)
1168
0
        {
1169
0
          int saved_errno = errno;
1170
0
          if (saved_errno == EINTR)
1171
0
            continue;
1172
1173
0
          if (err)
1174
0
            set_file_error (err,
1175
0
                            dest_file, _("Failed to write file “%s”: write() failed: %s"),
1176
0
                            saved_errno);
1177
0
          close (fd);
1178
1179
0
          return FALSE;
1180
0
        }
1181
1182
0
      g_assert ((gsize) s <= length);
1183
1184
0
      contents += s;
1185
0
      length -= s;
1186
0
    }
1187
1188
1189
0
#ifdef HAVE_FSYNC
1190
0
  errno = 0;
1191
0
  if (do_fsync && g_fsync (fd) != 0)
1192
0
    {
1193
0
      int saved_errno = errno;
1194
0
      if (err)
1195
0
        set_file_error (err,
1196
0
                        dest_file, _("Failed to write file “%s”: fsync() failed: %s"),
1197
0
                        saved_errno);
1198
0
      close (fd);
1199
1200
0
      return FALSE;
1201
0
    }
1202
0
#endif
1203
1204
0
  errno = 0;
1205
0
  if (!g_close (fd, err))
1206
0
    return FALSE;
1207
1208
0
  return TRUE;
1209
0
}
1210
1211
static inline int
1212
steal_fd (int *fd_ptr)
1213
0
{
1214
0
  int fd = *fd_ptr;
1215
0
  *fd_ptr = -1;
1216
0
  return fd;
1217
0
}
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
1237
g_file_set_contents (const gchar  *filename,
1238
                     const gchar  *contents,
1239
                     gssize        length,
1240
                     GError      **error)
1241
0
{
1242
0
  return g_file_set_contents_full (filename, contents, length,
1243
0
                                   G_FILE_SET_CONTENTS_CONSISTENT |
1244
0
                                   G_FILE_SET_CONTENTS_ONLY_EXISTING,
1245
0
                                   0666, error);
1246
0
}
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
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
0
{
1325
0
  g_return_val_if_fail (filename != NULL, FALSE);
1326
0
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1327
0
  g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1328
0
  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
0
  if (length < 0)
1345
0
    length = strlen (contents);
1346
1347
0
  if (flags & G_FILE_SET_CONTENTS_CONSISTENT)
1348
0
    {
1349
0
      gchar *tmp_filename = NULL;
1350
0
      GError *rename_error = NULL;
1351
0
      gboolean retval;
1352
0
      int fd;
1353
0
      gboolean do_fsync;
1354
1355
0
      tmp_filename = g_strdup_printf ("%s.XXXXXX", filename);
1356
1357
0
      errno = 0;
1358
0
      fd = g_mkstemp_full (tmp_filename, O_RDWR | O_BINARY, mode);
1359
1360
0
      if (fd == -1)
1361
0
        {
1362
0
          int saved_errno = errno;
1363
0
          if (error)
1364
0
            set_file_error (error,
1365
0
                            tmp_filename, _("Failed to create file “%s”: %s"),
1366
0
                            saved_errno);
1367
0
          retval = FALSE;
1368
0
          goto consistent_out;
1369
0
        }
1370
1371
0
      do_fsync = fd_should_be_fsynced (fd, filename, flags);
1372
0
      if (!write_to_file (contents, length, steal_fd (&fd), tmp_filename, do_fsync, error))
1373
0
        {
1374
0
          g_unlink (tmp_filename);
1375
0
          retval = FALSE;
1376
0
          goto consistent_out;
1377
0
        }
1378
1379
0
      if (!rename_file (tmp_filename, filename, do_fsync, &rename_error))
1380
0
        {
1381
0
#ifndef G_OS_WIN32
1382
1383
0
          g_unlink (tmp_filename);
1384
0
          g_propagate_error (error, rename_error);
1385
0
          retval = FALSE;
1386
0
          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
0
        }
1426
1427
0
      retval = TRUE;
1428
1429
0
consistent_out:
1430
0
      g_free (tmp_filename);
1431
0
      return retval;
1432
0
    }
1433
0
  else
1434
0
    {
1435
0
      int direct_fd;
1436
0
      int open_flags;
1437
0
      gboolean do_fsync;
1438
1439
0
      open_flags = O_RDWR | O_BINARY | O_CREAT | O_CLOEXEC;
1440
0
#ifdef O_NOFOLLOW
1441
      /* Windows doesn’t have symlinks, so O_NOFOLLOW is unnecessary there. */
1442
0
      open_flags |= O_NOFOLLOW;
1443
0
#endif
1444
1445
0
      errno = 0;
1446
0
      direct_fd = g_open (filename, open_flags, mode);
1447
1448
0
      if (direct_fd < 0)
1449
0
        {
1450
0
          int saved_errno = errno;
1451
1452
0
#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
0
          if (saved_errno == ELOOP)
1468
0
#endif
1469
0
            return g_file_set_contents_full (filename, contents, length,
1470
0
                                             flags | G_FILE_SET_CONTENTS_CONSISTENT,
1471
0
                                             mode, error);
1472
0
#endif  /* O_NOFOLLOW */
1473
1474
0
          if (error)
1475
0
            set_file_error (error,
1476
0
                            filename, _("Failed to open file “%s”: %s"),
1477
0
                            saved_errno);
1478
0
          return FALSE;
1479
0
        }
1480
1481
0
      do_fsync = fd_should_be_fsynced (direct_fd, filename, flags);
1482
0
      if (!write_to_file (contents, length, steal_fd (&direct_fd), filename,
1483
0
                          do_fsync, error))
1484
0
        return FALSE;
1485
0
    }
1486
1487
0
  return TRUE;
1488
0
}
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
1497
get_tmp_file (gchar            *tmpl,
1498
              GTmpFileCallback  f,
1499
              int               flags,
1500
              int               mode)
1501
0
{
1502
0
  char *XXXXXX;
1503
0
  int count, fd;
1504
0
  static const char letters[] =
1505
0
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1506
0
  static const int NLETTERS = sizeof (letters) - 1;
1507
0
  glong value;
1508
0
  gint64 now_us;
1509
0
  static int counter = 0;
1510
1511
0
  g_return_val_if_fail (tmpl != NULL, -1);
1512
1513
  /* find the last occurrence of "XXXXXX" */
1514
0
  XXXXXX = g_strrstr (tmpl, "XXXXXX");
1515
1516
0
  if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1517
0
    {
1518
0
      errno = EINVAL;
1519
0
      return -1;
1520
0
    }
1521
1522
  /* Get some more or less random data.  */
1523
0
  now_us = g_get_real_time ();
1524
0
  value = ((now_us % G_USEC_PER_SEC) ^ (now_us / G_USEC_PER_SEC)) + counter++;
1525
1526
0
  for (count = 0; count < 100; value += 7777, ++count)
1527
0
    {
1528
0
      glong v = value;
1529
1530
      /* Fill in the random bits.  */
1531
0
      XXXXXX[0] = letters[v % NLETTERS];
1532
0
      v /= NLETTERS;
1533
0
      XXXXXX[1] = letters[v % NLETTERS];
1534
0
      v /= NLETTERS;
1535
0
      XXXXXX[2] = letters[v % NLETTERS];
1536
0
      v /= NLETTERS;
1537
0
      XXXXXX[3] = letters[v % NLETTERS];
1538
0
      v /= NLETTERS;
1539
0
      XXXXXX[4] = letters[v % NLETTERS];
1540
0
      v /= NLETTERS;
1541
0
      XXXXXX[5] = letters[v % NLETTERS];
1542
1543
0
      fd = f (tmpl, flags, mode);
1544
1545
0
      if (fd >= 0)
1546
0
        return fd;
1547
0
      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
0
        return -1;
1552
0
    }
1553
1554
  /* We got out of the loop because we ran out of combinations to try.  */
1555
0
  errno = EEXIST;
1556
0
  return -1;
1557
0
}
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
1566
wrap_g_mkdir (const gchar *filename,
1567
              int          flags G_GNUC_UNUSED,
1568
              int          mode)
1569
0
{
1570
  /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1571
0
  return g_mkdir (filename, mode);
1572
0
}
1573
1574
static gint
1575
wrap_g_open (const gchar *filename,
1576
                int          flags,
1577
                int          mode)
1578
0
{
1579
0
  return g_open (filename, flags, mode);
1580
0
}
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 *
1610
g_mkdtemp_full (gchar *tmpl,
1611
                gint   mode)
1612
0
{
1613
0
  if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1614
0
    return NULL;
1615
0
  else
1616
0
    return tmpl;
1617
0
}
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 *
1646
g_mkdtemp (gchar *tmpl)
1647
0
{
1648
0
  return g_mkdtemp_full (tmpl, 0700);
1649
0
}
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
1678
g_mkstemp_full (gchar *tmpl,
1679
                gint   flags,
1680
                gint   mode)
1681
0
{
1682
  /* tmpl is in UTF-8 on Windows, thus use g_open() */
1683
0
  return get_tmp_file (tmpl, wrap_g_open,
1684
0
                       flags | O_CREAT | O_EXCL, mode);
1685
0
}
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
1709
g_mkstemp (gchar *tmpl)
1710
0
{
1711
0
  return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1712
0
}
1713
1714
static gint
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
0
{
1722
0
  int retval;
1723
0
  const char *tmpdir;
1724
0
  const char *sep;
1725
0
  char *fulltemplate;
1726
0
  const char *slash;
1727
1728
0
  if (tmpl == NULL)
1729
0
    tmpl = ".XXXXXX";
1730
1731
0
  if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1732
#ifdef G_OS_WIN32
1733
      || (strchr (tmpl, '/') != NULL && (slash = "/"))
1734
#endif
1735
0
      )
1736
0
    {
1737
0
      gchar *display_tmpl = g_filename_display_name (tmpl);
1738
0
      char c[2];
1739
0
      c[0] = *slash;
1740
0
      c[1] = '\0';
1741
1742
0
      g_set_error (error,
1743
0
                   G_FILE_ERROR,
1744
0
                   G_FILE_ERROR_FAILED,
1745
0
                   _("Template “%s” invalid, should not contain a “%s”"),
1746
0
                   display_tmpl, c);
1747
0
      g_free (display_tmpl);
1748
1749
0
      return -1;
1750
0
    }
1751
1752
0
  if (strstr (tmpl, "XXXXXX") == NULL)
1753
0
    {
1754
0
      gchar *display_tmpl = g_filename_display_name (tmpl);
1755
0
      g_set_error (error,
1756
0
                   G_FILE_ERROR,
1757
0
                   G_FILE_ERROR_FAILED,
1758
0
                   _("Template “%s” doesn’t contain XXXXXX"),
1759
0
                   display_tmpl);
1760
0
      g_free (display_tmpl);
1761
0
      return -1;
1762
0
    }
1763
1764
0
  tmpdir = g_get_tmp_dir ();
1765
1766
0
  if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1767
0
    sep = "";
1768
0
  else
1769
0
    sep = G_DIR_SEPARATOR_S;
1770
1771
0
  fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1772
1773
0
  retval = get_tmp_file (fulltemplate, f, flags, mode);
1774
0
  if (retval == -1)
1775
0
    {
1776
0
      int saved_errno = errno;
1777
0
      if (error)
1778
0
        set_file_error (error,
1779
0
                        fulltemplate,
1780
0
                        _("Failed to create file “%s”: %s"),
1781
0
                        saved_errno);
1782
0
      g_free (fulltemplate);
1783
0
      return -1;
1784
0
    }
1785
1786
0
  *name_used = fulltemplate;
1787
1788
0
  return retval;
1789
0
}
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
1822
g_file_open_tmp (const gchar  *tmpl,
1823
                 gchar       **name_used,
1824
                 GError      **error)
1825
0
{
1826
0
  gchar *fulltemplate;
1827
0
  gint result;
1828
1829
0
  g_return_val_if_fail (error == NULL || *error == NULL, -1);
1830
1831
0
  result = g_get_tmp_name (tmpl, &fulltemplate,
1832
0
                           wrap_g_open,
1833
0
                           O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1834
0
                           0600,
1835
0
                           error);
1836
0
  if (result != -1)
1837
0
    {
1838
0
      if (name_used)
1839
0
        *name_used = fulltemplate;
1840
0
      else
1841
0
        g_free (fulltemplate);
1842
0
    }
1843
1844
0
  return result;
1845
0
}
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 *
1873
g_dir_make_tmp (const gchar  *tmpl,
1874
                GError      **error)
1875
0
{
1876
0
  gchar *fulltemplate;
1877
1878
0
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1879
1880
0
  if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1881
0
    return NULL;
1882
0
  else
1883
0
    return fulltemplate;
1884
0
}
1885
1886
static gchar *
1887
g_build_path_va (const gchar  *separator,
1888
     const gchar  *first_element,
1889
     va_list      *args,
1890
     gchar       **str_array)
1891
0
{
1892
0
  GString *result;
1893
0
  gint separator_len = strlen (separator);
1894
0
  gboolean is_first = TRUE;
1895
0
  gboolean have_leading = FALSE;
1896
0
  const gchar *single_element = NULL;
1897
0
  const gchar *next_element;
1898
0
  const gchar *last_trailing = NULL;
1899
0
  gint i = 0;
1900
1901
0
  result = g_string_new (NULL);
1902
1903
0
  if (str_array)
1904
0
    next_element = str_array[i++];
1905
0
  else
1906
0
    next_element = first_element;
1907
1908
0
  while (TRUE)
1909
0
    {
1910
0
      const gchar *element;
1911
0
      const gchar *start;
1912
0
      const gchar *end;
1913
1914
0
      if (next_element)
1915
0
  {
1916
0
    element = next_element;
1917
0
    if (str_array)
1918
0
      next_element = str_array[i++];
1919
0
    else
1920
0
      next_element = va_arg (*args, gchar *);
1921
0
  }
1922
0
      else
1923
0
  break;
1924
1925
      /* Ignore empty elements */
1926
0
      if (!*element)
1927
0
  continue;
1928
      
1929
0
      start = element;
1930
1931
0
      if (separator_len)
1932
0
  {
1933
0
    while (strncmp (start, separator, separator_len) == 0)
1934
0
      start += separator_len;
1935
0
        }
1936
1937
0
      end = start + strlen (start);
1938
      
1939
0
      if (separator_len)
1940
0
  {
1941
0
    while (end >= start + separator_len &&
1942
0
     strncmp (end - separator_len, separator, separator_len) == 0)
1943
0
      end -= separator_len;
1944
    
1945
0
    last_trailing = end;
1946
0
    while (last_trailing >= element + separator_len &&
1947
0
     strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1948
0
      last_trailing -= separator_len;
1949
1950
0
    if (!have_leading)
1951
0
      {
1952
        /* If the leading and trailing separator strings are in the
1953
         * same element and overlap, the result is exactly that element
1954
         */
1955
0
        if (last_trailing <= start)
1956
0
    single_element = element;
1957
      
1958
0
        g_string_append_len (result, element, start - element);
1959
0
        have_leading = TRUE;
1960
0
      }
1961
0
    else
1962
0
      single_element = NULL;
1963
0
  }
1964
1965
0
      if (end == start)
1966
0
  continue;
1967
1968
0
      if (!is_first)
1969
0
  g_string_append (result, separator);
1970
      
1971
0
      g_string_append_len (result, start, end - start);
1972
0
      is_first = FALSE;
1973
0
    }
1974
1975
0
  if (single_element)
1976
0
    {
1977
0
      g_string_free (result, TRUE);
1978
0
      return g_strdup (single_element);
1979
0
    }
1980
0
  else
1981
0
    {
1982
0
      if (last_trailing)
1983
0
  g_string_append (result, last_trailing);
1984
  
1985
0
      return g_string_free (result, FALSE);
1986
0
    }
1987
0
}
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 *
2005
g_build_pathv (const gchar  *separator,
2006
         gchar       **args)
2007
0
{
2008
0
  if (!args)
2009
0
    return NULL;
2010
2011
0
  return g_build_path_va (separator, NULL, NULL, args);
2012
0
}
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 *
2052
g_build_path (const gchar *separator,
2053
        const gchar *first_element,
2054
        ...)
2055
0
{
2056
0
  gchar *str;
2057
0
  va_list args;
2058
2059
0
  g_return_val_if_fail (separator != NULL, NULL);
2060
2061
0
  va_start (args, first_element);
2062
0
  str = g_build_path_va (separator, first_element, &args, NULL);
2063
0
  va_end (args);
2064
2065
0
  return str;
2066
0
}
2067
2068
#ifdef G_OS_WIN32
2069
2070
static gchar *
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 *
2185
g_build_filename_va (const gchar  *first_argument,
2186
                     va_list      *args,
2187
                     gchar       **str_array)
2188
0
{
2189
0
  gchar *str;
2190
2191
0
#ifndef G_OS_WIN32
2192
0
  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
0
  return str;
2198
0
}
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 *
2214
g_build_filename_valist (const gchar  *first_element,
2215
                         va_list      *args)
2216
0
{
2217
0
  g_return_val_if_fail (first_element != NULL, NULL);
2218
2219
0
  return g_build_filename_va (first_element, args, NULL);
2220
0
}
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 *
2237
g_build_filenamev (gchar **args)
2238
0
{
2239
0
  return g_build_filename_va (NULL, NULL, args);
2240
0
}
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 *
2267
g_build_filename (const gchar *first_element, 
2268
      ...)
2269
0
{
2270
0
  gchar *str;
2271
0
  va_list args;
2272
2273
0
  va_start (args, first_element);
2274
0
  str = g_build_filename_va (first_element, &args, NULL);
2275
0
  va_end (args);
2276
2277
0
  return str;
2278
0
}
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 *
2295
g_file_read_link (const gchar  *filename,
2296
            GError      **error)
2297
0
{
2298
0
#if defined (HAVE_READLINK)
2299
0
  gchar *buffer;
2300
0
  size_t size;
2301
0
  gssize read_size;
2302
  
2303
0
  g_return_val_if_fail (filename != NULL, NULL);
2304
0
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2305
2306
0
  size = 256;
2307
0
  buffer = g_malloc (size);
2308
  
2309
0
  while (TRUE) 
2310
0
    {
2311
0
      read_size = readlink (filename, buffer, size);
2312
0
      if (read_size < 0)
2313
0
        {
2314
0
          int saved_errno = errno;
2315
0
          if (error)
2316
0
            set_file_error (error,
2317
0
                            filename,
2318
0
                            _("Failed to read the symbolic link “%s”: %s"),
2319
0
                            saved_errno);
2320
0
          g_free (buffer);
2321
0
          return NULL;
2322
0
        }
2323
    
2324
0
      if ((size_t) read_size < size)
2325
0
        {
2326
0
          buffer[read_size] = 0;
2327
0
          return buffer;
2328
0
        }
2329
      
2330
0
      size *= 2;
2331
0
      buffer = g_realloc (buffer, size);
2332
0
    }
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
0
}
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
2400
g_path_is_absolute (const gchar *file_name)
2401
0
{
2402
0
  g_return_val_if_fail (file_name != NULL, FALSE);
2403
2404
0
  if (G_IS_DIR_SEPARATOR (file_name[0]))
2405
0
    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
0
  return FALSE;
2415
0
}
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 *
2429
g_path_skip_root (const gchar *file_name)
2430
0
{
2431
0
  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
0
  if (G_IS_DIR_SEPARATOR (file_name[0]))
2471
0
    {
2472
0
      while (G_IS_DIR_SEPARATOR (file_name[0]))
2473
0
        file_name++;
2474
0
      return (gchar *)file_name;
2475
0
    }
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
0
  return NULL;
2486
0
}
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 *
2505
g_basename (const gchar *file_name)
2506
0
{
2507
0
  gchar *base;
2508
2509
0
  g_return_val_if_fail (file_name != NULL, NULL);
2510
2511
0
  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
0
  if (base)
2523
0
    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
0
  return (gchar*) file_name;
2531
0
}
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 *
2548
g_path_get_basename (const gchar *file_name)
2549
0
{
2550
0
  gssize base;
2551
0
  gssize last_nonslash;
2552
0
  gsize len;
2553
0
  gchar *retval;
2554
2555
0
  g_return_val_if_fail (file_name != NULL, NULL);
2556
2557
0
  if (file_name[0] == '\0')
2558
0
    return g_strdup (".");
2559
2560
0
  last_nonslash = strlen (file_name) - 1;
2561
2562
0
  while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2563
0
    last_nonslash--;
2564
2565
0
  if (last_nonslash == -1)
2566
    /* string only containing slashes */
2567
0
    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
0
  base = last_nonslash;
2577
2578
0
  while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2579
0
    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
0
  len = last_nonslash - base;
2589
0
  retval = g_malloc (len + 1);
2590
0
  memcpy (retval, file_name + (base + 1), len);
2591
0
  retval [len] = '\0';
2592
2593
0
  return retval;
2594
0
}
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 *
2624
g_path_get_dirname (const gchar *file_name)
2625
0
{
2626
0
  gchar *base;
2627
0
  gsize len;
2628
2629
0
  g_return_val_if_fail (file_name != NULL, NULL);
2630
2631
0
  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
0
  if (!base)
2643
0
    {
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
0
    return g_strdup (".");
2658
0
    }
2659
2660
0
  while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2661
0
    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
0
  len = (guint) 1 + base - file_name;
2710
0
  base = g_new (gchar, len + 1);
2711
0
  memmove (base, file_name, len);
2712
0
  base[len] = 0;
2713
2714
0
  return base;
2715
0
}
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 *
2743
g_canonicalize_filename (const gchar *filename,
2744
                         const gchar *relative_to)
2745
0
{
2746
0
  gchar *canon, *start, *p, *q;
2747
0
  guint i;
2748
2749
0
  g_return_val_if_fail (relative_to == NULL || g_path_is_absolute (relative_to), NULL);
2750
2751
0
  if (!g_path_is_absolute (filename))
2752
0
    {
2753
0
      gchar *cwd_allocated = NULL;
2754
0
      const gchar  *cwd;
2755
2756
0
      if (relative_to != NULL)
2757
0
        cwd = relative_to;
2758
0
      else
2759
0
        cwd = cwd_allocated = g_get_current_dir ();
2760
2761
0
      canon = g_build_filename (cwd, filename, NULL);
2762
0
      g_free (cwd_allocated);
2763
0
    }
2764
0
  else
2765
0
    {
2766
0
      canon = g_strdup (filename);
2767
0
    }
2768
2769
0
  start = (char *)g_path_skip_root (canon);
2770
2771
0
  if (start == NULL)
2772
0
    {
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
0
      g_free (canon);
2777
0
      return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
2778
0
    }
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
0
  i = 0;
2786
0
  for (p = start - 1;
2787
0
       (p >= canon) &&
2788
0
         G_IS_DIR_SEPARATOR (*p);
2789
0
       p--)
2790
0
    i++;
2791
0
  if (i > 2)
2792
0
    {
2793
0
      i -= 1;
2794
0
      start -= i;
2795
0
      memmove (start, start+i, strlen (start+i) + 1);
2796
0
    }
2797
2798
  /* Make sure we're using the canonical dir separator */
2799
0
  p++;
2800
0
  while (p < start && G_IS_DIR_SEPARATOR (*p))
2801
0
    *p++ = G_DIR_SEPARATOR;
2802
2803
0
  p = start;
2804
0
  while (*p != 0)
2805
0
    {
2806
0
      if (p[0] == '.' && (p[1] == 0 || G_IS_DIR_SEPARATOR (p[1])))
2807
0
        {
2808
0
          memmove (p, p+1, strlen (p+1)+1);
2809
0
        }
2810
0
      else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || G_IS_DIR_SEPARATOR (p[2])))
2811
0
        {
2812
0
          q = p + 2;
2813
          /* Skip previous separator */
2814
0
          p = p - 2;
2815
0
          if (p < start)
2816
0
            p = start;
2817
0
          while (p > start && !G_IS_DIR_SEPARATOR (*p))
2818
0
            p--;
2819
0
          if (G_IS_DIR_SEPARATOR (*p))
2820
0
            *p++ = G_DIR_SEPARATOR;
2821
0
          memmove (p, q, strlen (q)+1);
2822
0
        }
2823
0
      else
2824
0
        {
2825
          /* Skip until next separator */
2826
0
          while (*p != 0 && !G_IS_DIR_SEPARATOR (*p))
2827
0
            p++;
2828
2829
0
          if (*p != 0)
2830
0
            {
2831
              /* Canonicalize one separator */
2832
0
              *p++ = G_DIR_SEPARATOR;
2833
0
            }
2834
0
        }
2835
2836
      /* Remove additional separators */
2837
0
      q = p;
2838
0
      while (*q && G_IS_DIR_SEPARATOR (*q))
2839
0
        q++;
2840
2841
0
      if (p != q)
2842
0
        memmove (p, q, strlen (q) + 1);
2843
0
    }
2844
2845
  /* Remove trailing slashes */
2846
0
  if (p > start && G_IS_DIR_SEPARATOR (*(p-1)))
2847
0
    *(p-1) = 0;
2848
2849
0
  return canon;
2850
0
}
2851
2852
#if defined(MAXPATHLEN)
2853
#define G_PATH_LENGTH MAXPATHLEN
2854
#elif defined(PATH_MAX)
2855
0
#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 *
2879
g_get_current_dir (void)
2880
0
{
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
0
  const gchar *pwd;
2902
0
  gchar *buffer = NULL;
2903
0
  gchar *dir = NULL;
2904
0
  static gulong max_len = 0;
2905
0
  struct stat pwdbuf, dotbuf;
2906
2907
0
  pwd = g_getenv ("PWD");
2908
0
  if (pwd != NULL &&
2909
0
      g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2910
0
      dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2911
0
    return g_strdup (pwd);
2912
2913
0
  if (max_len == 0)
2914
0
    max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2915
2916
0
  while (max_len < G_MAXULONG / 2)
2917
0
    {
2918
0
      g_free (buffer);
2919
0
      buffer = g_new (gchar, max_len + 1);
2920
0
      *buffer = 0;
2921
0
      dir = getcwd (buffer, max_len);
2922
2923
0
      if (dir || errno != ERANGE)
2924
0
        break;
2925
2926
0
      max_len *= 2;
2927
0
    }
2928
2929
0
  if (!dir || !*buffer)
2930
0
    {
2931
      /* hm, should we g_error() out here?
2932
       * this can happen if e.g. "./" has mode \0000
2933
       */
2934
0
      buffer[0] = G_DIR_SEPARATOR;
2935
0
      buffer[1] = 0;
2936
0
    }
2937
2938
0
  dir = g_strdup (buffer);
2939
0
  g_free (buffer);
2940
2941
0
  return dir;
2942
2943
0
#endif /* !G_OS_WIN32 */
2944
0
}
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
2964
g_file_test_utf8 (const gchar *filename,
2965
                  GFileTest    test)
2966
{
2967
  return g_file_test (filename, test);
2968
}
2969
2970
gboolean
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
2980
g_mkstemp_utf8 (gchar *tmpl)
2981
{
2982
  return g_mkstemp (tmpl);
2983
}
2984
2985
gint
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 *
2994
g_get_current_dir_utf8 (void)
2995
{
2996
  return g_get_current_dir ();
2997
}
2998
2999
#endif