1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 2011 Red Hat, Inc.
4 * glib-unix.c: UNIX specific API wrappers and convenience functions
6 * SPDX-License-Identifier: LGPL-2.1-or-later
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Authors: Colin Walters <walters@verbum.org>
26 #include "glib-unix.h"
27 #include "glib-unixprivate.h"
28 #include "gmain-internal.h"
31 #include <sys/types.h>
34 G_STATIC_ASSERT (sizeof (ssize_t) == GLIB_SIZEOF_SSIZE_T);
35 G_STATIC_ASSERT (G_ALIGNOF (gssize) == G_ALIGNOF (ssize_t));
37 G_STATIC_ASSERT (sizeof (GPid) == sizeof (pid_t));
38 G_STATIC_ASSERT (G_ALIGNOF (GPid) == G_ALIGNOF (pid_t));
40 /* If this assertion fails, then the ABI of g_unix_open_pipe() would be
41 * ambiguous on this platform.
42 * On Linux, usually O_NONBLOCK == 04000 and FD_CLOEXEC == 1, but the same
43 * might not be true everywhere. */
44 G_STATIC_ASSERT (O_NONBLOCK != FD_CLOEXEC);
48 * @title: UNIX-specific utilities and integration
49 * @short_description: pipes, signal handling
50 * @include: glib-unix.h
52 * Most of GLib is intended to be portable; in contrast, this set of
53 * functions is designed for programs which explicitly target UNIX,
54 * or are using it to build higher level abstractions which would be
55 * conditionally compiled if the platform matches %G_OS_UNIX.
57 * To use these functions, you must explicitly include the
58 * "glib-unix.h" header.
61 G_DEFINE_QUARK (g-unix-error-quark, g_unix_error)
64 g_unix_set_error_from_errno (GError **error,
67 g_set_error_literal (error,
70 g_strerror (saved_errno));
77 * @fds: (array fixed-size=2): Array of two integers
78 * @flags: Bitfield of file descriptor flags, as for fcntl()
81 * Similar to the UNIX pipe() call, but on modern systems like Linux
82 * uses the pipe2() system call, which atomically creates a pipe with
83 * the configured flags.
85 * As of GLib 2.78, the supported flags are `O_CLOEXEC`/`FD_CLOEXEC` (see below)
86 * and `O_NONBLOCK`. Prior to GLib 2.78, only `FD_CLOEXEC` was supported — if
87 * you wanted to configure `O_NONBLOCK` then that had to be done separately with
90 * It is a programmer error to call this function with unsupported flags, and a
91 * critical warning will be raised.
93 * As of GLib 2.78, it is preferred to pass `O_CLOEXEC` in, rather than
94 * `FD_CLOEXEC`, as that matches the underlying `pipe()` API more closely. Prior
95 * to 2.78, only `FD_CLOEXEC` was supported. Support for `FD_CLOEXEC` may be
96 * deprecated and removed in future.
98 * Returns: %TRUE on success, %FALSE if not (and errno will be set).
103 g_unix_open_pipe (int *fds,
107 /* We only support O_CLOEXEC/FD_CLOEXEC and O_NONBLOCK */
108 g_return_val_if_fail ((flags & (O_CLOEXEC | FD_CLOEXEC | O_NONBLOCK)) == flags, FALSE);
110 #if O_CLOEXEC != FD_CLOEXEC && !defined(G_DISABLE_CHECKS)
111 if (flags & FD_CLOEXEC)
112 g_debug ("g_unix_open_pipe() called with FD_CLOEXEC; please migrate to using O_CLOEXEC instead");
115 if (!g_unix_open_pipe_internal (fds,
116 (flags & (O_CLOEXEC | FD_CLOEXEC)) != 0,
117 (flags & O_NONBLOCK) != 0))
118 return g_unix_set_error_from_errno (error, errno);
124 * g_unix_set_fd_nonblocking:
125 * @fd: A file descriptor
126 * @nonblock: If %TRUE, set the descriptor to be non-blocking
129 * Control the non-blocking state of the given file descriptor,
130 * according to @nonblock. On most systems this uses %O_NONBLOCK, but
131 * on some older ones may use %O_NDELAY.
133 * Returns: %TRUE if successful
138 g_unix_set_fd_nonblocking (gint fd,
144 fcntl_flags = fcntl (fd, F_GETFL);
146 if (fcntl_flags == -1)
147 return g_unix_set_error_from_errno (error, errno);
150 fcntl_flags |= O_NONBLOCK;
152 fcntl_flags &= ~O_NONBLOCK;
154 if (fcntl (fd, F_SETFL, fcntl_flags) == -1)
155 return g_unix_set_error_from_errno (error, errno);
158 return g_unix_set_error_from_errno (error, EINVAL);
163 * g_unix_signal_source_new:
164 * @signum: A signal number
166 * Create a #GSource that will be dispatched upon delivery of the UNIX
167 * signal @signum. In GLib versions before 2.36, only `SIGHUP`, `SIGINT`,
168 * `SIGTERM` can be monitored. In GLib 2.36, `SIGUSR1` and `SIGUSR2`
169 * were added. In GLib 2.54, `SIGWINCH` was added.
171 * Note that unlike the UNIX default, all sources which have created a
172 * watch will be dispatched, regardless of which underlying thread
173 * invoked g_unix_signal_source_new().
175 * For example, an effective use of this function is to handle `SIGTERM`
176 * cleanly; flushing any outstanding files, and then calling
177 * g_main_loop_quit(). It is not safe to do any of this from a regular
178 * UNIX signal handler; such a handler may be invoked while malloc() or
179 * another library function is running, causing reentrancy issues if the
180 * handler attempts to use those functions. None of the GLib/GObject
181 * API is safe against this kind of reentrancy.
183 * The interaction of this source when combined with native UNIX
184 * functions like sigprocmask() is not defined.
186 * The source will not initially be associated with any #GMainContext
187 * and must be added to one with g_source_attach() before it will be
190 * Returns: A newly created #GSource
195 g_unix_signal_source_new (int signum)
197 g_return_val_if_fail (signum == SIGHUP || signum == SIGINT || signum == SIGTERM ||
198 signum == SIGUSR1 || signum == SIGUSR2 || signum == SIGWINCH,
201 return _g_main_create_unix_signal_watch (signum);
205 * g_unix_signal_add_full: (rename-to g_unix_signal_add)
206 * @priority: the priority of the signal source. Typically this will be in
207 * the range between %G_PRIORITY_DEFAULT and %G_PRIORITY_HIGH.
208 * @signum: Signal number
210 * @user_data: Data for @handler
211 * @notify: #GDestroyNotify for @handler
213 * A convenience function for g_unix_signal_source_new(), which
214 * attaches to the default #GMainContext. You can remove the watch
215 * using g_source_remove().
217 * Returns: An ID (greater than 0) for the event source
222 g_unix_signal_add_full (int priority,
226 GDestroyNotify notify)
231 source = g_unix_signal_source_new (signum);
233 if (priority != G_PRIORITY_DEFAULT)
234 g_source_set_priority (source, priority);
236 g_source_set_callback (source, handler, user_data, notify);
237 id = g_source_attach (source, NULL);
238 g_source_unref (source);
245 * @signum: Signal number
247 * @user_data: Data for @handler
249 * A convenience function for g_unix_signal_source_new(), which
250 * attaches to the default #GMainContext. You can remove the watch
251 * using g_source_remove().
253 * Returns: An ID (greater than 0) for the event source
258 g_unix_signal_add (int signum,
262 return g_unix_signal_add_full (G_PRIORITY_DEFAULT, signum, handler, user_data, NULL);
274 g_unix_fd_source_dispatch (GSource *source,
275 GSourceFunc callback,
278 GUnixFDSource *fd_source = (GUnixFDSource *) source;
279 GUnixFDSourceFunc func = (GUnixFDSourceFunc) callback;
283 g_warning ("GUnixFDSource dispatched without callback. "
284 "You must call g_source_set_callback().");
288 return (* func) (fd_source->fd, g_source_query_unix_fd (source, fd_source->tag), user_data);
291 GSourceFuncs g_unix_fd_source_funcs = {
292 NULL, NULL, g_unix_fd_source_dispatch, NULL, NULL, NULL
296 * g_unix_fd_source_new:
297 * @fd: a file descriptor
298 * @condition: I/O conditions to watch for on @fd
300 * Creates a #GSource to watch for a particular I/O condition on a file
303 * The source will never close the @fd — you must do it yourself.
305 * Any callback attached to the returned #GSource must have type
306 * #GUnixFDSourceFunc.
308 * Returns: the newly created #GSource
313 g_unix_fd_source_new (gint fd,
314 GIOCondition condition)
316 GUnixFDSource *fd_source;
319 source = g_source_new (&g_unix_fd_source_funcs, sizeof (GUnixFDSource));
320 fd_source = (GUnixFDSource *) source;
323 fd_source->tag = g_source_add_unix_fd (source, fd, condition);
329 * g_unix_fd_add_full:
330 * @priority: the priority of the source
331 * @fd: a file descriptor
332 * @condition: IO conditions to watch for on @fd
333 * @function: a #GUnixFDSourceFunc
334 * @user_data: data to pass to @function
335 * @notify: function to call when the idle is removed, or %NULL
337 * Sets a function to be called when the IO condition, as specified by
338 * @condition becomes true for @fd.
340 * This is the same as g_unix_fd_add(), except that it allows you to
341 * specify a non-default priority and a provide a #GDestroyNotify for
344 * Returns: the ID (greater than 0) of the event source
349 g_unix_fd_add_full (gint priority,
351 GIOCondition condition,
352 GUnixFDSourceFunc function,
354 GDestroyNotify notify)
359 g_return_val_if_fail (function != NULL, 0);
361 source = g_unix_fd_source_new (fd, condition);
363 if (priority != G_PRIORITY_DEFAULT)
364 g_source_set_priority (source, priority);
366 g_source_set_callback (source, (GSourceFunc) function, user_data, notify);
367 id = g_source_attach (source, NULL);
368 g_source_unref (source);
375 * @fd: a file descriptor
376 * @condition: IO conditions to watch for on @fd
377 * @function: a #GUnixFDSourceFunc
378 * @user_data: data to pass to @function
380 * Sets a function to be called when the IO condition, as specified by
381 * @condition becomes true for @fd.
383 * @function will be called when the specified IO condition becomes
384 * %TRUE. The function is expected to clear whatever event caused the
385 * IO condition to become true and return %TRUE in order to be notified
386 * when it happens again. If @function returns %FALSE then the watch
389 * The return value of this function can be passed to g_source_remove()
390 * to cancel the watch at any time that it exists.
392 * The source will never close the fd -- you must do it yourself.
394 * Returns: the ID (greater than 0) of the event source
399 g_unix_fd_add (gint fd,
400 GIOCondition condition,
401 GUnixFDSourceFunc function,
404 return g_unix_fd_add_full (G_PRIORITY_DEFAULT, fd, condition, function, user_data, NULL);
408 * g_unix_get_passwd_entry:
409 * @user_name: the username to get the passwd file entry for
410 * @error: return location for a #GError, or %NULL
412 * Get the `passwd` file entry for the given @user_name using `getpwnam_r()`.
413 * This can fail if the given @user_name doesn’t exist.
415 * The returned `struct passwd` has been allocated using g_malloc() and should
416 * be freed using g_free(). The strings referenced by the returned struct are
417 * included in the same allocation, so are valid until the `struct passwd` is
420 * This function is safe to call from multiple threads concurrently.
422 * You will need to include `pwd.h` to get the definition of `struct passwd`.
424 * Returns: (transfer full): passwd entry, or %NULL on error; free the returned
425 * value with g_free()
429 g_unix_get_passwd_entry (const gchar *user_name,
432 struct passwd *passwd_file_entry;
436 char string_buffer[];
438 gsize string_buffer_size = 0;
439 GError *local_error = NULL;
441 g_return_val_if_fail (user_name != NULL, NULL);
442 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
444 #ifdef _SC_GETPW_R_SIZE_MAX
446 /* Get the recommended buffer size */
447 glong string_buffer_size_long = sysconf (_SC_GETPW_R_SIZE_MAX);
448 if (string_buffer_size_long > 0)
449 string_buffer_size = string_buffer_size_long;
451 #endif /* _SC_GETPW_R_SIZE_MAX */
453 /* Default starting size. */
454 if (string_buffer_size == 0)
455 string_buffer_size = 64;
462 /* Allocate space for the `struct passwd`, and then a buffer for all its
463 * strings (whose size is @string_buffer_size, which increases in this
464 * loop until it’s big enough). Add 6 extra bytes to work around a bug in
465 * macOS < 10.3. See #156446.
467 buffer = g_malloc0 (sizeof (*buffer) + string_buffer_size + 6);
469 retval = getpwnam_r (user_name, &buffer->pwd, buffer->string_buffer,
470 string_buffer_size, &passwd_file_entry);
472 /* Bail out if: the lookup was successful, or if the user id can't be
473 * found (should be pretty rare case actually), or if the buffer should be
474 * big enough and yet lookups are still not successful.
476 if (passwd_file_entry != NULL)
481 else if (retval == 0 ||
482 retval == ENOENT || retval == ESRCH ||
483 retval == EBADF || retval == EPERM)
485 /* Username not found. */
486 g_unix_set_error_from_errno (&local_error, retval);
489 else if (retval == ERANGE)
491 /* Can’t allocate enough string buffer space. */
492 if (string_buffer_size > 32 * 1024)
494 g_unix_set_error_from_errno (&local_error, retval);
498 string_buffer_size *= 2;
503 g_unix_set_error_from_errno (&local_error, retval);
507 while (passwd_file_entry == NULL);
509 g_assert (passwd_file_entry == NULL ||
510 (gpointer) passwd_file_entry == (gpointer) buffer);
512 /* Success or error. */
513 if (local_error != NULL)
515 g_clear_pointer (&buffer, g_free);
516 g_propagate_error (error, g_steal_pointer (&local_error));
519 return (struct passwd *) g_steal_pointer (&buffer);