Coverage Report

Created: 2026-12-01 06:30

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