Coverage Report

Created: 2026-04-12 06:39

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