Coverage Report

Created: 2025-07-18 06:10

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