Coverage Report

Created: 2025-07-11 07:03

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