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