gkdbus: Fix underflow and unreachable code bug
[platform/upstream/glib.git] / glib / glib-unix.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 2011 Red Hat, Inc.
3  *
4  * glib-unix.c: UNIX specific API wrappers and convenience functions
5  *
6  * SPDX-License-Identifier: LGPL-2.1-or-later
7  *
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.
12  *
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.
17  *
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/>.
20  *
21  * Authors: Colin Walters <walters@verbum.org>
22  */
23
24 #include "config.h"
25
26 #include "glib-unix.h"
27 #include "glib-unixprivate.h"
28 #include "gmain-internal.h"
29
30 #include <string.h>
31 #include <sys/types.h>
32 #include <pwd.h>
33
34 G_STATIC_ASSERT (sizeof (ssize_t) == GLIB_SIZEOF_SSIZE_T);
35 G_STATIC_ASSERT (G_ALIGNOF (gssize) == G_ALIGNOF (ssize_t));
36
37 G_STATIC_ASSERT (sizeof (GPid) == sizeof (pid_t));
38 G_STATIC_ASSERT (G_ALIGNOF (GPid) == G_ALIGNOF (pid_t));
39
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);
45
46 /**
47  * SECTION:gunix
48  * @title: UNIX-specific utilities and integration
49  * @short_description: pipes, signal handling
50  * @include: glib-unix.h
51  *
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.
56  *
57  * To use these functions, you must explicitly include the
58  * "glib-unix.h" header.
59  */
60
61 G_DEFINE_QUARK (g-unix-error-quark, g_unix_error)
62
63 static gboolean
64 g_unix_set_error_from_errno (GError **error,
65                              gint     saved_errno)
66 {
67   g_set_error_literal (error,
68                        G_UNIX_ERROR,
69                        0,
70                        g_strerror (saved_errno));
71   errno = saved_errno;
72   return FALSE;
73 }
74
75 /**
76  * g_unix_open_pipe:
77  * @fds: (array fixed-size=2): Array of two integers
78  * @flags: Bitfield of file descriptor flags, as for fcntl()
79  * @error: a #GError
80  *
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.
84  *
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
88  * `fcntl()`.
89  *
90  * It is a programmer error to call this function with unsupported flags, and a
91  * critical warning will be raised.
92  *
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.
97  *
98  * Returns: %TRUE on success, %FALSE if not (and errno will be set).
99  *
100  * Since: 2.30
101  */
102 gboolean
103 g_unix_open_pipe (int     *fds,
104                   int      flags,
105                   GError **error)
106 {
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);
109
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");
113 #endif
114
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);
119
120   return TRUE;
121 }
122
123 /**
124  * g_unix_set_fd_nonblocking:
125  * @fd: A file descriptor
126  * @nonblock: If %TRUE, set the descriptor to be non-blocking
127  * @error: a #GError
128  *
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.
132  *
133  * Returns: %TRUE if successful
134  *
135  * Since: 2.30
136  */
137 gboolean
138 g_unix_set_fd_nonblocking (gint       fd,
139                            gboolean   nonblock,
140                            GError   **error)
141 {
142 #ifdef F_GETFL
143   glong fcntl_flags;
144   fcntl_flags = fcntl (fd, F_GETFL);
145
146   if (fcntl_flags == -1)
147     return g_unix_set_error_from_errno (error, errno);
148
149   if (nonblock)
150     fcntl_flags |= O_NONBLOCK;
151   else
152     fcntl_flags &= ~O_NONBLOCK;
153
154   if (fcntl (fd, F_SETFL, fcntl_flags) == -1)
155     return g_unix_set_error_from_errno (error, errno);
156   return TRUE;
157 #else
158   return g_unix_set_error_from_errno (error, EINVAL);
159 #endif
160 }
161
162 /**
163  * g_unix_signal_source_new:
164  * @signum: A signal number
165  *
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.
170  *
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().
174  *
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.
182  *
183  * The interaction of this source when combined with native UNIX
184  * functions like sigprocmask() is not defined.
185  *
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
188  * executed.
189  *
190  * Returns: A newly created #GSource
191  *
192  * Since: 2.30
193  */
194 GSource *
195 g_unix_signal_source_new (int signum)
196 {
197   g_return_val_if_fail (signum == SIGHUP || signum == SIGINT || signum == SIGTERM ||
198                         signum == SIGUSR1 || signum == SIGUSR2 || signum == SIGWINCH,
199                         NULL);
200
201   return _g_main_create_unix_signal_watch (signum);
202 }
203
204 /**
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
209  * @handler: Callback
210  * @user_data: Data for @handler
211  * @notify: #GDestroyNotify for @handler
212  *
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().
216  *
217  * Returns: An ID (greater than 0) for the event source
218  *
219  * Since: 2.30
220  */
221 guint
222 g_unix_signal_add_full (int            priority,
223                         int            signum,
224                         GSourceFunc    handler,
225                         gpointer       user_data,
226                         GDestroyNotify notify)
227 {
228   guint id;
229   GSource *source;
230
231   source = g_unix_signal_source_new (signum);
232
233   if (priority != G_PRIORITY_DEFAULT)
234     g_source_set_priority (source, priority);
235
236   g_source_set_callback (source, handler, user_data, notify);
237   id = g_source_attach (source, NULL);
238   g_source_unref (source);
239
240   return id;
241 }
242
243 /**
244  * g_unix_signal_add:
245  * @signum: Signal number
246  * @handler: Callback
247  * @user_data: Data for @handler
248  *
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().
252  *
253  * Returns: An ID (greater than 0) for the event source
254  *
255  * Since: 2.30
256  */
257 guint
258 g_unix_signal_add (int         signum,
259                    GSourceFunc handler,
260                    gpointer    user_data)
261 {
262   return g_unix_signal_add_full (G_PRIORITY_DEFAULT, signum, handler, user_data, NULL);
263 }
264
265 typedef struct
266 {
267   GSource source;
268
269   gint     fd;
270   gpointer tag;
271 } GUnixFDSource;
272
273 static gboolean
274 g_unix_fd_source_dispatch (GSource     *source,
275                            GSourceFunc  callback,
276                            gpointer     user_data)
277 {
278   GUnixFDSource *fd_source = (GUnixFDSource *) source;
279   GUnixFDSourceFunc func = (GUnixFDSourceFunc) callback;
280
281   if (!callback)
282     {
283       g_warning ("GUnixFDSource dispatched without callback. "
284                  "You must call g_source_set_callback().");
285       return FALSE;
286     }
287
288   return (* func) (fd_source->fd, g_source_query_unix_fd (source, fd_source->tag), user_data);
289 }
290
291 GSourceFuncs g_unix_fd_source_funcs = {
292   NULL, NULL, g_unix_fd_source_dispatch, NULL, NULL, NULL
293 };
294
295 /**
296  * g_unix_fd_source_new:
297  * @fd: a file descriptor
298  * @condition: I/O conditions to watch for on @fd
299  *
300  * Creates a #GSource to watch for a particular I/O condition on a file
301  * descriptor.
302  *
303  * The source will never close the @fd — you must do it yourself.
304  *
305  * Any callback attached to the returned #GSource must have type
306  * #GUnixFDSourceFunc.
307  *
308  * Returns: the newly created #GSource
309  *
310  * Since: 2.36
311  **/
312 GSource *
313 g_unix_fd_source_new (gint         fd,
314                       GIOCondition condition)
315 {
316   GUnixFDSource *fd_source;
317   GSource *source;
318
319   source = g_source_new (&g_unix_fd_source_funcs, sizeof (GUnixFDSource));
320   fd_source = (GUnixFDSource *) source;
321
322   fd_source->fd = fd;
323   fd_source->tag = g_source_add_unix_fd (source, fd, condition);
324
325   return source;
326 }
327
328 /**
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
336  *
337  * Sets a function to be called when the IO condition, as specified by
338  * @condition becomes true for @fd.
339  *
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
342  * @user_data.
343  *
344  * Returns: the ID (greater than 0) of the event source
345  *
346  * Since: 2.36
347  **/
348 guint
349 g_unix_fd_add_full (gint              priority,
350                     gint              fd,
351                     GIOCondition      condition,
352                     GUnixFDSourceFunc function,
353                     gpointer          user_data,
354                     GDestroyNotify    notify)
355 {
356   GSource *source;
357   guint id;
358
359   g_return_val_if_fail (function != NULL, 0);
360
361   source = g_unix_fd_source_new (fd, condition);
362
363   if (priority != G_PRIORITY_DEFAULT)
364     g_source_set_priority (source, priority);
365
366   g_source_set_callback (source, (GSourceFunc) function, user_data, notify);
367   id = g_source_attach (source, NULL);
368   g_source_unref (source);
369
370   return id;
371 }
372
373 /**
374  * g_unix_fd_add:
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
379  *
380  * Sets a function to be called when the IO condition, as specified by
381  * @condition becomes true for @fd.
382  *
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
387  * will be cancelled.
388  *
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.
391  *
392  * The source will never close the fd -- you must do it yourself.
393  *
394  * Returns: the ID (greater than 0) of the event source
395  *
396  * Since: 2.36
397  **/
398 guint
399 g_unix_fd_add (gint              fd,
400                GIOCondition      condition,
401                GUnixFDSourceFunc function,
402                gpointer          user_data)
403 {
404   return g_unix_fd_add_full (G_PRIORITY_DEFAULT, fd, condition, function, user_data, NULL);
405 }
406
407 /**
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
411  *
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.
414  *
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
418  * freed.
419  *
420  * This function is safe to call from multiple threads concurrently.
421  *
422  * You will need to include `pwd.h` to get the definition of `struct passwd`.
423  *
424  * Returns: (transfer full): passwd entry, or %NULL on error; free the returned
425  *    value with g_free()
426  * Since: 2.64
427  */
428 struct passwd *
429 g_unix_get_passwd_entry (const gchar  *user_name,
430                          GError      **error)
431 {
432   struct passwd *passwd_file_entry;
433   struct
434     {
435       struct passwd pwd;
436       char string_buffer[];
437     } *buffer = NULL;
438   gsize string_buffer_size = 0;
439   GError *local_error = NULL;
440
441   g_return_val_if_fail (user_name != NULL, NULL);
442   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
443
444 #ifdef _SC_GETPW_R_SIZE_MAX
445     {
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;
450     }
451 #endif /* _SC_GETPW_R_SIZE_MAX */
452
453   /* Default starting size. */
454   if (string_buffer_size == 0)
455     string_buffer_size = 64;
456
457   do
458     {
459       int retval;
460
461       g_free (buffer);
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.
466        */
467       buffer = g_malloc0 (sizeof (*buffer) + string_buffer_size + 6);
468
469       retval = getpwnam_r (user_name, &buffer->pwd, buffer->string_buffer,
470                            string_buffer_size, &passwd_file_entry);
471
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.
475        */
476       if (passwd_file_entry != NULL)
477         {
478           /* Success. */
479           break;
480         }
481       else if (retval == 0 ||
482           retval == ENOENT || retval == ESRCH ||
483           retval == EBADF || retval == EPERM)
484         {
485           /* Username not found. */
486           g_unix_set_error_from_errno (&local_error, retval);
487           break;
488         }
489       else if (retval == ERANGE)
490         {
491           /* Can’t allocate enough string buffer space. */
492           if (string_buffer_size > 32 * 1024)
493             {
494               g_unix_set_error_from_errno (&local_error, retval);
495               break;
496             }
497
498           string_buffer_size *= 2;
499           continue;
500         }
501       else
502         {
503           g_unix_set_error_from_errno (&local_error, retval);
504           break;
505         }
506     }
507   while (passwd_file_entry == NULL);
508
509   g_assert (passwd_file_entry == NULL ||
510             (gpointer) passwd_file_entry == (gpointer) buffer);
511
512   /* Success or error. */
513   if (local_error != NULL)
514     {
515       g_clear_pointer (&buffer, g_free);
516       g_propagate_error (error, g_steal_pointer (&local_error));
517     }
518
519   return (struct passwd *) g_steal_pointer (&buffer);
520 }