Silence a bunch of -Wunused-but-set-variable warnings
[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
54 G_DEFINE_TYPE_WITH_CODE (GUnixConnection, g_unix_connection,
55                          G_TYPE_SOCKET_CONNECTION,
56   g_socket_connection_factory_register_type (g_define_type_id,
57                                              G_SOCKET_FAMILY_UNIX,
58                                              G_SOCKET_TYPE_STREAM,
59                                              G_SOCKET_PROTOCOL_DEFAULT);
60                          );
61
62 /**
63  * g_unix_connection_send_fd:
64  * @connection: a #GUnixConnection
65  * @fd: a file descriptor
66  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
67  * @error: (allow-none): #GError for error reporting, or %NULL to ignore.
68  *
69  * Passes a file descriptor to the recieving side of the
70  * connection. The recieving end has to call g_unix_connection_receive_fd()
71  * to accept the file descriptor.
72  *
73  * As well as sending the fd this also writes a single byte to the
74  * stream, as this is required for fd passing to work on some
75  * implementations.
76  *
77  * Returns: a %TRUE on success, %NULL on error.
78  *
79  * Since: 2.22
80  */
81 gboolean
82 g_unix_connection_send_fd (GUnixConnection  *connection,
83                            gint              fd,
84                            GCancellable     *cancellable,
85                            GError          **error)
86 {
87   GSocketControlMessage *scm;
88   GSocket *socket;
89
90   g_return_val_if_fail (G_IS_UNIX_CONNECTION (connection), FALSE);
91   g_return_val_if_fail (fd >= 0, FALSE);
92
93   scm = g_unix_fd_message_new ();
94
95   if (!g_unix_fd_message_append_fd (G_UNIX_FD_MESSAGE (scm), fd, error))
96     {
97       g_object_unref (scm);
98       return FALSE;
99     }
100
101   g_object_get (connection, "socket", &socket, NULL);
102   if (g_socket_send_message (socket, NULL, NULL, 0, &scm, 1, 0, cancellable, error) != 1)
103     /* XXX could it 'fail' with zero? */
104     {
105       g_object_unref (socket);
106       g_object_unref (scm);
107
108       return FALSE;
109     }
110
111   g_object_unref (socket);
112   g_object_unref (scm);
113
114   return TRUE;
115 }
116
117 /**
118  * g_unix_connection_receive_fd:
119  * @connection: a #GUnixConnection
120  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore
121  * @error: (allow-none): #GError for error reporting, or %NULL to ignore
122  *
123  * Receives a file descriptor from the sending end of the connection.
124  * The sending end has to call g_unix_connection_send_fd() for this
125  * to work.
126  *
127  * As well as reading the fd this also reads a single byte from the
128  * stream, as this is required for fd passing to work on some
129  * implementations.
130  *
131  * Returns: a file descriptor on success, -1 on error.
132  *
133  * Since: 2.22
134  **/
135 gint
136 g_unix_connection_receive_fd (GUnixConnection  *connection,
137                               GCancellable     *cancellable,
138                               GError          **error)
139 {
140   GSocketControlMessage **scms;
141   gint *fds, nfd, fd, nscm;
142   GUnixFDMessage *fdmsg;
143   GSocket *socket;
144
145   g_return_val_if_fail (G_IS_UNIX_CONNECTION (connection), -1);
146
147   g_object_get (connection, "socket", &socket, NULL);
148   if (g_socket_receive_message (socket, NULL, NULL, 0,
149                                 &scms, &nscm, NULL, cancellable, error) != 1)
150     /* XXX it _could_ 'fail' with zero. */
151     {
152       g_object_unref (socket);
153
154       return -1;
155     }
156
157   g_object_unref (socket);
158
159   if (nscm != 1)
160     {
161       gint i;
162
163       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
164                    _("Expecting 1 control message, got %d"), nscm);
165
166       for (i = 0; i < nscm; i++)
167         g_object_unref (scms[i]);
168
169       g_free (scms);
170
171       return -1;
172     }
173
174   if (!G_IS_UNIX_FD_MESSAGE (scms[0]))
175     {
176       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
177                            _("Unexpected type of ancillary data"));
178       g_object_unref (scms[0]);
179       g_free (scms);
180
181       return -1;
182     }
183
184   fdmsg = G_UNIX_FD_MESSAGE (scms[0]);
185   g_free (scms);
186
187   fds = g_unix_fd_message_steal_fds (fdmsg, &nfd);
188   g_object_unref (fdmsg);
189
190   if (nfd != 1)
191     {
192       gint i;
193
194       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
195                    _("Expecting one fd, but got %d\n"), nfd);
196
197       for (i = 0; i < nfd; i++)
198         close (fds[i]);
199
200       g_free (fds);
201
202       return -1;
203     }
204
205   fd = *fds;
206   g_free (fds);
207
208   if (fd < 0)
209     {
210       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
211                            _("Received invalid fd"));
212       fd = -1;
213     }
214
215   return fd;
216 }
217
218 static void
219 g_unix_connection_init (GUnixConnection *connection)
220 {
221 }
222
223 static void
224 g_unix_connection_class_init (GUnixConnectionClass *class)
225 {
226 }
227
228 /* TODO: Other stuff we might want to add are:
229 void                    g_unix_connection_send_fd_async                 (GUnixConnection      *connection,
230                                                                          gint                  fd,
231                                                                          gboolean              close,
232                                                                          gint                  io_priority,
233                                                                          GAsyncReadyCallback   callback,
234                                                                          gpointer              user_data);
235 gboolean                g_unix_connection_send_fd_finish                (GUnixConnection      *connection,
236                                                                          GError              **error);
237
238 gboolean                g_unix_connection_send_fds                      (GUnixConnection      *connection,
239                                                                          gint                 *fds,
240                                                                          gint                  nfds,
241                                                                          GError              **error);
242 void                    g_unix_connection_send_fds_async                (GUnixConnection      *connection,
243                                                                          gint                 *fds,
244                                                                          gint                  nfds,
245                                                                          gint                  io_priority,
246                                                                          GAsyncReadyCallback   callback,
247                                                                          gpointer              user_data);
248 gboolean                g_unix_connection_send_fds_finish               (GUnixConnection      *connection,
249                                                                          GError              **error);
250
251 void                    g_unix_connection_receive_fd_async              (GUnixConnection      *connection,
252                                                                          gint                  io_priority,
253                                                                          GAsyncReadyCallback   callback,
254                                                                          gpointer              user_data);
255 gint                    g_unix_connection_receive_fd_finish             (GUnixConnection      *connection,
256                                                                          GError              **error);
257
258
259 gboolean                g_unix_connection_send_credentials              (GUnixConnection      *connection,
260                                                                          GError              **error);
261 void                    g_unix_connection_send_credentials_async        (GUnixConnection      *connection,
262                                                                          gint                  io_priority,
263                                                                          GAsyncReadyCallback   callback,
264                                                                          gpointer              user_data);
265 gboolean                g_unix_connection_send_credentials_finish       (GUnixConnection      *connection,
266                                                                          GError              **error);
267
268 gboolean                g_unix_connection_send_fake_credentials         (GUnixConnection      *connection,
269                                                                          guint64               pid,
270                                                                          guint64               uid,
271                                                                          guint64               gid,
272                                                                          GError              **error);
273 void                    g_unix_connection_send_fake_credentials_async   (GUnixConnection      *connection,
274                                                                          guint64               pid,
275                                                                          guint64               uid,
276                                                                          guint64               gid,
277                                                                          gint                  io_priority,
278                                                                          GAsyncReadyCallback   callback,
279                                                                          gpointer              user_data);
280 gboolean                g_unix_connection_send_fake_credentials_finish  (GUnixConnection      *connection,
281                                                                          GError              **error);
282
283 gboolean                g_unix_connection_receive_credentials           (GUnixConnection      *connection,
284                                                                          guint64              *pid,
285                                                                          guint64              *uid,
286                                                                          guint64              *gid,
287                                                                          GError              **error);
288 void                    g_unix_connection_receive_credentials_async     (GUnixConnection      *connection,
289                                                                          gint                  io_priority,
290                                                                          GAsyncReadyCallback   callback,
291                                                                          gpointer              user_data);
292 gboolean                g_unix_connection_receive_credentials_finish    (GUnixConnection      *connection,
293                                                                          guint64              *pid,
294                                                                          guint64              *uid,
295                                                                          guint64              *gid,
296                                                                          GError              **error);
297
298 gboolean                g_unix_connection_create_pair                   (GUnixConnection     **one,
299                                                                          GUnixConnection     **two,
300                                                                          GError              **error);
301 */
302
303
304 /**
305  * g_unix_connection_send_credentials:
306  * @connection: A #GUnixConnection.
307  * @cancellable: (allow-none): A #GCancellable or %NULL.
308  * @error: Return location for error or %NULL.
309  *
310  * Passes the credentials of the current user the receiving side
311  * of the connection. The recieving end has to call
312  * g_unix_connection_receive_credentials() (or similar) to accept the
313  * credentials.
314  *
315  * As well as sending the credentials this also writes a single NUL
316  * byte to the stream, as this is required for credentials passing to
317  * work on some implementations.
318  *
319  * Other ways to exchange credentials with a foreign peer includes the
320  * #GUnixCredentialsMessage type and g_socket_get_credentials() function.
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: (allow-none): 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  * Other ways to exchange credentials with a foreign peer includes the
387  * #GUnixCredentialsMessage type and g_socket_get_credentials() function.
388  *
389  * Returns: (transfer full): Received credentials on success (free with
390  * g_object_unref()), %NULL if @error is set.
391  *
392  * Since: 2.26
393  */
394 GCredentials *
395 g_unix_connection_receive_credentials (GUnixConnection      *connection,
396                                        GCancellable         *cancellable,
397                                        GError              **error)
398 {
399   GCredentials *ret;
400   GSocketControlMessage **scms;
401   gint nscm;
402   GSocket *socket;
403   gint n;
404   volatile GType credentials_message_gtype;
405   gssize num_bytes_read;
406 #ifdef __linux__
407   gboolean turn_off_so_passcreds;
408 #endif
409
410   g_return_val_if_fail (G_IS_UNIX_CONNECTION (connection), NULL);
411   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
412
413   ret = NULL;
414   scms = NULL;
415
416   g_object_get (connection, "socket", &socket, NULL);
417
418   /* On Linux, we need to turn on SO_PASSCRED if it isn't enabled
419    * already. We also need to turn it off when we're done.  See
420    * #617483 for more discussion.
421    */
422 #ifdef __linux__
423   {
424     gint opt_val;
425     socklen_t opt_len;
426
427     turn_off_so_passcreds = FALSE;
428     opt_val = 0;
429     opt_len = sizeof (gint);
430     if (getsockopt (g_socket_get_fd (socket),
431                     SOL_SOCKET,
432                     SO_PASSCRED,
433                     &opt_val,
434                     &opt_len) != 0)
435       {
436         g_set_error (error,
437                      G_IO_ERROR,
438                      g_io_error_from_errno (errno),
439                      _("Error checking if SO_PASSCRED is enabled for socket: %s"),
440                      strerror (errno));
441         goto out;
442       }
443     if (opt_len != sizeof (gint))
444       {
445         g_set_error (error,
446                      G_IO_ERROR,
447                      G_IO_ERROR_FAILED,
448                      _("Unexpected option length while checking if SO_PASSCRED is enabled for socket. "
449                        "Expected %d bytes, got %d"),
450                      (gint) sizeof (gint), (gint) opt_len);
451         goto out;
452       }
453     if (opt_val == 0)
454       {
455         opt_val = 1;
456         if (setsockopt (g_socket_get_fd (socket),
457                         SOL_SOCKET,
458                         SO_PASSCRED,
459                         &opt_val,
460                         sizeof opt_val) != 0)
461           {
462             g_set_error (error,
463                          G_IO_ERROR,
464                          g_io_error_from_errno (errno),
465                          _("Error enabling SO_PASSCRED: %s"),
466                          strerror (errno));
467             goto out;
468           }
469         turn_off_so_passcreds = TRUE;
470       }
471   }
472 #endif
473
474   /* ensure the type of GUnixCredentialsMessage has been registered with the type system */
475   credentials_message_gtype = G_TYPE_UNIX_CREDENTIALS_MESSAGE;
476   (credentials_message_gtype); /* To avoid -Wunused-but-set-variable */
477   num_bytes_read = g_socket_receive_message (socket,
478                                              NULL, /* GSocketAddress **address */
479                                              NULL,
480                                              0,
481                                              &scms,
482                                              &nscm,
483                                              NULL,
484                                              cancellable,
485                                              error);
486   if (num_bytes_read != 1)
487     {
488       /* Handle situation where g_socket_receive_message() returns
489        * 0 bytes and not setting @error
490        */
491       if (num_bytes_read == 0 && error != NULL && *error == NULL)
492         {
493           g_set_error_literal (error,
494                                G_IO_ERROR,
495                                G_IO_ERROR_FAILED,
496                                _("Expecting to read a single byte for receiving credentials but read zero bytes"));
497         }
498       goto out;
499     }
500
501   if (nscm != 1)
502     {
503       g_set_error (error,
504                    G_IO_ERROR,
505                    G_IO_ERROR_FAILED,
506                    _("Expecting 1 control message, got %d"),
507                    nscm);
508       goto out;
509     }
510
511   if (!G_IS_UNIX_CREDENTIALS_MESSAGE (scms[0]))
512     {
513       g_set_error_literal (error,
514                            G_IO_ERROR,
515                            G_IO_ERROR_FAILED,
516                            _("Unexpected type of ancillary data"));
517       goto out;
518     }
519
520   ret = g_unix_credentials_message_get_credentials (G_UNIX_CREDENTIALS_MESSAGE (scms[0]));
521   g_object_ref (ret);
522
523  out:
524
525 #ifdef __linux__
526   if (turn_off_so_passcreds)
527     {
528       gint opt_val;
529       opt_val = 0;
530       if (setsockopt (g_socket_get_fd (socket),
531                       SOL_SOCKET,
532                       SO_PASSCRED,
533                       &opt_val,
534                       sizeof opt_val) != 0)
535         {
536           g_set_error (error,
537                        G_IO_ERROR,
538                        g_io_error_from_errno (errno),
539                        _("Error while disabling SO_PASSCRED: %s"),
540                        strerror (errno));
541           goto out;
542         }
543     }
544 #endif
545
546   if (scms != NULL)
547     {
548       for (n = 0; n < nscm; n++)
549         g_object_unref (scms[n]);
550       g_free (scms);
551     }
552   g_object_unref (socket);
553   return ret;
554 }