Branch data Line data Source code
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 : 7 : G_DEFINE_QUARK (g-unix-error-quark, g_unix_error)
92 : :
93 : : static gboolean
94 : 3 : g_unix_set_error_from_errno (GError **error,
95 : : gint saved_errno)
96 : : {
97 : 3 : g_set_error_literal (error,
98 : : G_UNIX_ERROR,
99 : : 0,
100 : : g_strerror (saved_errno));
101 : 3 : errno = saved_errno;
102 : 3 : return FALSE;
103 : : }
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 : 2980 : g_unix_open_pipe (int *fds,
137 : : int flags,
138 : : GError **error)
139 : : {
140 : : /* We only support O_CLOEXEC/FD_CLOEXEC and O_NONBLOCK */
141 : 2980 : g_return_val_if_fail ((flags & (O_CLOEXEC | FD_CLOEXEC | O_NONBLOCK)) == flags, FALSE);
142 : :
143 : : #if O_CLOEXEC != FD_CLOEXEC && !defined(G_DISABLE_CHECKS)
144 : 2980 : if (flags & FD_CLOEXEC)
145 : 1 : g_debug ("g_unix_open_pipe() called with FD_CLOEXEC; please migrate to using O_CLOEXEC instead");
146 : : #endif
147 : :
148 : 2980 : if (!g_unix_open_pipe_internal (fds,
149 : 2980 : (flags & (O_CLOEXEC | FD_CLOEXEC)) != 0,
150 : 2980 : (flags & O_NONBLOCK) != 0))
151 : 0 : return g_unix_set_error_from_errno (error, errno);
152 : :
153 : 2980 : return TRUE;
154 : : }
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 : 504 : g_unix_set_fd_nonblocking (gint fd,
172 : : gboolean nonblock,
173 : : GError **error)
174 : : {
175 : : #ifdef F_GETFL
176 : : glong fcntl_flags;
177 : 504 : fcntl_flags = fcntl (fd, F_GETFL);
178 : :
179 : 504 : if (fcntl_flags == -1)
180 : 1 : return g_unix_set_error_from_errno (error, errno);
181 : :
182 : 503 : if (nonblock)
183 : 502 : fcntl_flags |= O_NONBLOCK;
184 : : else
185 : 1 : fcntl_flags &= ~O_NONBLOCK;
186 : :
187 : 503 : if (fcntl (fd, F_SETFL, fcntl_flags) == -1)
188 : 0 : return g_unix_set_error_from_errno (error, errno);
189 : 503 : return TRUE;
190 : : #else
191 : : return g_unix_set_error_from_errno (error, EINVAL);
192 : : #endif
193 : : }
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 : 32 : g_unix_signal_source_new (int signum)
229 : : {
230 : 32 : g_return_val_if_fail (signum == SIGHUP || signum == SIGINT || signum == SIGTERM ||
231 : : signum == SIGUSR1 || signum == SIGUSR2 || signum == SIGWINCH,
232 : : NULL);
233 : :
234 : 32 : return _g_main_create_unix_signal_watch (signum);
235 : : }
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 : 29 : g_unix_signal_add_full (int priority,
256 : : int signum,
257 : : GSourceFunc handler,
258 : : gpointer user_data,
259 : : GDestroyNotify notify)
260 : : {
261 : : guint id;
262 : : GSource *source;
263 : :
264 : 29 : source = g_unix_signal_source_new (signum);
265 : :
266 : 29 : if (priority != G_PRIORITY_DEFAULT)
267 : 0 : g_source_set_priority (source, priority);
268 : :
269 : 29 : g_source_set_callback (source, handler, user_data, notify);
270 : 29 : id = g_source_attach (source, NULL);
271 : 29 : g_source_unref (source);
272 : :
273 : 29 : return id;
274 : : }
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 : 29 : g_unix_signal_add (int signum,
292 : : GSourceFunc handler,
293 : : gpointer user_data)
294 : : {
295 : 29 : return g_unix_signal_add_full (G_PRIORITY_DEFAULT, signum, handler, user_data, NULL);
296 : : }
297 : :
298 : : typedef struct
299 : : {
300 : : GSource source;
301 : :
302 : : gint fd;
303 : : gpointer tag;
304 : : } GUnixFDSource;
305 : :
306 : : static gboolean
307 : 262485 : g_unix_fd_source_dispatch (GSource *source,
308 : : GSourceFunc callback,
309 : : gpointer user_data)
310 : : {
311 : 262485 : GUnixFDSource *fd_source = (GUnixFDSource *) source;
312 : 262485 : GUnixFDSourceFunc func = (GUnixFDSourceFunc) callback;
313 : :
314 : 262485 : if (!callback)
315 : : {
316 : 1 : g_warning ("GUnixFDSource dispatched without callback. "
317 : : "You must call g_source_set_callback().");
318 : 1 : return FALSE;
319 : : }
320 : :
321 : 262484 : return (* func) (fd_source->fd, g_source_query_unix_fd (source, fd_source->tag), user_data);
322 : : }
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 : 471 : g_unix_fd_source_new (gint fd,
347 : : GIOCondition condition)
348 : : {
349 : : GUnixFDSource *fd_source;
350 : : GSource *source;
351 : :
352 : 471 : source = g_source_new (&g_unix_fd_source_funcs, sizeof (GUnixFDSource));
353 : 471 : fd_source = (GUnixFDSource *) source;
354 : :
355 : 471 : fd_source->fd = fd;
356 : 471 : fd_source->tag = g_source_add_unix_fd (source, fd, condition);
357 : :
358 : 471 : return source;
359 : : }
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 : 2 : g_unix_fd_add_full (gint priority,
383 : : gint fd,
384 : : GIOCondition condition,
385 : : GUnixFDSourceFunc function,
386 : : gpointer user_data,
387 : : GDestroyNotify notify)
388 : : {
389 : : GSource *source;
390 : : guint id;
391 : :
392 : 2 : g_return_val_if_fail (function != NULL, 0);
393 : :
394 : 2 : source = g_unix_fd_source_new (fd, condition);
395 : :
396 : 2 : if (priority != G_PRIORITY_DEFAULT)
397 : 1 : g_source_set_priority (source, priority);
398 : :
399 : 2 : g_source_set_callback (source, (GSourceFunc) function, user_data, notify);
400 : 2 : id = g_source_attach (source, NULL);
401 : 2 : g_source_unref (source);
402 : :
403 : 2 : return id;
404 : : }
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 : 1 : g_unix_fd_add (gint fd,
433 : : GIOCondition condition,
434 : : GUnixFDSourceFunc function,
435 : : gpointer user_data)
436 : : {
437 : 1 : return g_unix_fd_add_full (G_PRIORITY_DEFAULT, fd, condition, function, user_data, NULL);
438 : : }
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 : 3 : g_unix_get_passwd_entry (const gchar *user_name,
463 : : GError **error)
464 : : {
465 : : struct passwd *passwd_file_entry;
466 : : struct
467 : : {
468 : : struct passwd pwd;
469 : : char string_buffer[];
470 : 3 : } *buffer = NULL;
471 : 3 : gsize string_buffer_size = 0;
472 : 3 : GError *local_error = NULL;
473 : :
474 : 3 : g_return_val_if_fail (user_name != NULL, NULL);
475 : 3 : g_return_val_if_fail (error == NULL || *error == NULL, NULL);
476 : :
477 : : #ifdef _SC_GETPW_R_SIZE_MAX
478 : : {
479 : : /* Get the recommended buffer size */
480 : 3 : glong string_buffer_size_long = sysconf (_SC_GETPW_R_SIZE_MAX);
481 : 3 : if (string_buffer_size_long > 0)
482 : 3 : string_buffer_size = string_buffer_size_long;
483 : : }
484 : : #endif /* _SC_GETPW_R_SIZE_MAX */
485 : :
486 : : /* Default starting size. */
487 : 3 : if (string_buffer_size == 0)
488 : 0 : string_buffer_size = 64;
489 : :
490 : : do
491 : : {
492 : : int retval;
493 : :
494 : 3 : 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 : 3 : buffer = g_malloc0 (sizeof (*buffer) + string_buffer_size + 6);
501 : :
502 : 3 : retval = getpwnam_r (user_name, &buffer->pwd, buffer->string_buffer,
503 : : 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 : 3 : if (passwd_file_entry != NULL)
510 : : {
511 : : /* Success. */
512 : 1 : break;
513 : : }
514 : 2 : else if (retval == 0 ||
515 : 0 : retval == ENOENT || retval == ESRCH ||
516 : 0 : retval == EBADF || retval == EPERM)
517 : : {
518 : : /* Username not found. */
519 : 2 : g_unix_set_error_from_errno (&local_error, retval);
520 : 2 : break;
521 : : }
522 : 0 : else if (retval == ERANGE)
523 : : {
524 : : /* Can’t allocate enough string buffer space. */
525 : 0 : if (string_buffer_size > 32 * 1024)
526 : : {
527 : 0 : g_unix_set_error_from_errno (&local_error, retval);
528 : 0 : break;
529 : : }
530 : :
531 : 0 : string_buffer_size *= 2;
532 : 0 : continue;
533 : : }
534 : : else
535 : : {
536 : 0 : g_unix_set_error_from_errno (&local_error, retval);
537 : 0 : break;
538 : : }
539 : : }
540 : 0 : while (passwd_file_entry == NULL);
541 : :
542 : 3 : g_assert (passwd_file_entry == NULL ||
543 : : (gpointer) passwd_file_entry == (gpointer) buffer);
544 : :
545 : : /* Success or error. */
546 : 3 : if (local_error != NULL)
547 : : {
548 : 2 : g_clear_pointer (&buffer, g_free);
549 : 2 : g_propagate_error (error, g_steal_pointer (&local_error));
550 : : }
551 : :
552 : 3 : return (struct passwd *) g_steal_pointer (&buffer);
553 : : }
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 : 0 : set_cloexec (void *data, gint fd)
559 : : {
560 : 0 : if (fd >= GPOINTER_TO_INT (data))
561 : 0 : fcntl (fd, F_SETFD, FD_CLOEXEC);
562 : :
563 : 0 : return 0;
564 : : }
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 : 0 : close_func_with_invalid_fds (void *data, int fd)
577 : : {
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 : : }
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 : 0 : filename_to_fd (const char *p)
609 : : {
610 : : 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 : : {
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 : : }
630 : :
631 : 0 : return fd;
632 : : }
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 : 0 : safe_fdwalk (int (*cb)(void *data, int fd), void *data)
641 : : {
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 : : #ifdef __linux__
657 : : 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 : : {
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 : : union
668 : : {
669 : : char buf[4096];
670 : : struct linux_dirent64 alignment;
671 : : } u;
672 : : int pos, nread;
673 : : struct linux_dirent64 *de;
674 : :
675 : 0 : while ((nread = syscall (SYS_getdents64, dir_fd, u.buf, sizeof (u.buf))) > 0)
676 : : {
677 : 0 : for (pos = 0; pos < nread; pos += de->d_reclen)
678 : : {
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 : : }
688 : : }
689 : :
690 : 0 : g_close (dir_fd, NULL);
691 : 0 : return res;
692 : : }
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 : : #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 : : #endif
728 : : }
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 : 0 : safe_fdwalk_with_invalid_fds (int (*cb)(void *data, int fd), void *data)
734 : : {
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 : : 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 : : }
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 : 9 : g_fdwalk_set_cloexec (int lowfd)
836 : : {
837 : : int ret;
838 : :
839 : 9 : 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 : 8 : ret = close_range (lowfd, G_MAXUINT, CLOSE_RANGE_CLOEXEC);
853 : 8 : if (ret == 0 || !(errno == ENOSYS || errno == EINVAL))
854 : 8 : 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 : : }
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 : 991 : g_closefrom (int lowfd)
887 : : {
888 : : int ret;
889 : :
890 : 991 : 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 : 990 : ret = close_range (lowfd, G_MAXUINT, 0);
900 : 990 : if (ret == 0 || errno != ENOSYS)
901 : 990 : 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 : : #endif
939 : : }
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 : 14 : g_unix_fd_query_path (int fd,
953 : : GError **error)
954 : : {
955 : : #if defined(__linux__) || defined(__sun) || defined(_AIX) || defined (__CYGWIN__)
956 : : char *path;
957 : : 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 : 14 : proc_path = g_strdup_printf ("/proc/self/fd/%d", fd);
965 : : #endif
966 : 14 : path = g_file_read_link (proc_path, error);
967 : 14 : g_free (proc_path);
968 : :
969 : 14 : 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 : : }
|