Coverage Report

Created: 2025-12-31 06:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/glib/glib/glib-unix.c
Line
Count
Source
1
/* GLIB - Library of useful routines for C programming
2
 * Copyright 2000-2022 Red Hat, Inc.
3
 * Copyright 2006-2007 Matthias Clasen
4
 * Copyright 2006 Padraig O'Briain
5
 * Copyright 2007 Lennart Poettering
6
 * Copyright 2018-2022 Endless OS Foundation, LLC
7
 * Copyright 2018 Peter Wu
8
 * Copyright 2019 Ting-Wei Lan
9
 * Copyright 2019 Sebastian Schwarz
10
 * Copyright 2020 Matt Rose
11
 * Copyright 2021 Casper Dik
12
 * Copyright 2022 Alexander Richardson
13
 * Copyright 2022 Ray Strode
14
 * Copyright 2022 Thomas Haller
15
 * Copyright 2023-2024 Collabora Ltd.
16
 * Copyright 2023 Sebastian Wilhelmi
17
 * Copyright 2023 CaiJingLong
18
 *
19
 * glib-unix.c: UNIX specific API wrappers and convenience functions
20
 *
21
 * SPDX-License-Identifier: LGPL-2.1-or-later
22
 *
23
 * This library is free software; you can redistribute it and/or
24
 * modify it under the terms of the GNU Lesser General Public
25
 * License as published by the Free Software Foundation; either
26
 * version 2.1 of the License, or (at your option) any later version.
27
 *
28
 * This library is distributed in the hope that it will be useful,
29
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
31
 * Lesser General Public License for more details.
32
 *
33
 * You should have received a copy of the GNU Lesser General Public
34
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
35
 *
36
 * Authors: Colin Walters <walters@verbum.org>
37
 */
38
39
#include "config.h"
40
41
#include "glib-private.h"
42
#include "glib-unix.h"
43
#include "glib-unixprivate.h"
44
#include "glib.h"
45
#include "gmain-internal.h"
46
47
#include <dirent.h>
48
#include <errno.h>
49
#include <fcntl.h>
50
#include <stdlib.h>   /* for fdwalk */
51
#include <string.h>
52
#include <sys/types.h>
53
#include <pwd.h>
54
#include <unistd.h>
55
56
#if defined(__linux__) || defined(__DragonFly__)
57
#include <sys/syscall.h>  /* for syscall and SYS_getdents64 */
58
#endif
59
60
#ifdef HAVE_SYS_RESOURCE_H
61
#include <sys/resource.h>
62
#endif /* HAVE_SYS_RESOURCE_H */
63
64
65
#if defined (__APPLE__)
66
#include <sys/param.h>
67
#  if defined(HAVE_LIBPROC_H)
68
#    include <libproc.h>
69
#    include <sys/proc_info.h>
70
#  endif /* defined(HAVE_LIBPROC_H) */
71
#endif  /* defined (__APPLE__ )*/
72
73
#if defined (__FreeBSD__)
74
#include <sys/user.h>
75
#endif  /* defined (__FreeBSD__ )*/
76
77
G_STATIC_ASSERT (sizeof (ssize_t) == GLIB_SIZEOF_SSIZE_T);
78
G_STATIC_ASSERT (G_ALIGNOF (gssize) == G_ALIGNOF (ssize_t));
79
G_STATIC_ASSERT (G_SIGNEDNESS_OF (ssize_t) == 1);
80
81
G_STATIC_ASSERT (sizeof (GPid) == sizeof (pid_t));
82
G_STATIC_ASSERT (G_ALIGNOF (GPid) == G_ALIGNOF (pid_t));
83
/* It's platform-dependent whether pid_t is signed, so no assertion */
84
85
/* If this assertion fails, then the ABI of g_unix_open_pipe() would be
86
 * ambiguous on this platform.
87
 * On Linux, usually O_NONBLOCK == 04000 and FD_CLOEXEC == 1, but the same
88
 * might not be true everywhere. */
89
G_STATIC_ASSERT (O_NONBLOCK != FD_CLOEXEC);
90
91
G_DEFINE_QUARK (g-unix-error-quark, g_unix_error)
92
93
static gboolean
94
g_unix_set_error_from_errno (GError **error,
95
                             gint     saved_errno)
96
0
{
97
0
  g_set_error_literal (error,
98
0
                       G_UNIX_ERROR,
99
0
                       0,
100
0
                       g_strerror (saved_errno));
101
0
  errno = saved_errno;
102
0
  return FALSE;
103
0
}
104
105
/**
106
 * g_unix_open_pipe:
107
 * @fds: (array fixed-size=2): Array of two integers
108
 * @flags: Bitfield of file descriptor flags, as for fcntl()
109
 * @error: a #GError
110
 *
111
 * Similar to the UNIX pipe() call, but on modern systems like Linux
112
 * uses the pipe2() system call, which atomically creates a pipe with
113
 * the configured flags.
114
 *
115
 * As of GLib 2.78, the supported flags are `O_CLOEXEC`/`FD_CLOEXEC` (see below)
116
 * and `O_NONBLOCK`. Prior to GLib 2.78, only `FD_CLOEXEC` was supported — if
117
 * you wanted to configure `O_NONBLOCK` then that had to be done separately with
118
 * `fcntl()`.
119
 *
120
 * Since GLib 2.80, the constants %G_UNIX_PIPE_END_READ and
121
 * %G_UNIX_PIPE_END_WRITE can be used as mnemonic indexes in @fds.
122
 *
123
 * It is a programmer error to call this function with unsupported flags, and a
124
 * critical warning will be raised.
125
 *
126
 * As of GLib 2.78, it is preferred to pass `O_CLOEXEC` in, rather than
127
 * `FD_CLOEXEC`, as that matches the underlying `pipe()` API more closely. Prior
128
 * to 2.78, only `FD_CLOEXEC` was supported. Support for `FD_CLOEXEC` may be
129
 * deprecated and removed in future.
130
 *
131
 * Returns: %TRUE on success, %FALSE if not (and errno will be set).
132
 *
133
 * Since: 2.30
134
 */
135
gboolean
136
g_unix_open_pipe (int     *fds,
137
                  int      flags,
138
                  GError **error)
139
0
{
140
  /* We only support O_CLOEXEC/FD_CLOEXEC and O_NONBLOCK */
141
0
  g_return_val_if_fail ((flags & (O_CLOEXEC | FD_CLOEXEC | O_NONBLOCK)) == flags, FALSE);
142
143
0
#if O_CLOEXEC != FD_CLOEXEC && !defined(G_DISABLE_CHECKS)
144
0
  if (flags & FD_CLOEXEC)
145
0
    g_debug ("g_unix_open_pipe() called with FD_CLOEXEC; please migrate to using O_CLOEXEC instead");
146
0
#endif
147
148
0
  if (!g_unix_open_pipe_internal (fds,
149
0
                                  (flags & (O_CLOEXEC | FD_CLOEXEC)) != 0,
150
0
                                  (flags & O_NONBLOCK) != 0))
151
0
    return g_unix_set_error_from_errno (error, errno);
152
153
0
  return TRUE;
154
0
}
155
156
/**
157
 * g_unix_set_fd_nonblocking:
158
 * @fd: A file descriptor
159
 * @nonblock: If %TRUE, set the descriptor to be non-blocking
160
 * @error: a #GError
161
 *
162
 * Control the non-blocking state of the given file descriptor,
163
 * according to @nonblock. On most systems this uses %O_NONBLOCK, but
164
 * on some older ones may use %O_NDELAY.
165
 *
166
 * Returns: %TRUE if successful
167
 *
168
 * Since: 2.30
169
 */
170
gboolean
171
g_unix_set_fd_nonblocking (gint       fd,
172
                           gboolean   nonblock,
173
                           GError   **error)
174
0
{
175
0
#ifdef F_GETFL
176
0
  glong fcntl_flags;
177
0
  fcntl_flags = fcntl (fd, F_GETFL);
178
179
0
  if (fcntl_flags == -1)
180
0
    return g_unix_set_error_from_errno (error, errno);
181
182
0
  if (nonblock)
183
0
    fcntl_flags |= O_NONBLOCK;
184
0
  else
185
0
    fcntl_flags &= ~O_NONBLOCK;
186
187
0
  if (fcntl (fd, F_SETFL, fcntl_flags) == -1)
188
0
    return g_unix_set_error_from_errno (error, errno);
189
0
  return TRUE;
190
#else
191
  return g_unix_set_error_from_errno (error, EINVAL);
192
#endif
193
0
}
194
195
/**
196
 * g_unix_signal_source_new:
197
 * @signum: A signal number
198
 *
199
 * Create a #GSource that will be dispatched upon delivery of the UNIX
200
 * signal @signum.  In GLib versions before 2.36, only `SIGHUP`, `SIGINT`,
201
 * `SIGTERM` can be monitored.  In GLib 2.36, `SIGUSR1` and `SIGUSR2`
202
 * were added. In GLib 2.54, `SIGWINCH` was added.
203
 *
204
 * Note that unlike the UNIX default, all sources which have created a
205
 * watch will be dispatched, regardless of which underlying thread
206
 * invoked g_unix_signal_source_new().
207
 *
208
 * For example, an effective use of this function is to handle `SIGTERM`
209
 * cleanly; flushing any outstanding files, and then calling
210
 * g_main_loop_quit().  It is not safe to do any of this from a regular
211
 * UNIX signal handler; such a handler may be invoked while malloc() or
212
 * another library function is running, causing reentrancy issues if the
213
 * handler attempts to use those functions.  None of the GLib/GObject
214
 * API is safe against this kind of reentrancy.
215
 *
216
 * The interaction of this source when combined with native UNIX
217
 * functions like sigprocmask() is not defined.
218
 *
219
 * The source will not initially be associated with any #GMainContext
220
 * and must be added to one with g_source_attach() before it will be
221
 * executed.
222
 *
223
 * Returns: A newly created #GSource
224
 *
225
 * Since: 2.30
226
 */
227
GSource *
228
g_unix_signal_source_new (int signum)
229
0
{
230
0
  g_return_val_if_fail (signum == SIGHUP || signum == SIGINT || signum == SIGTERM ||
231
0
                        signum == SIGUSR1 || signum == SIGUSR2 || signum == SIGWINCH,
232
0
                        NULL);
233
234
0
  return _g_main_create_unix_signal_watch (signum);
235
0
}
236
237
/**
238
 * g_unix_signal_add_full: (rename-to g_unix_signal_add)
239
 * @priority: the priority of the signal source. Typically this will be in
240
 *            the range between %G_PRIORITY_DEFAULT and %G_PRIORITY_HIGH.
241
 * @signum: Signal number
242
 * @handler: Callback
243
 * @user_data: Data for @handler
244
 * @notify: #GDestroyNotify for @handler
245
 *
246
 * A convenience function for g_unix_signal_source_new(), which
247
 * attaches to the default #GMainContext.  You can remove the watch
248
 * using g_source_remove().
249
 *
250
 * Returns: An ID (greater than 0) for the event source
251
 *
252
 * Since: 2.30
253
 */
254
guint
255
g_unix_signal_add_full (int            priority,
256
                        int            signum,
257
                        GSourceFunc    handler,
258
                        gpointer       user_data,
259
                        GDestroyNotify notify)
260
0
{
261
0
  guint id;
262
0
  GSource *source;
263
264
0
  source = g_unix_signal_source_new (signum);
265
266
0
  if (priority != G_PRIORITY_DEFAULT)
267
0
    g_source_set_priority (source, priority);
268
269
0
  g_source_set_callback (source, handler, user_data, notify);
270
0
  id = g_source_attach (source, NULL);
271
0
  g_source_unref (source);
272
273
0
  return id;
274
0
}
275
276
/**
277
 * g_unix_signal_add:
278
 * @signum: Signal number
279
 * @handler: Callback
280
 * @user_data: Data for @handler
281
 *
282
 * A convenience function for g_unix_signal_source_new(), which
283
 * attaches to the default #GMainContext.  You can remove the watch
284
 * using g_source_remove().
285
 *
286
 * Returns: An ID (greater than 0) for the event source
287
 *
288
 * Since: 2.30
289
 */
290
guint
291
g_unix_signal_add (int         signum,
292
                   GSourceFunc handler,
293
                   gpointer    user_data)
294
0
{
295
0
  return g_unix_signal_add_full (G_PRIORITY_DEFAULT, signum, handler, user_data, NULL);
296
0
}
297
298
typedef struct
299
{
300
  GSource source;
301
302
  gint     fd;
303
  gpointer tag;
304
} GUnixFDSource;
305
306
static gboolean
307
g_unix_fd_source_dispatch (GSource     *source,
308
                           GSourceFunc  callback,
309
                           gpointer     user_data)
310
0
{
311
0
  GUnixFDSource *fd_source = (GUnixFDSource *) source;
312
0
  GUnixFDSourceFunc func = (GUnixFDSourceFunc) callback;
313
314
0
  if (!callback)
315
0
    {
316
0
      g_warning ("GUnixFDSource dispatched without callback. "
317
0
                 "You must call g_source_set_callback().");
318
0
      return FALSE;
319
0
    }
320
321
0
  return (* func) (fd_source->fd, g_source_query_unix_fd (source, fd_source->tag), user_data);
322
0
}
323
324
GSourceFuncs g_unix_fd_source_funcs = {
325
  NULL, NULL, g_unix_fd_source_dispatch, NULL, NULL, NULL
326
};
327
328
/**
329
 * g_unix_fd_source_new:
330
 * @fd: a file descriptor
331
 * @condition: I/O conditions to watch for on @fd
332
 *
333
 * Creates a #GSource to watch for a particular I/O condition on a file
334
 * descriptor.
335
 *
336
 * The source will never close the @fd — you must do it yourself.
337
 *
338
 * Any callback attached to the returned #GSource must have type
339
 * #GUnixFDSourceFunc.
340
 *
341
 * Returns: the newly created #GSource
342
 *
343
 * Since: 2.36
344
 **/
345
GSource *
346
g_unix_fd_source_new (gint         fd,
347
                      GIOCondition condition)
348
0
{
349
0
  GUnixFDSource *fd_source;
350
0
  GSource *source;
351
352
0
  source = g_source_new (&g_unix_fd_source_funcs, sizeof (GUnixFDSource));
353
0
  fd_source = (GUnixFDSource *) source;
354
355
0
  fd_source->fd = fd;
356
0
  fd_source->tag = g_source_add_unix_fd (source, fd, condition);
357
358
0
  return source;
359
0
}
360
361
/**
362
 * g_unix_fd_add_full:
363
 * @priority: the priority of the source
364
 * @fd: a file descriptor
365
 * @condition: IO conditions to watch for on @fd
366
 * @function: a #GUnixFDSourceFunc
367
 * @user_data: data to pass to @function
368
 * @notify: function to call when the idle is removed, or %NULL
369
 *
370
 * Sets a function to be called when the IO condition, as specified by
371
 * @condition becomes true for @fd.
372
 *
373
 * This is the same as g_unix_fd_add(), except that it allows you to
374
 * specify a non-default priority and a provide a #GDestroyNotify for
375
 * @user_data.
376
 *
377
 * Returns: the ID (greater than 0) of the event source
378
 *
379
 * Since: 2.36
380
 **/
381
guint
382
g_unix_fd_add_full (gint              priority,
383
                    gint              fd,
384
                    GIOCondition      condition,
385
                    GUnixFDSourceFunc function,
386
                    gpointer          user_data,
387
                    GDestroyNotify    notify)
388
0
{
389
0
  GSource *source;
390
0
  guint id;
391
392
0
  g_return_val_if_fail (function != NULL, 0);
393
394
0
  source = g_unix_fd_source_new (fd, condition);
395
396
0
  if (priority != G_PRIORITY_DEFAULT)
397
0
    g_source_set_priority (source, priority);
398
399
0
  g_source_set_callback (source, (GSourceFunc) function, user_data, notify);
400
0
  id = g_source_attach (source, NULL);
401
0
  g_source_unref (source);
402
403
0
  return id;
404
0
}
405
406
/**
407
 * g_unix_fd_add:
408
 * @fd: a file descriptor
409
 * @condition: IO conditions to watch for on @fd
410
 * @function: a #GUnixFDSourceFunc
411
 * @user_data: data to pass to @function
412
 *
413
 * Sets a function to be called when the IO condition, as specified by
414
 * @condition becomes true for @fd.
415
 *
416
 * @function will be called when the specified IO condition becomes
417
 * %TRUE.  The function is expected to clear whatever event caused the
418
 * IO condition to become true and return %TRUE in order to be notified
419
 * when it happens again.  If @function returns %FALSE then the watch
420
 * will be cancelled.
421
 *
422
 * The return value of this function can be passed to g_source_remove()
423
 * to cancel the watch at any time that it exists.
424
 *
425
 * The source will never close the fd -- you must do it yourself.
426
 *
427
 * Returns: the ID (greater than 0) of the event source
428
 *
429
 * Since: 2.36
430
 **/
431
guint
432
g_unix_fd_add (gint              fd,
433
               GIOCondition      condition,
434
               GUnixFDSourceFunc function,
435
               gpointer          user_data)
436
0
{
437
0
  return g_unix_fd_add_full (G_PRIORITY_DEFAULT, fd, condition, function, user_data, NULL);
438
0
}
439
440
/**
441
 * g_unix_get_passwd_entry:
442
 * @user_name: the username to get the passwd file entry for
443
 * @error: return location for a #GError, or %NULL
444
 *
445
 * Get the `passwd` file entry for the given @user_name using `getpwnam_r()`.
446
 * This can fail if the given @user_name doesn’t exist.
447
 *
448
 * The returned `struct passwd` has been allocated using g_malloc() and should
449
 * be freed using g_free(). The strings referenced by the returned struct are
450
 * included in the same allocation, so are valid until the `struct passwd` is
451
 * freed.
452
 *
453
 * This function is safe to call from multiple threads concurrently.
454
 *
455
 * You will need to include `pwd.h` to get the definition of `struct passwd`.
456
 *
457
 * Returns: (transfer full): passwd entry, or %NULL on error; free the returned
458
 *    value with g_free()
459
 * Since: 2.64
460
 */
461
struct passwd *
462
g_unix_get_passwd_entry (const gchar  *user_name,
463
                         GError      **error)
464
0
{
465
0
  struct passwd *passwd_file_entry;
466
0
  struct
467
0
    {
468
0
      struct passwd pwd;
469
0
      char string_buffer[];
470
0
    } *buffer = NULL;
471
0
  gsize string_buffer_size = 0;
472
0
  GError *local_error = NULL;
473
474
0
  g_return_val_if_fail (user_name != NULL, NULL);
475
0
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
476
477
0
#ifdef _SC_GETPW_R_SIZE_MAX
478
0
    {
479
      /* Get the recommended buffer size */
480
0
      glong string_buffer_size_long = sysconf (_SC_GETPW_R_SIZE_MAX);
481
0
      if (string_buffer_size_long > 0)
482
0
        string_buffer_size = string_buffer_size_long;
483
0
    }
484
0
#endif /* _SC_GETPW_R_SIZE_MAX */
485
486
  /* Default starting size. */
487
0
  if (string_buffer_size == 0)
488
0
    string_buffer_size = 64;
489
490
0
  do
491
0
    {
492
0
      int retval;
493
494
0
      g_free (buffer);
495
      /* Allocate space for the `struct passwd`, and then a buffer for all its
496
       * strings (whose size is @string_buffer_size, which increases in this
497
       * loop until it’s big enough). Add 6 extra bytes to work around a bug in
498
       * macOS < 10.3. See #156446.
499
       */
500
0
      buffer = g_malloc0 (sizeof (*buffer) + string_buffer_size + 6);
501
502
0
      retval = getpwnam_r (user_name, &buffer->pwd, buffer->string_buffer,
503
0
                           string_buffer_size, &passwd_file_entry);
504
505
      /* Bail out if: the lookup was successful, or if the user id can't be
506
       * found (should be pretty rare case actually), or if the buffer should be
507
       * big enough and yet lookups are still not successful.
508
       */
509
0
      if (passwd_file_entry != NULL)
510
0
        {
511
          /* Success. */
512
0
          break;
513
0
        }
514
0
      else if (retval == 0 ||
515
0
          retval == ENOENT || retval == ESRCH ||
516
0
          retval == EBADF || retval == EPERM)
517
0
        {
518
          /* Username not found. */
519
0
          g_unix_set_error_from_errno (&local_error, retval);
520
0
          break;
521
0
        }
522
0
      else if (retval == ERANGE)
523
0
        {
524
          /* Can’t allocate enough string buffer space. */
525
0
          if (string_buffer_size > 32 * 1024)
526
0
            {
527
0
              g_unix_set_error_from_errno (&local_error, retval);
528
0
              break;
529
0
            }
530
531
0
          string_buffer_size *= 2;
532
0
          continue;
533
0
        }
534
0
      else
535
0
        {
536
0
          g_unix_set_error_from_errno (&local_error, retval);
537
0
          break;
538
0
        }
539
0
    }
540
0
  while (passwd_file_entry == NULL);
541
542
0
  g_assert (passwd_file_entry == NULL ||
543
0
            (gpointer) passwd_file_entry == (gpointer) buffer);
544
545
  /* Success or error. */
546
0
  if (local_error != NULL)
547
0
    {
548
0
      g_clear_pointer (&buffer, g_free);
549
0
      g_propagate_error (error, g_steal_pointer (&local_error));
550
0
    }
551
552
0
  return (struct passwd *) g_steal_pointer (&buffer);
553
0
}
554
555
/* This function is called between fork() and exec() and hence must be
556
 * async-signal-safe (see signal-safety(7)). */
557
static int
558
set_cloexec (void *data, gint fd)
559
0
{
560
0
  if (fd >= GPOINTER_TO_INT (data))
561
0
    fcntl (fd, F_SETFD, FD_CLOEXEC);
562
563
0
  return 0;
564
0
}
565
566
/* fdwalk()-compatible callback to close a fd for non-compliant
567
 * implementations of fdwalk() that potentially pass already
568
 * closed fds.
569
 *
570
 * It is not an error to pass an invalid fd to this function.
571
 *
572
 * This function is called between fork() and exec() and hence must be
573
 * async-signal-safe (see signal-safety(7)).
574
 */
575
G_GNUC_UNUSED static int
576
close_func_with_invalid_fds (void *data, int fd)
577
0
{
578
  /* We use close and not g_close here because on some platforms, we
579
   * don't know how to close only valid, open file descriptors, so we
580
   * have to pass bad fds to close too. g_close warns if given a bad
581
   * fd.
582
   *
583
   * This function returns no error, because there is nothing that the caller
584
   * could do with that information. That is even the case for EINTR. See
585
   * g_close() about the specialty of EINTR and why that is correct.
586
   * If g_close() ever gets extended to handle EINTR specially, then this place
587
   * should get updated to do the same handling.
588
   */
589
0
  if (fd >= GPOINTER_TO_INT (data))
590
0
    close (fd);
591
592
0
  return 0;
593
0
}
594
595
#ifdef __linux__
596
struct linux_dirent64
597
{
598
  guint64        d_ino;    /* 64-bit inode number */
599
  guint64        d_off;    /* 64-bit offset to next structure */
600
  unsigned short d_reclen; /* Size of this dirent */
601
  unsigned char  d_type;   /* File type */
602
  char           d_name[]; /* Filename (null-terminated) */
603
};
604
605
/* This function is called between fork() and exec() and hence must be
606
 * async-signal-safe (see signal-safety(7)). */
607
static gint
608
filename_to_fd (const char *p)
609
0
{
610
0
  char c;
611
0
  int fd = 0;
612
0
  const int cutoff = G_MAXINT / 10;
613
0
  const int cutlim = G_MAXINT % 10;
614
615
0
  if (*p == '\0')
616
0
    return -1;
617
618
0
  while ((c = *p++) != '\0')
619
0
    {
620
0
      if (c < '0' || c > '9')
621
0
        return -1;
622
0
      c -= '0';
623
624
      /* Check for overflow. */
625
0
      if (fd > cutoff || (fd == cutoff && c > cutlim))
626
0
        return -1;
627
628
0
      fd = fd * 10 + c;
629
0
    }
630
631
0
  return fd;
632
0
}
633
#endif
634
635
static int safe_fdwalk_with_invalid_fds (int (*cb)(void *data, int fd), void *data);
636
637
/* This function is called between fork() and exec() and hence must be
638
 * async-signal-safe (see signal-safety(7)). */
639
static int
640
safe_fdwalk (int (*cb)(void *data, int fd), void *data)
641
0
{
642
#if 0
643
  /* Use fdwalk function provided by the system if it is known to be
644
   * async-signal safe.
645
   *
646
   * Currently there are no operating systems known to provide a safe
647
   * implementation, so this section is not used for now.
648
   */
649
  return fdwalk (cb, data);
650
#else
651
  /* Fallback implementation of fdwalk. It should be async-signal safe, but it
652
   * may fail on non-Linux operating systems. See safe_fdwalk_with_invalid_fds
653
   * for a slower alternative.
654
   */
655
656
0
#ifdef __linux__
657
0
  gint fd;
658
0
  gint res = 0;
659
660
  /* Avoid use of opendir/closedir since these are not async-signal-safe. */
661
0
  int dir_fd = open ("/proc/self/fd", O_RDONLY | O_DIRECTORY);
662
0
  if (dir_fd >= 0)
663
0
    {
664
      /* buf needs to be aligned correctly to receive linux_dirent64.
665
       * C11 has _Alignof for this purpose, but for now a
666
       * union serves the same purpose. */
667
0
      union
668
0
      {
669
0
        char buf[4096];
670
0
        struct linux_dirent64 alignment;
671
0
      } u;
672
0
      int pos, nread;
673
0
      struct linux_dirent64 *de;
674
675
0
      while ((nread = syscall (SYS_getdents64, dir_fd, u.buf, sizeof (u.buf))) > 0)
676
0
        {
677
0
          for (pos = 0; pos < nread; pos += de->d_reclen)
678
0
            {
679
0
              de = (struct linux_dirent64 *) (u.buf + pos);
680
681
0
              fd = filename_to_fd (de->d_name);
682
0
              if (fd < 0 || fd == dir_fd)
683
0
                  continue;
684
685
0
              if ((res = cb (data, fd)) != 0)
686
0
                  break;
687
0
            }
688
0
        }
689
690
0
      g_close (dir_fd, NULL);
691
0
      return res;
692
0
    }
693
694
  /* If /proc is not mounted or not accessible we fail here and rely on
695
   * safe_fdwalk_with_invalid_fds to fall back to the old
696
   * rlimit trick. */
697
698
0
#endif
699
700
#if defined(__sun__) && defined(F_PREVFD) && defined(F_NEXTFD)
701
/*
702
 * Solaris 11.4 has a signal-safe way which allows
703
 * us to find all file descriptors in a process.
704
 *
705
 * fcntl(fd, F_NEXTFD, maxfd)
706
 * - returns the first allocated file descriptor <= maxfd  > fd.
707
 *
708
 * fcntl(fd, F_PREVFD)
709
 * - return highest allocated file descriptor < fd.
710
 */
711
  gint open_max;
712
  gint fd;
713
  gint res = 0;
714
715
  open_max = fcntl (INT_MAX, F_PREVFD); /* find the maximum fd */
716
  if (open_max < 0) /* No open files */
717
    return 0;
718
719
  for (fd = -1; (fd = fcntl (fd, F_NEXTFD, open_max)) != -1; )
720
    if ((res = cb (data, fd)) != 0 || fd == open_max)
721
      break;
722
723
  return res;
724
#endif
725
726
0
  return safe_fdwalk_with_invalid_fds (cb, data);
727
0
#endif
728
0
}
729
730
/* This function is called between fork() and exec() and hence must be
731
 * async-signal-safe (see signal-safety(7)). */
732
static int
733
safe_fdwalk_with_invalid_fds (int (*cb)(void *data, int fd), void *data)
734
0
{
735
  /* Fallback implementation of fdwalk. It should be async-signal safe, but it
736
   * may be slow, especially on systems allowing very high number of open file
737
   * descriptors.
738
   */
739
0
  gint open_max = -1;
740
0
  gint fd;
741
0
  gint res = 0;
742
743
#if 0 && defined(HAVE_SYS_RESOURCE_H)
744
  struct rlimit rl;
745
746
  /* Use getrlimit() function provided by the system if it is known to be
747
   * async-signal safe.
748
   *
749
   * Currently there are no operating systems known to provide a safe
750
   * implementation, so this section is not used for now.
751
   */
752
  if (getrlimit (RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
753
    open_max = rl.rlim_max;
754
#endif
755
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
756
  /* Use sysconf() function provided by the system if it is known to be
757
   * async-signal safe.
758
   *
759
   * FreeBSD: sysconf() is included in the list of async-signal safe functions
760
   * found in https://man.freebsd.org/sigaction(2).
761
   *
762
   * OpenBSD: sysconf() is included in the list of async-signal safe functions
763
   * found in https://man.openbsd.org/sigaction.2.
764
   *
765
   * Apple: sysconf() is included in the list of async-signal safe functions
766
   * found in https://opensource.apple.com/source/xnu/xnu-517.12.7/bsd/man/man2/sigaction.2
767
   */
768
  if (open_max < 0)
769
    open_max = sysconf (_SC_OPEN_MAX);
770
#endif
771
  /* Hardcoded fallback: the default process hard limit in Linux as of 2020 */
772
0
  if (open_max < 0)
773
0
    open_max = 4096;
774
775
#if defined(__APPLE__) && defined(HAVE_LIBPROC_H)
776
  /* proc_pidinfo isn't documented as async-signal-safe but looking at the implementation
777
   * in the darwin tree here:
778
   *
779
   * https://opensource.apple.com/source/Libc/Libc-498/darwin/libproc.c.auto.html
780
   *
781
   * It's just a thin wrapper around a syscall, so it's probably okay.
782
   */
783
  {
784
    char buffer[4096 * PROC_PIDLISTFD_SIZE];
785
    ssize_t buffer_size;
786
787
    buffer_size = proc_pidinfo (getpid (), PROC_PIDLISTFDS, 0, buffer, sizeof (buffer));
788
789
    if (buffer_size > 0 &&
790
        sizeof (buffer) >= (size_t) buffer_size &&
791
        (buffer_size % PROC_PIDLISTFD_SIZE) == 0)
792
      {
793
        const struct proc_fdinfo *fd_info = (const struct proc_fdinfo *) buffer;
794
        size_t number_of_fds = (size_t) buffer_size / PROC_PIDLISTFD_SIZE;
795
796
        for (size_t i = 0; i < number_of_fds; i++)
797
          if ((res = cb (data, fd_info[i].proc_fd)) != 0)
798
            break;
799
800
        return res;
801
      }
802
  }
803
#endif
804
805
0
  for (fd = 0; fd < open_max; fd++)
806
0
      if ((res = cb (data, fd)) != 0)
807
0
          break;
808
809
0
  return res;
810
0
}
811
812
/**
813
 * g_fdwalk_set_cloexec:
814
 * @lowfd: Minimum fd to act on, which must be non-negative
815
 *
816
 * Mark every file descriptor equal to or greater than @lowfd to be closed
817
 * at the next `execve()` or similar, as if via the `FD_CLOEXEC` flag.
818
 *
819
 * Typically @lowfd will be 3, to leave standard input, standard output
820
 * and standard error open after exec.
821
 *
822
 * This is the same as Linux `close_range (lowfd, ~0U, CLOSE_RANGE_CLOEXEC)`,
823
 * but portable to other OSs and to older versions of Linux.
824
 *
825
 * This function is async-signal safe, making it safe to call from a
826
 * signal handler or a [callback@GLib.SpawnChildSetupFunc], as long as @lowfd is
827
 * non-negative.
828
 * See [`signal(7)`](man:signal(7)) and
829
 * [`signal-safety(7)`](man:signal-safety(7)) for more details.
830
 *
831
 * Returns: 0 on success, -1 with errno set on error
832
 * Since: 2.80
833
 */
834
int
835
g_fdwalk_set_cloexec (int lowfd)
836
0
{
837
0
  int ret;
838
839
0
  g_return_val_if_fail (lowfd >= 0, (errno = EINVAL, -1));
840
841
#if defined(HAVE_CLOSE_RANGE) && defined(CLOSE_RANGE_CLOEXEC)
842
  /* close_range() is available in Linux since kernel 5.9, and on FreeBSD at
843
   * around the same time. It was designed for use in async-signal-safe
844
   * situations: https://bugs.python.org/issue38061
845
   *
846
   * The `CLOSE_RANGE_CLOEXEC` flag was added in Linux 5.11, and is not yet
847
   * present in FreeBSD.
848
   *
849
   * Handle ENOSYS in case it’s supported in libc but not the kernel; if so,
850
   * fall back to safe_fdwalk(). Handle EINVAL in case `CLOSE_RANGE_CLOEXEC`
851
   * is not supported. */
852
  ret = close_range (lowfd, G_MAXUINT, CLOSE_RANGE_CLOEXEC);
853
  if (ret == 0 || !(errno == ENOSYS || errno == EINVAL))
854
    return ret;
855
#endif  /* HAVE_CLOSE_RANGE */
856
857
0
  ret = safe_fdwalk (set_cloexec, GINT_TO_POINTER (lowfd));
858
859
0
  return ret;
860
0
}
861
862
/**
863
 * g_closefrom:
864
 * @lowfd: Minimum fd to close, which must be non-negative
865
 *
866
 * Close every file descriptor equal to or greater than @lowfd.
867
 *
868
 * Typically @lowfd will be 3, to leave standard input, standard output
869
 * and standard error open.
870
 *
871
 * This is the same as Linux `close_range (lowfd, ~0U, 0)`,
872
 * but portable to other OSs and to older versions of Linux.
873
 * Equivalently, it is the same as BSD `closefrom (lowfd)`, but portable,
874
 * and async-signal-safe on all OSs.
875
 *
876
 * This function is async-signal safe, making it safe to call from a
877
 * signal handler or a [callback@GLib.SpawnChildSetupFunc], as long as @lowfd is
878
 * non-negative.
879
 * See [`signal(7)`](man:signal(7)) and
880
 * [`signal-safety(7)`](man:signal-safety(7)) for more details.
881
 *
882
 * Returns: 0 on success, -1 with errno set on error
883
 * Since: 2.80
884
 */
885
int
886
g_closefrom (int lowfd)
887
0
{
888
0
  int ret;
889
890
0
  g_return_val_if_fail (lowfd >= 0, (errno = EINVAL, -1));
891
892
#if defined(HAVE_CLOSE_RANGE)
893
  /* close_range() is available in Linux since kernel 5.9, and on FreeBSD at
894
   * around the same time. It was designed for use in async-signal-safe
895
   * situations: https://bugs.python.org/issue38061
896
   *
897
   * Handle ENOSYS in case it’s supported in libc but not the kernel; if so,
898
   * fall back to safe_fdwalk(). */
899
  ret = close_range (lowfd, G_MAXUINT, 0);
900
  if (ret == 0 || errno != ENOSYS)
901
    return ret;
902
#endif  /* HAVE_CLOSE_RANGE */
903
904
#if defined(__FreeBSD__) || defined(__OpenBSD__) || \
905
  (defined(__sun__) && defined(F_CLOSEFROM))
906
  /* Use closefrom function provided by the system if it is known to be
907
   * async-signal safe.
908
   *
909
   * FreeBSD: closefrom is included in the list of async-signal safe functions
910
   * found in https://man.freebsd.org/sigaction(2).
911
   *
912
   * OpenBSD: closefrom is not included in the list, but a direct system call
913
   * should be safe to use.
914
   *
915
   * In Solaris as of 11.3 SRU 31, closefrom() is also a direct system call.
916
   * On such systems, F_CLOSEFROM is defined.
917
   */
918
  (void) closefrom (lowfd);
919
  return 0;
920
#elif defined(__DragonFly__)
921
  /* It is unclear whether closefrom function included in DragonFlyBSD libc_r
922
   * is safe to use because it calls a lot of library functions. It is also
923
   * unclear whether libc_r itself is still being used. Therefore, we do a
924
   * direct system call here ourselves to avoid possible issues.
925
   */
926
  (void) syscall (SYS_closefrom, lowfd);
927
  return 0;
928
#elif defined(F_CLOSEM)
929
  /* NetBSD and AIX have a special fcntl command which does the same thing as
930
   * closefrom. NetBSD also includes closefrom function, which seems to be a
931
   * simple wrapper of the fcntl command.
932
   */
933
  return fcntl (lowfd, F_CLOSEM);
934
#else
935
0
  ret = safe_fdwalk (close_func_with_invalid_fds, GINT_TO_POINTER (lowfd));
936
937
0
  return ret;
938
0
#endif
939
0
}
940
941
/**
942
 * g_unix_fd_query_path:
943
 * @fd: The file descriptor to query.
944
 * @error: A [type@GLib.Error] for error reporting, or `NULL` to ignore.
945
 *
946
 * Queries the file path for the given FD opened by the current process.
947
 *
948
 * Returns: (transfer full): The file path, or `NULL` on error
949
 * Since: 2.88
950
 */
951
char *
952
g_unix_fd_query_path (int      fd,
953
                      GError **error)
954
0
{
955
0
#if defined(__linux__) || defined(__sun) || defined(_AIX)
956
0
  char *path;
957
0
  char *proc_path;
958
959
#ifdef __sun
960
  proc_path = g_strdup_printf ("/proc/self/path/%d", fd);
961
#elif _AIX
962
  proc_path = g_strdup_printf ("/proc/%ld/fd/%d", (long) getpid (), fd);
963
#else
964
0
  proc_path = g_strdup_printf ("/proc/self/fd/%d", fd);
965
0
#endif
966
0
  path = g_file_read_link (proc_path, error);
967
0
  g_free (proc_path);
968
969
0
  return g_steal_pointer (&path);
970
#elif defined (__FreeBSD__) || defined(__DragonFly__)
971
  struct kinfo_file kf = {0};
972
973
  kf.kf_structsize = sizeof (kf);
974
  if (fcntl (fd, F_KINFO, &kf) < 0)
975
    {
976
      int errsv = errno;
977
978
      g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errsv),
979
                   "Error querying file information for FD %d: %s",
980
                   fd, g_strerror (errsv));
981
      return NULL;
982
    }
983
984
  return g_strdup (kf.kf_path);
985
#elif defined (__APPLE__) || defined (__NetBSD__) || defined (__OpenBSD__)
986
  char file_path[MAXPATHLEN] = {0};
987
988
  if (fcntl (fd, F_GETPATH, file_path) < 0)
989
    {
990
      int errsv = errno;
991
992
      g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errsv),
993
                   "Error querying file information for FD %d: %s",
994
                   fd, g_strerror (errsv));
995
      return NULL;
996
    }
997
998
  return g_strdup (file_path);
999
#elif defined (__GNU__)
1000
  /*
1001
   * Hurd allows to open("/dev/fd/%u") to open the very same fd, but it's not
1002
   * possible to get the file name from it, see:
1003
   * - https://gitlab.gnome.org/GNOME/glib/-/merge_requests/4396#note_2279923
1004
   * - https://gitlab.gnome.org/GNOME/glib/-/commit/8c3fda5c8d3
1005
   */
1006
  g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_NOSYS,
1007
               "g_unix_fd_query_path() not supported on HURD");
1008
  return NULL;
1009
#else
1010
  #error "g_unix_fd_query_path() not supported on this platform"
1011
#endif
1012
0
}