Set up gtk-doc for GDBus
[platform/upstream/glib.git] / gio / gunixconnection.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright © 2009 Codethink Limited
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License as published
7  * by the Free Software Foundation; either version 2 of the licence or (at
8  * your option) any later version.
9  *
10  * See the included COPYING file for more information.
11  *
12  * Authors: Ryan Lortie <desrt@desrt.ca>
13  */
14
15 #include "config.h"
16 #include "gunixconnection.h"
17 #include "glibintl.h"
18
19 /**
20  * SECTION: gunixconnection
21  * @title: GUnixConnection
22  * @short_description: a Unix domain #GSocketConnection
23  * @see_also: #GSocketConnection.
24  *
25  * This is the subclass of #GSocketConnection that is created
26  * for UNIX domain sockets.
27  *
28  * It contains functions to do some of the unix socket specific
29  * functionallity like passing file descriptors.
30  *
31  * Since: 2.22
32  */
33
34 #include <gio/gsocketcontrolmessage.h>
35 #include <gio/gunixfdmessage.h>
36 #include <gio/gsocket.h>
37 #include <unistd.h>
38
39 #ifdef __linux__
40 /* for getsockopt() and setsockopt() */
41 #include <sys/types.h>          /* See NOTES */
42 #include <sys/socket.h>
43 #include <errno.h>
44 #include <string.h>
45 #endif
46
47 #include "gioalias.h"
48
49 G_DEFINE_TYPE_WITH_CODE (GUnixConnection, g_unix_connection,
50                          G_TYPE_SOCKET_CONNECTION,
51   g_socket_connection_factory_register_type (g_define_type_id,
52                                              G_SOCKET_FAMILY_UNIX,
53                                              G_SOCKET_TYPE_STREAM,
54                                              G_SOCKET_PROTOCOL_DEFAULT);
55                          );
56
57 /**
58  * g_unix_connection_send_fd:
59  * @connection: a #GUnixConnection
60  * @fd: a file descriptor
61  * @cancellable: optional #GCancellable object, %NULL to ignore.
62  * @error: #GError for error reporting, or %NULL to ignore.
63  *
64  * Passes a file descriptor to the recieving side of the
65  * connection. The recieving end has to call g_unix_connection_receive_fd()
66  * to accept the file descriptor.
67  *
68  * As well as sending the fd this also writes a single byte to the
69  * stream, as this is required for fd passing to work on some
70  * implementations.
71  *
72  * Returns: a %TRUE on success, %NULL on error.
73  *
74  * Since: 2.22
75  */
76 gboolean
77 g_unix_connection_send_fd (GUnixConnection  *connection,
78                            gint              fd,
79                            GCancellable     *cancellable,
80                            GError          **error)
81 {
82   GSocketControlMessage *scm;
83   GSocket *socket;
84
85   g_return_val_if_fail (G_IS_UNIX_CONNECTION (connection), FALSE);
86   g_return_val_if_fail (fd >= 0, FALSE);
87
88   scm = g_unix_fd_message_new ();
89
90   if (!g_unix_fd_message_append_fd (G_UNIX_FD_MESSAGE (scm), fd, error))
91     {
92       g_object_unref (scm);
93       return FALSE;
94     }
95
96   g_object_get (connection, "socket", &socket, NULL);
97   if (g_socket_send_message (socket, NULL, NULL, 0, &scm, 1, 0, cancellable, error) != 1)
98     /* XXX could it 'fail' with zero? */
99     {
100       g_object_unref (socket);
101       g_object_unref (scm);
102
103       return FALSE;
104     }
105
106   g_object_unref (socket);
107   g_object_unref (scm);
108
109   return TRUE;
110 }
111
112 /**
113  * g_unix_connection_receive_fd:
114  * @connection: a #GUnixConnection
115  * @cancellable: optional #GCancellable object, %NULL to ignore
116  * @error: #GError for error reporting, or %NULL to ignore
117  *
118  * Receives a file descriptor from the sending end of the connection.
119  * The sending end has to call g_unix_connection_send_fd() for this
120  * to work.
121  *
122  * As well as reading the fd this also reads a single byte from the
123  * stream, as this is required for fd passing to work on some
124  * implementations.
125  *
126  * Returns: a file descriptor on success, -1 on error.
127  *
128  * Since: 2.22
129  */
130 gint
131 g_unix_connection_receive_fd (GUnixConnection  *connection,
132                               GCancellable     *cancellable,
133                               GError          **error)
134 {
135   GSocketControlMessage **scms;
136   gint *fds, nfd, fd, nscm;
137   GUnixFDMessage *fdmsg;
138   GSocket *socket;
139
140   g_return_val_if_fail (G_IS_UNIX_CONNECTION (connection), -1);
141
142   g_object_get (connection, "socket", &socket, NULL);
143   if (g_socket_receive_message (socket, NULL, NULL, 0,
144                                 &scms, &nscm, NULL, cancellable, error) != 1)
145     /* XXX it _could_ 'fail' with zero. */
146     {
147       g_object_unref (socket);
148
149       return -1;
150     }
151
152   g_object_unref (socket);
153
154   if (nscm != 1)
155     {
156       gint i;
157
158       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
159                    _("Expecting 1 control message, got %d"), nscm);
160
161       for (i = 0; i < nscm; i++)
162         g_object_unref (scms[i]);
163
164       g_free (scms);
165
166       return -1;
167     }
168
169   if (!G_IS_UNIX_FD_MESSAGE (scms[0]))
170     {
171       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
172                            _("Unexpected type of ancillary data"));
173       g_object_unref (scms[0]);
174       g_free (scms);
175
176       return -1;
177     }
178
179   fdmsg = G_UNIX_FD_MESSAGE (scms[0]);
180   g_free (scms);
181
182   fds = g_unix_fd_message_steal_fds (fdmsg, &nfd);
183   g_object_unref (fdmsg);
184
185   if (nfd != 1)
186     {
187       gint i;
188
189       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
190                    _("Expecting one fd, but got %d\n"), nfd);
191
192       for (i = 0; i < nfd; i++)
193         close (fds[i]);
194
195       g_free (fds);
196
197       return -1;
198     }
199
200   fd = *fds;
201   g_free (fds);
202
203   if (fd < 0)
204     {
205       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
206                            _("Received invalid fd"));
207       fd = -1;
208     }
209
210   return fd;
211 }
212
213 static void
214 g_unix_connection_init (GUnixConnection *connection)
215 {
216 }
217
218 static void
219 g_unix_connection_class_init (GUnixConnectionClass *class)
220 {
221 }
222
223 /* TODO: Other stuff we might want to add are:
224 void                    g_unix_connection_send_fd_async                 (GUnixConnection      *connection,
225                                                                          gint                  fd,
226                                                                          gboolean              close,
227                                                                          gint                  io_priority,
228                                                                          GAsyncReadyCallback   callback,
229                                                                          gpointer              user_data);
230 gboolean                g_unix_connection_send_fd_finish                (GUnixConnection      *connection,
231                                                                          GError              **error);
232
233 gboolean                g_unix_connection_send_fds                      (GUnixConnection      *connection,
234                                                                          gint                 *fds,
235                                                                          gint                  nfds,
236                                                                          GError              **error);
237 void                    g_unix_connection_send_fds_async                (GUnixConnection      *connection,
238                                                                          gint                 *fds,
239                                                                          gint                  nfds,
240                                                                          gint                  io_priority,
241                                                                          GAsyncReadyCallback   callback,
242                                                                          gpointer              user_data);
243 gboolean                g_unix_connection_send_fds_finish               (GUnixConnection      *connection,
244                                                                          GError              **error);
245
246 void                    g_unix_connection_receive_fd_async              (GUnixConnection      *connection,
247                                                                          gint                  io_priority,
248                                                                          GAsyncReadyCallback   callback,
249                                                                          gpointer              user_data);
250 gint                    g_unix_connection_receive_fd_finish             (GUnixConnection      *connection,
251                                                                          GError              **error);
252
253
254 gboolean                g_unix_connection_send_credentials              (GUnixConnection      *connection,
255                                                                          GError              **error);
256 void                    g_unix_connection_send_credentials_async        (GUnixConnection      *connection,
257                                                                          gint                  io_priority,
258                                                                          GAsyncReadyCallback   callback,
259                                                                          gpointer              user_data);
260 gboolean                g_unix_connection_send_credentials_finish       (GUnixConnection      *connection,
261                                                                          GError              **error);
262
263 gboolean                g_unix_connection_send_fake_credentials         (GUnixConnection      *connection,
264                                                                          guint64               pid,
265                                                                          guint64               uid,
266                                                                          guint64               gid,
267                                                                          GError              **error);
268 void                    g_unix_connection_send_fake_credentials_async   (GUnixConnection      *connection,
269                                                                          guint64               pid,
270                                                                          guint64               uid,
271                                                                          guint64               gid,
272                                                                          gint                  io_priority,
273                                                                          GAsyncReadyCallback   callback,
274                                                                          gpointer              user_data);
275 gboolean                g_unix_connection_send_fake_credentials_finish  (GUnixConnection      *connection,
276                                                                          GError              **error);
277
278 gboolean                g_unix_connection_receive_credentials           (GUnixConnection      *connection,
279                                                                          guint64              *pid,
280                                                                          guint64              *uid,
281                                                                          guint64              *gid,
282                                                                          GError              **error);
283 void                    g_unix_connection_receive_credentials_async     (GUnixConnection      *connection,
284                                                                          gint                  io_priority,
285                                                                          GAsyncReadyCallback   callback,
286                                                                          gpointer              user_data);
287 gboolean                g_unix_connection_receive_credentials_finish    (GUnixConnection      *connection,
288                                                                          guint64              *pid,
289                                                                          guint64              *uid,
290                                                                          guint64              *gid,
291                                                                          GError              **error);
292
293 gboolean                g_unix_connection_create_pair                   (GUnixConnection     **one,
294                                                                          GUnixConnection     **two,
295                                                                          GError              **error);
296 */
297
298
299 /**
300  * g_unix_connection_send_credentials:
301  * @connection: A #GUnixConnection.
302  * @credentials: A #GCredentials to send.
303  * @cancellable: A #GCancellable or %NULL.
304  * @error: Return location for error or %NULL.
305  *
306  * Passes the credentials stored in @credentials to the recieving side
307  * of the connection. The recieving end has to call
308  * g_unix_connection_receive_credentials() (or similar) to accept the
309  * credentials.
310  *
311  * The credentials which the sender specifies are checked by the
312  * kernel.  A process with effective user ID 0 is allowed to specify
313  * values that do not match its own. This means that the credentials
314  * can be used to authenticate other connections.
315  *
316  * As well as sending the credentials this also writes a single NUL
317  * byte to the stream, as this is required for credentials passing to
318  * work on some implementations.
319  *
320  * Returns: %TRUE on success, %FALSE if @error is set.
321  *
322  * Since: 2.26
323  */
324 gboolean
325 g_unix_connection_send_credentials (GUnixConnection      *connection,
326                                     GCredentials         *credentials,
327                                     GCancellable         *cancellable,
328                                     GError              **error)
329 {
330   GSocketControlMessage *scm;
331   GSocket *socket;
332   gboolean ret;
333   GOutputVector vector;
334   guchar nul_byte[1] = {'\0'};
335
336   g_return_val_if_fail (G_IS_UNIX_CONNECTION (connection), FALSE);
337   g_return_val_if_fail (G_IS_CREDENTIALS (credentials), FALSE);
338   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
339
340   ret = FALSE;
341
342   vector.buffer = &nul_byte;
343   vector.size = 1;
344   scm = g_unix_credentials_message_new_with_credentials (credentials);
345   g_object_get (connection, "socket", &socket, NULL);
346   if (g_socket_send_message (socket,
347                              NULL, /* address */
348                              &vector,
349                              1,
350                              &scm,
351                              1,
352                              G_SOCKET_MSG_NONE,
353                              cancellable,
354                              error) != 1)
355     {
356       g_prefix_error (error, _("Error sending credentials: "));
357       goto out;
358     }
359
360   ret = TRUE;
361
362  out:
363   g_object_unref (socket);
364   g_object_unref (scm);
365   return ret;
366 }
367
368 /**
369  * g_unix_connection_receive_credentials:
370  * @connection: A #GUnixConnection.
371  * @cancellable: A #GCancellable or %NULL.
372  * @error: Return location for error or %NULL.
373  *
374  * Receives credentials from the sending end of the connection.  The
375  * sending end has to call g_unix_connection_send_credentials() (or
376  * similar) for this to work.
377  *
378  * As well as reading the credentials this also reads (and discards) a
379  * single byte from the stream, as this is required for credentials
380  * passing to work on some implementations.
381  *
382  * Returns: Received credentials on success (free with
383  * g_object_unref()), %NULL if @error is set.
384  *
385  * Since: 2.26
386  */
387 GCredentials *
388 g_unix_connection_receive_credentials (GUnixConnection      *connection,
389                                        GCancellable         *cancellable,
390                                        GError              **error)
391 {
392   GCredentials *ret;
393   GSocketControlMessage **scms;
394   gint nscm;
395   GSocket *socket;
396   gint n;
397   volatile GType credentials_message_gtype;
398   gssize num_bytes_read;
399 #ifdef __linux__
400   gboolean turn_off_so_passcreds;
401 #endif
402
403   g_return_val_if_fail (G_IS_UNIX_CONNECTION (connection), NULL);
404   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
405
406   ret = NULL;
407   scms = NULL;
408
409   g_object_get (connection, "socket", &socket, NULL);
410
411   /* On Linux, we need to turn on SO_PASSCRED if it isn't enabled
412    * already. We also need to turn it off when we're done.  See
413    * #617483 for more discussion.
414    */
415 #ifdef __linux__
416   {
417     gint opt_val;
418     socklen_t opt_len;
419
420     turn_off_so_passcreds = FALSE;
421     opt_val = 0;
422     opt_len = sizeof (gint);
423     if (getsockopt (g_socket_get_fd (socket),
424                     SOL_SOCKET,
425                     SO_PASSCRED,
426                     &opt_val,
427                     &opt_len) != 0)
428       {
429         g_set_error (error,
430                      G_IO_ERROR,
431                      g_io_error_from_errno (errno),
432                      _("Error checking if SO_PASSCRED is enabled for socket: %s"),
433                      strerror (errno));
434         goto out;
435       }
436     if (opt_len != sizeof (gint))
437       {
438         g_set_error (error,
439                      G_IO_ERROR,
440                      G_IO_ERROR_FAILED,
441                      _("Unexpected option length while checking if SO_PASSCRED is enabled for socket. "
442                        "Expected %d bytes, got %d"),
443                      (gint) sizeof (gint), (gint) opt_len);
444         goto out;
445       }
446     if (opt_val == 0)
447       {
448         opt_val = 1;
449         if (setsockopt (g_socket_get_fd (socket),
450                         SOL_SOCKET,
451                         SO_PASSCRED,
452                         &opt_val,
453                         sizeof opt_val) != 0)
454           {
455             g_set_error (error,
456                          G_IO_ERROR,
457                          g_io_error_from_errno (errno),
458                          _("Error enabling SO_PASSCRED: %s"),
459                          strerror (errno));
460             goto out;
461           }
462         turn_off_so_passcreds = TRUE;
463       }
464   }
465 #endif
466
467   /* ensure the type of GUnixCredentialsMessage has been registered with the type system */
468   credentials_message_gtype = G_TYPE_UNIX_CREDENTIALS_MESSAGE;
469   num_bytes_read = g_socket_receive_message (socket,
470                                              NULL, /* GSocketAddress **address */
471                                              NULL,
472                                              0,
473                                              &scms,
474                                              &nscm,
475                                              NULL,
476                                              cancellable,
477                                              error);
478   if (num_bytes_read != 1)
479     {
480       /* Handle situation where g_socket_receive_message() returns
481        * 0 bytes and not setting @error
482        */
483       if (num_bytes_read == 0 && error != NULL && *error == NULL)
484         {
485           g_set_error_literal (error,
486                                G_IO_ERROR,
487                                G_IO_ERROR_FAILED,
488                                _("Expecting to read a single byte for receiving credentials but read zero bytes"));
489         }
490       goto out;
491     }
492
493   if (nscm != 1)
494     {
495       g_set_error (error,
496                    G_IO_ERROR,
497                    G_IO_ERROR_FAILED,
498                    _("Expecting 1 control message, got %d"),
499                    nscm);
500       goto out;
501     }
502
503   if (!G_IS_UNIX_CREDENTIALS_MESSAGE (scms[0]))
504     {
505       g_set_error_literal (error,
506                            G_IO_ERROR,
507                            G_IO_ERROR_FAILED,
508                            _("Unexpected type of ancillary data"));
509       goto out;
510     }
511
512   ret = g_unix_credentials_message_get_credentials (G_UNIX_CREDENTIALS_MESSAGE (scms[0]));
513   g_object_ref (ret);
514
515  out:
516
517 #ifdef __linux__
518   if (turn_off_so_passcreds)
519     {
520       gint opt_val;
521       opt_val = 0;
522       if (setsockopt (g_socket_get_fd (socket),
523                       SOL_SOCKET,
524                       SO_PASSCRED,
525                       &opt_val,
526                       sizeof opt_val) != 0)
527         {
528           g_set_error (error,
529                        G_IO_ERROR,
530                        g_io_error_from_errno (errno),
531                        _("Error while disabling SO_PASSCRED: %s"),
532                        strerror (errno));
533           goto out;
534         }
535     }
536 #endif
537
538   if (scms != NULL)
539     {
540       for (n = 0; n < nscm; n++)
541         g_object_unref (scms[n]);
542       g_free (scms);
543     }
544   g_object_unref (socket);
545   return ret;
546 }
547
548 #define __G_UNIX_CONNECTION_C__
549 #include "gioaliasdef.c"