[kdbus] KDBUS_ITEM_PAYLOAD_OFF items are (once again) relative to msg header
[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  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  *
19  * Authors: Colin Walters <walters@verbum.org>
20  */
21
22 #include "config.h"
23
24 /* To make bionic export pipe2() */
25 #ifndef _GNU_SOURCE
26 #define _GNU_SOURCE 1
27 #endif
28
29 #include "glib-unix.h"
30 #include "gmain-internal.h"
31
32 #include <string.h>
33
34 #include <fcntl.h>
35 #include <sys/syscall.h>
36 #include <unistd.h>
37
38 #ifdef __linux__
39
40 /* We want to support these features of Linux even when building GLib
41  * against older versions of system headers.  This will allow us to
42  * 'automatically' start supporting a particular feature when GLib is
43  * used with a newer kernel, without recompile.
44  *
45  * This means that we're not changing functionality of GLib simply based
46  * on the set of headers we happen to compile against...
47  */
48
49 #ifndef F_LINUX_SPECIFIC_BASE
50 #define F_LINUX_SPECIFIC_BASE 1024
51 #endif
52
53 #ifndef F_ADD_SEALS
54 #define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9)
55 #define F_GET_SEALS (F_LINUX_SPECIFIC_BASE + 10)
56
57 #define F_SEAL_SEAL     0x0001  /* prevent further seals from being set */
58 #define F_SEAL_SHRINK   0x0002  /* prevent file from shrinking */
59 #define F_SEAL_GROW     0x0004  /* prevent file from growing */
60 #define F_SEAL_WRITE    0x0008  /* prevent writes */
61 #endif
62
63 #endif
64
65 /**
66  * SECTION:gunix
67  * @title: UNIX-specific utilities and integration
68  * @short_description: pipes, signal handling
69  * @include: glib-unix.h
70  *
71  * Most of GLib is intended to be portable; in contrast, this set of
72  * functions is designed for programs which explicitly target UNIX,
73  * or are using it to build higher level abstractions which would be
74  * conditionally compiled if the platform matches G_OS_UNIX.
75  *
76  * To use these functions, you must explicitly include the
77  * "glib-unix.h" header.
78  */
79
80 G_DEFINE_QUARK (g-unix-error-quark, g_unix_error)
81
82 static gboolean
83 g_unix_set_error_from_errno (GError **error,
84                              gint     saved_errno)
85 {
86   g_set_error_literal (error,
87                        G_UNIX_ERROR,
88                        0,
89                        g_strerror (saved_errno));
90   errno = saved_errno;
91   return FALSE;
92 }
93
94 /**
95  * g_unix_open_pipe:
96  * @fds: Array of two integers
97  * @flags: Bitfield of file descriptor flags, as for fcntl()
98  * @error: a #GError
99  *
100  * Similar to the UNIX pipe() call, but on modern systems like Linux
101  * uses the pipe2() system call, which atomically creates a pipe with
102  * the configured flags. The only supported flag currently is
103  * %FD_CLOEXEC. If for example you want to configure %O_NONBLOCK, that
104  * must still be done separately with fcntl().
105  *
106  * This function does not take %O_CLOEXEC, it takes %FD_CLOEXEC as if
107  * for fcntl(); these are different on Linux/glibc.
108  *
109  * Returns: %TRUE on success, %FALSE if not (and errno will be set).
110  *
111  * Since: 2.30
112  */
113 gboolean
114 g_unix_open_pipe (int     *fds,
115                   int      flags,
116                   GError **error)
117 {
118   int ecode;
119
120   /* We only support FD_CLOEXEC */
121   g_return_val_if_fail ((flags & (FD_CLOEXEC)) == flags, FALSE);
122
123 #ifdef HAVE_PIPE2
124   {
125     int pipe2_flags = 0;
126     if (flags & FD_CLOEXEC)
127       pipe2_flags |= O_CLOEXEC;
128     /* Atomic */
129     ecode = pipe2 (fds, pipe2_flags);
130     if (ecode == -1 && errno != ENOSYS)
131       return g_unix_set_error_from_errno (error, errno);
132     else if (ecode == 0)
133       return TRUE;
134     /* Fall through on -ENOSYS, we must be running on an old kernel */
135   }
136 #endif
137   ecode = pipe (fds);
138   if (ecode == -1)
139     return g_unix_set_error_from_errno (error, errno);
140
141   if (flags == 0)
142     return TRUE;
143
144   ecode = fcntl (fds[0], F_SETFD, flags);
145   if (ecode == -1)
146     {
147       int saved_errno = errno;
148       close (fds[0]);
149       close (fds[1]);
150       return g_unix_set_error_from_errno (error, saved_errno);
151     }
152   ecode = fcntl (fds[1], F_SETFD, flags);
153   if (ecode == -1)
154     {
155       int saved_errno = errno;
156       close (fds[0]);
157       close (fds[1]);
158       return g_unix_set_error_from_errno (error, saved_errno);
159     }
160   return TRUE;
161 }
162
163 /**
164  * g_unix_set_fd_nonblocking:
165  * @fd: A file descriptor
166  * @nonblock: If %TRUE, set the descriptor to be non-blocking
167  * @error: a #GError
168  *
169  * Control the non-blocking state of the given file descriptor,
170  * according to @nonblock. On most systems this uses %O_NONBLOCK, but
171  * on some older ones may use %O_NDELAY.
172  *
173  * Returns: %TRUE if successful
174  *
175  * Since: 2.30
176  */
177 gboolean
178 g_unix_set_fd_nonblocking (gint       fd,
179                            gboolean   nonblock,
180                            GError   **error)
181 {
182 #ifdef F_GETFL
183   glong fcntl_flags;
184   fcntl_flags = fcntl (fd, F_GETFL);
185
186   if (fcntl_flags == -1)
187     return g_unix_set_error_from_errno (error, errno);
188
189   if (nonblock)
190     {
191 #ifdef O_NONBLOCK
192       fcntl_flags |= O_NONBLOCK;
193 #else
194       fcntl_flags |= O_NDELAY;
195 #endif
196     }
197   else
198     {
199 #ifdef O_NONBLOCK
200       fcntl_flags &= ~O_NONBLOCK;
201 #else
202       fcntl_flags &= ~O_NDELAY;
203 #endif
204     }
205
206   if (fcntl (fd, F_SETFL, fcntl_flags) == -1)
207     return g_unix_set_error_from_errno (error, errno);
208   return TRUE;
209 #else
210   return g_unix_set_error_from_errno (error, EINVAL);
211 #endif
212 }
213
214 /**
215  * g_unix_signal_source_new:
216  * @signum: A signal number
217  *
218  * Create a #GSource that will be dispatched upon delivery of the UNIX
219  * signal @signum.  In GLib versions before 2.36, only `SIGHUP`, `SIGINT`,
220  * `SIGTERM` can be monitored.  In GLib 2.36, `SIGUSR1` and `SIGUSR2`
221  * were added.
222  *
223  * Note that unlike the UNIX default, all sources which have created a
224  * watch will be dispatched, regardless of which underlying thread
225  * invoked g_unix_signal_source_new().
226  *
227  * For example, an effective use of this function is to handle `SIGTERM`
228  * cleanly; flushing any outstanding files, and then calling
229  * g_main_loop_quit ().  It is not safe to do any of this a regular
230  * UNIX signal handler; your handler may be invoked while malloc() or
231  * another library function is running, causing reentrancy if you
232  * attempt to use it from the handler.  None of the GLib/GObject API
233  * is safe against this kind of reentrancy.
234  *
235  * The interaction of this source when combined with native UNIX
236  * functions like sigprocmask() is not defined.
237  *
238  * The source will not initially be associated with any #GMainContext
239  * and must be added to one with g_source_attach() before it will be
240  * executed.
241  *
242  * Returns: A newly created #GSource
243  *
244  * Since: 2.30
245  */
246 GSource *
247 g_unix_signal_source_new (int signum)
248 {
249   g_return_val_if_fail (signum == SIGHUP || signum == SIGINT || signum == SIGTERM ||
250                         signum == SIGUSR1 || signum == SIGUSR2, NULL);
251
252   return _g_main_create_unix_signal_watch (signum);
253 }
254
255 /**
256  * g_unix_signal_add_full:
257  * @priority: the priority of the signal source. Typically this will be in
258  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
259  * @signum: Signal number
260  * @handler: Callback
261  * @user_data: Data for @handler
262  * @notify: #GDestroyNotify for @handler
263  *
264  * A convenience function for g_unix_signal_source_new(), which
265  * attaches to the default #GMainContext.  You can remove the watch
266  * using g_source_remove().
267  *
268  * Returns: An ID (greater than 0) for the event source
269  *
270  * Rename to: g_unix_signal_add
271  * Since: 2.30
272  */
273 guint
274 g_unix_signal_add_full (int            priority,
275                         int            signum,
276                         GSourceFunc    handler,
277                         gpointer       user_data,
278                         GDestroyNotify notify)
279 {
280   guint id;
281   GSource *source;
282
283   source = g_unix_signal_source_new (signum);
284
285   if (priority != G_PRIORITY_DEFAULT)
286     g_source_set_priority (source, priority);
287
288   g_source_set_callback (source, handler, user_data, notify);
289   id = g_source_attach (source, NULL);
290   g_source_unref (source);
291
292   return id;
293 }
294
295 /**
296  * g_unix_signal_add:
297  * @signum: Signal number
298  * @handler: Callback
299  * @user_data: Data for @handler
300  *
301  * A convenience function for g_unix_signal_source_new(), which
302  * attaches to the default #GMainContext.  You can remove the watch
303  * using g_source_remove().
304  *
305  * Returns: An ID (greater than 0) for the event source
306  *
307  * Since: 2.30
308  */
309 guint
310 g_unix_signal_add (int         signum,
311                    GSourceFunc handler,
312                    gpointer    user_data)
313 {
314   return g_unix_signal_add_full (G_PRIORITY_DEFAULT, signum, handler, user_data, NULL);
315 }
316
317 typedef struct
318 {
319   GSource source;
320
321   gint     fd;
322   gpointer tag;
323 } GUnixFDSource;
324
325 static gboolean
326 g_unix_fd_source_dispatch (GSource     *source,
327                            GSourceFunc  callback,
328                            gpointer     user_data)
329 {
330   GUnixFDSource *fd_source = (GUnixFDSource *) source;
331   GUnixFDSourceFunc func = (GUnixFDSourceFunc) callback;
332
333   if (!callback)
334     {
335       g_warning ("GUnixFDSource dispatched without callback\n"
336                  "You must call g_source_set_callback().");
337       return FALSE;
338     }
339
340   return (* func) (fd_source->fd, g_source_query_unix_fd (source, fd_source->tag), user_data);
341 }
342
343 GSourceFuncs g_unix_fd_source_funcs = {
344   NULL, NULL, g_unix_fd_source_dispatch, NULL
345 };
346
347 /**
348  * g_unix_fd_source_new:
349  * @fd: a file descriptor
350  * @condition: IO conditions to watch for on @fd
351  *
352  * Creates a #GSource to watch for a particular IO condition on a file
353  * descriptor.
354  *
355  * The source will never close the fd -- you must do it yourself.
356  *
357  * Returns: the newly created #GSource
358  *
359  * Since: 2.36
360  **/
361 GSource *
362 g_unix_fd_source_new (gint         fd,
363                       GIOCondition condition)
364 {
365   GUnixFDSource *fd_source;
366   GSource *source;
367
368   source = g_source_new (&g_unix_fd_source_funcs, sizeof (GUnixFDSource));
369   fd_source = (GUnixFDSource *) source;
370
371   fd_source->fd = fd;
372   fd_source->tag = g_source_add_unix_fd (source, fd, condition);
373
374   return source;
375 }
376
377 /**
378  * g_unix_fd_add_full:
379  * @priority: the priority of the source
380  * @fd: a file descriptor
381  * @condition: IO conditions to watch for on @fd
382  * @function: a #GUnixFDSourceFunc
383  * @user_data: data to pass to @function
384  * @notify: function to call when the idle is removed, or %NULL
385  *
386  * Sets a function to be called when the IO condition, as specified by
387  * @condition becomes true for @fd.
388  *
389  * This is the same as g_unix_fd_add(), except that it allows you to
390  * specify a non-default priority and a provide a #GDestroyNotify for
391  * @user_data.
392  *
393  * Returns: the ID (greater than 0) of the event source
394  *
395  * Since: 2.36
396  **/
397 guint
398 g_unix_fd_add_full (gint              priority,
399                     gint              fd,
400                     GIOCondition      condition,
401                     GUnixFDSourceFunc function,
402                     gpointer          user_data,
403                     GDestroyNotify    notify)
404 {
405   GSource *source;
406   guint id;
407
408   g_return_val_if_fail (function != NULL, 0);
409
410   source = g_unix_fd_source_new (fd, condition);
411
412   if (priority != G_PRIORITY_DEFAULT)
413     g_source_set_priority (source, priority);
414
415   g_source_set_callback (source, (GSourceFunc) function, user_data, notify);
416   id = g_source_attach (source, NULL);
417   g_source_unref (source);
418
419   return id;
420 }
421
422 /**
423  * g_unix_fd_add:
424  * @fd: a file descriptor
425  * @condition: IO conditions to watch for on @fd
426  * @function: a #GPollFDFunc
427  * @user_data: data to pass to @function
428  *
429  * Sets a function to be called when the IO condition, as specified by
430  * @condition becomes true for @fd.
431  *
432  * @function will be called when the specified IO condition becomes
433  * %TRUE.  The function is expected to clear whatever event caused the
434  * IO condition to become true and return %TRUE in order to be notified
435  * when it happens again.  If @function returns %FALSE then the watch
436  * will be cancelled.
437  *
438  * The return value of this function can be passed to g_source_remove()
439  * to cancel the watch at any time that it exists.
440  *
441  * The source will never close the fd -- you must do it yourself.
442  *
443  * Returns: the ID (greater than 0) of the event source
444  *
445  * Since: 2.36
446  **/
447 guint
448 g_unix_fd_add (gint              fd,
449                GIOCondition      condition,
450                GUnixFDSourceFunc function,
451                gpointer          user_data)
452 {
453   return g_unix_fd_add_full (G_PRIORITY_DEFAULT, fd, condition, function, user_data, NULL);
454 }
455
456 /**
457  * g_unix_fd_ensure_zero_copy_safe:
458  * @fd: a file descriptor
459  *
460  * Checks whether @fd can be use in zero-copy mode. On Linux, this checks that
461  * the descriptor is a memfd, created with memfd_create(), and tries to apply
462  * seals to it so that it can be safely consumed by another process. On other
463  * Unix systems, this function will fail.
464  *
465  * Returns: whether the fd is safe to use in zero-copy mode. Sealing of memfds
466  *          is required for the @fd to be considered safe. If sealing fails, or
467  *          memfds are not available, or the @fd is not a memfd, returns %FALSE
468  *
469  * Since: 2.44
470  **/
471 gboolean
472 g_unix_fd_ensure_zero_copy_safe (gint fd)
473 {
474 #ifdef F_GET_SEALS
475   gint seals;
476   const gint IMMUTABLE_SEALS = F_SEAL_WRITE |
477                                F_SEAL_SHRINK |
478                                F_SEAL_GROW |
479                                F_SEAL_SEAL;
480
481   g_return_val_if_fail (fd >= 0, FALSE);
482
483   /* Seal the fd if possible (only on Linux 3.17+, and if the fd was created
484    * with memfd_create()). */
485   seals = fcntl (fd, F_GET_SEALS);
486   if (seals == -1)
487     {
488       g_debug ("Retrieving fd seals failed: %s", g_strerror (errno));
489       return FALSE;
490     }
491
492   /* Seal the fd, if it is not already. */
493   if ((seals & (IMMUTABLE_SEALS)) >= IMMUTABLE_SEALS)
494     {
495       g_debug ("%s", "fd already sealed");
496     }
497   else
498     {
499       gint error;
500
501       error = fcntl (fd, F_ADD_SEALS, IMMUTABLE_SEALS);
502       if (error == -1)
503         {
504           g_debug ("fd sealing failed: %s", g_strerror (errno));
505           return FALSE;
506         }
507     }
508
509   return TRUE;
510 #else
511   return FALSE;
512 #endif
513 }