Revert "GIOScheduler: Avoid constant iteration over pending job list"
[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 receiving side of the
70  * connection. The receiving 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_fake_credentials         (GUnixConnection      *connection,
260                                                                          guint64               pid,
261                                                                          guint64               uid,
262                                                                          guint64               gid,
263                                                                          GError              **error);
264 void                    g_unix_connection_send_fake_credentials_async   (GUnixConnection      *connection,
265                                                                          guint64               pid,
266                                                                          guint64               uid,
267                                                                          guint64               gid,
268                                                                          gint                  io_priority,
269                                                                          GAsyncReadyCallback   callback,
270                                                                          gpointer              user_data);
271 gboolean                g_unix_connection_send_fake_credentials_finish  (GUnixConnection      *connection,
272                                                                          GError              **error);
273
274 gboolean                g_unix_connection_create_pair                   (GUnixConnection     **one,
275                                                                          GUnixConnection     **two,
276                                                                          GError              **error);
277 */
278
279
280 /**
281  * g_unix_connection_send_credentials:
282  * @connection: A #GUnixConnection.
283  * @cancellable: (allow-none): A #GCancellable or %NULL.
284  * @error: Return location for error or %NULL.
285  *
286  * Passes the credentials of the current user the receiving side
287  * of the connection. The receiving end has to call
288  * g_unix_connection_receive_credentials() (or similar) to accept the
289  * credentials.
290  *
291  * As well as sending the credentials this also writes a single NUL
292  * byte to the stream, as this is required for credentials passing to
293  * work on some implementations.
294  *
295  * Other ways to exchange credentials with a foreign peer includes the
296  * #GUnixCredentialsMessage type and g_socket_get_credentials() function.
297  *
298  * Returns: %TRUE on success, %FALSE if @error is set.
299  *
300  * Since: 2.26
301  */
302 gboolean
303 g_unix_connection_send_credentials (GUnixConnection      *connection,
304                                     GCancellable         *cancellable,
305                                     GError              **error)
306 {
307   GCredentials *credentials;
308   GSocketControlMessage *scm;
309   GSocket *socket;
310   gboolean ret;
311   GOutputVector vector;
312   guchar nul_byte[1] = {'\0'};
313   gint num_messages;
314
315   g_return_val_if_fail (G_IS_UNIX_CONNECTION (connection), FALSE);
316   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
317
318   ret = FALSE;
319
320   credentials = g_credentials_new ();
321
322   vector.buffer = &nul_byte;
323   vector.size = 1;
324
325   if (g_unix_credentials_message_is_supported ())
326     {
327       scm = g_unix_credentials_message_new_with_credentials (credentials);
328       num_messages = 1;
329     }
330   else
331     {
332       scm = NULL;
333       num_messages = 0;
334     }
335
336   g_object_get (connection, "socket", &socket, NULL);
337   if (g_socket_send_message (socket,
338                              NULL, /* address */
339                              &vector,
340                              1,
341                              &scm,
342                              num_messages,
343                              G_SOCKET_MSG_NONE,
344                              cancellable,
345                              error) != 1)
346     {
347       g_prefix_error (error, _("Error sending credentials: "));
348       goto out;
349     }
350
351   ret = TRUE;
352
353  out:
354   g_object_unref (socket);
355   if (scm != NULL)
356     g_object_unref (scm);
357   g_object_unref (credentials);
358   return ret;
359 }
360
361 static void
362 send_credentials_async_thread (GSimpleAsyncResult *result,
363                                GObject            *object,
364                                GCancellable       *cancellable)
365 {
366   GError *error = NULL;
367
368   if (!g_unix_connection_send_credentials (G_UNIX_CONNECTION (object),
369                                            cancellable,
370                                            &error))
371     {
372       g_simple_async_result_take_error (result, error);
373     }
374 }
375
376 /**
377  * g_unix_connection_send_credentials_async:
378  * @connection: A #GUnixConnection.
379  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
380  * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied
381  * @user_data: (closure): the data to pass to callback function
382  *
383  * Asynchronously send credentials.
384  *
385  * For more details, see g_unix_connection_send_credentials() which is
386  * the synchronous version of this call.
387  *
388  * When the operation is finished, @callback will be called. You can then call
389  * g_unix_connection_send_credentials_finish() to get the result of the operation.
390  *
391  * Since: 2.32
392  **/
393 void
394 g_unix_connection_send_credentials_async (GUnixConnection      *connection,
395                                           GCancellable         *cancellable,
396                                           GAsyncReadyCallback   callback,
397                                           gpointer              user_data)
398 {
399   GSimpleAsyncResult *result;
400
401   result = g_simple_async_result_new (G_OBJECT (connection),
402                                       callback, user_data,
403                                       g_unix_connection_send_credentials_async);
404
405   g_simple_async_result_run_in_thread (result,
406                                        send_credentials_async_thread,
407                                        G_PRIORITY_DEFAULT,
408                                        cancellable);
409   g_object_unref (result);
410 }
411
412 /**
413  * g_unix_connection_send_credentials_finish:
414  * @connection: A #GUnixConnection.
415  * @result: a #GAsyncResult.
416  * @error: a #GError, or %NULL
417  *
418  * Finishes an asynchronous send credentials operation started with
419  * g_unix_connection_send_credentials_async().
420  *
421  * Returns: %TRUE if the operation was successful, otherwise %FALSE.
422  *
423  * Since: 2.32
424  **/
425 gboolean
426 g_unix_connection_send_credentials_finish (GUnixConnection *connection,
427                                            GAsyncResult    *result,
428                                            GError         **error)
429 {
430   g_return_val_if_fail (
431       g_simple_async_result_is_valid (result,
432                                       G_OBJECT (connection),
433                                       g_unix_connection_send_credentials_async),
434       FALSE);
435
436   if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result),
437                                              error))
438     return FALSE;
439
440
441   return TRUE;
442 }
443
444 /**
445  * g_unix_connection_receive_credentials:
446  * @connection: A #GUnixConnection.
447  * @cancellable: (allow-none): A #GCancellable or %NULL.
448  * @error: Return location for error or %NULL.
449  *
450  * Receives credentials from the sending end of the connection.  The
451  * sending end has to call g_unix_connection_send_credentials() (or
452  * similar) for this to work.
453  *
454  * As well as reading the credentials this also reads (and discards) a
455  * single byte from the stream, as this is required for credentials
456  * passing to work on some implementations.
457  *
458  * Other ways to exchange credentials with a foreign peer includes the
459  * #GUnixCredentialsMessage type and g_socket_get_credentials() function.
460  *
461  * Returns: (transfer full): Received credentials on success (free with
462  * g_object_unref()), %NULL if @error is set.
463  *
464  * Since: 2.26
465  */
466 GCredentials *
467 g_unix_connection_receive_credentials (GUnixConnection      *connection,
468                                        GCancellable         *cancellable,
469                                        GError              **error)
470 {
471   GCredentials *ret;
472   GSocketControlMessage **scms;
473   gint nscm;
474   GSocket *socket;
475   gint n;
476   gssize num_bytes_read;
477 #ifdef __linux__
478   gboolean turn_off_so_passcreds;
479 #endif
480
481   g_return_val_if_fail (G_IS_UNIX_CONNECTION (connection), NULL);
482   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
483
484   ret = NULL;
485   scms = NULL;
486
487   g_object_get (connection, "socket", &socket, NULL);
488
489   /* On Linux, we need to turn on SO_PASSCRED if it isn't enabled
490    * already. We also need to turn it off when we're done.  See
491    * #617483 for more discussion.
492    */
493 #ifdef __linux__
494   {
495     gint opt_val;
496     socklen_t opt_len;
497
498     turn_off_so_passcreds = FALSE;
499     opt_val = 0;
500     opt_len = sizeof (gint);
501     if (getsockopt (g_socket_get_fd (socket),
502                     SOL_SOCKET,
503                     SO_PASSCRED,
504                     &opt_val,
505                     &opt_len) != 0)
506       {
507         g_set_error (error,
508                      G_IO_ERROR,
509                      g_io_error_from_errno (errno),
510                      _("Error checking if SO_PASSCRED is enabled for socket: %s"),
511                      strerror (errno));
512         goto out;
513       }
514     if (opt_len != sizeof (gint))
515       {
516         g_set_error (error,
517                      G_IO_ERROR,
518                      G_IO_ERROR_FAILED,
519                      _("Unexpected option length while checking if SO_PASSCRED is enabled for socket. "
520                        "Expected %d bytes, got %d"),
521                      (gint) sizeof (gint), (gint) opt_len);
522         goto out;
523       }
524     if (opt_val == 0)
525       {
526         opt_val = 1;
527         if (setsockopt (g_socket_get_fd (socket),
528                         SOL_SOCKET,
529                         SO_PASSCRED,
530                         &opt_val,
531                         sizeof opt_val) != 0)
532           {
533             g_set_error (error,
534                          G_IO_ERROR,
535                          g_io_error_from_errno (errno),
536                          _("Error enabling SO_PASSCRED: %s"),
537                          strerror (errno));
538             goto out;
539           }
540         turn_off_so_passcreds = TRUE;
541       }
542   }
543 #endif
544
545   g_type_ensure (G_TYPE_UNIX_CREDENTIALS_MESSAGE);
546   num_bytes_read = g_socket_receive_message (socket,
547                                              NULL, /* GSocketAddress **address */
548                                              NULL,
549                                              0,
550                                              &scms,
551                                              &nscm,
552                                              NULL,
553                                              cancellable,
554                                              error);
555   if (num_bytes_read != 1)
556     {
557       /* Handle situation where g_socket_receive_message() returns
558        * 0 bytes and not setting @error
559        */
560       if (num_bytes_read == 0 && error != NULL && *error == NULL)
561         {
562           g_set_error_literal (error,
563                                G_IO_ERROR,
564                                G_IO_ERROR_FAILED,
565                                _("Expecting to read a single byte for receiving credentials but read zero bytes"));
566         }
567       goto out;
568     }
569
570   if (g_unix_credentials_message_is_supported () &&
571       /* Fall back on get_credentials if the other side didn't send the credentials */
572       nscm > 0)
573     {
574       if (nscm != 1)
575         {
576           g_set_error (error,
577                        G_IO_ERROR,
578                        G_IO_ERROR_FAILED,
579                        _("Expecting 1 control message, got %d"),
580                        nscm);
581           goto out;
582         }
583
584       if (!G_IS_UNIX_CREDENTIALS_MESSAGE (scms[0]))
585         {
586           g_set_error_literal (error,
587                                G_IO_ERROR,
588                                G_IO_ERROR_FAILED,
589                                _("Unexpected type of ancillary data"));
590           goto out;
591         }
592
593       ret = g_unix_credentials_message_get_credentials (G_UNIX_CREDENTIALS_MESSAGE (scms[0]));
594       g_object_ref (ret);
595     }
596   else
597     {
598       if (nscm != 0)
599         {
600           g_set_error (error,
601                        G_IO_ERROR,
602                        G_IO_ERROR_FAILED,
603                        _("Not expecting control message, but got %d"),
604                        nscm);
605           goto out;
606         }
607       else
608         {
609           ret = g_socket_get_credentials (socket, error);
610         }
611     }
612
613  out:
614
615 #ifdef __linux__
616   if (turn_off_so_passcreds)
617     {
618       gint opt_val;
619       opt_val = 0;
620       if (setsockopt (g_socket_get_fd (socket),
621                       SOL_SOCKET,
622                       SO_PASSCRED,
623                       &opt_val,
624                       sizeof opt_val) != 0)
625         {
626           g_set_error (error,
627                        G_IO_ERROR,
628                        g_io_error_from_errno (errno),
629                        _("Error while disabling SO_PASSCRED: %s"),
630                        strerror (errno));
631           goto out;
632         }
633     }
634 #endif
635
636   if (scms != NULL)
637     {
638       for (n = 0; n < nscm; n++)
639         g_object_unref (scms[n]);
640       g_free (scms);
641     }
642   g_object_unref (socket);
643   return ret;
644 }
645
646 static void
647 receive_credentials_async_thread (GSimpleAsyncResult *result,
648                                   GObject            *object,
649                                   GCancellable       *cancellable)
650 {
651   GCredentials *creds;
652   GError *error = NULL;
653
654   creds = g_unix_connection_receive_credentials (G_UNIX_CONNECTION (object),
655                                                  cancellable,
656                                                  &error);
657
658   if (creds == NULL)
659     g_simple_async_result_take_error (result, error);
660   else
661     g_simple_async_result_set_op_res_gpointer (result, creds, g_object_unref);
662 }
663
664 /**
665  * g_unix_connection_receive_credentials_async:
666  * @connection: A #GUnixConnection.
667  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
668  * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied
669  * @user_data: (closure): the data to pass to callback function
670  *
671  * Asynchronously receive credentials.
672  *
673  * For more details, see g_unix_connection_receive_credentials() which is
674  * the synchronous version of this call.
675  *
676  * When the operation is finished, @callback will be called. You can then call
677  * g_unix_connection_receive_credentials_finish() to get the result of the operation.
678  *
679  * Since: 2.32
680  **/
681 void
682 g_unix_connection_receive_credentials_async (GUnixConnection      *connection,
683                                               GCancellable         *cancellable,
684                                               GAsyncReadyCallback   callback,
685                                               gpointer              user_data)
686 {
687   GSimpleAsyncResult *result;
688
689   result = g_simple_async_result_new (G_OBJECT (connection),
690                                       callback, user_data,
691                                       g_unix_connection_receive_credentials_async);
692
693   g_simple_async_result_run_in_thread (result,
694                                        receive_credentials_async_thread,
695                                        G_PRIORITY_DEFAULT,
696                                        cancellable);
697
698   g_object_unref (result);
699 }
700
701 /**
702  * g_unix_connection_receive_credentials_finish:
703  * @connection: A #GUnixConnection.
704  * @result: a #GAsyncResult.
705  * @error: a #GError, or %NULL
706  *
707  * Finishes an asynchronous receive credentials operation started with
708  * g_unix_connection_receive_credentials_async().
709  *
710  * Returns: (transfer full): a #GCredentials, or %NULL on error.
711  *     Free the returned object with g_object_unref().
712  *
713  * Since: 2.32
714  **/
715 GCredentials *
716 g_unix_connection_receive_credentials_finish (GUnixConnection *connection,
717                                               GAsyncResult    *result,
718                                               GError         **error)
719 {
720   g_return_val_if_fail (
721       g_simple_async_result_is_valid (result,
722                                       G_OBJECT (connection),
723                                       g_unix_connection_receive_credentials_async),
724       NULL);
725
726   if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result),
727                                              error))
728     return NULL;
729
730   return g_object_ref (g_simple_async_result_get_op_res_gpointer (
731       G_SIMPLE_ASYNC_RESULT (result)));
732 }