20c6129f92af39922dcfc8bf93a18cab26e6e44b
[platform/upstream/glib.git] / gio / gdbusprivate.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2009 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: David Zeuthen <davidz@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27
28 #ifdef G_OS_UNIX
29 #include <gio/gunixconnection.h>
30 #include <gio/gunixfdmessage.h>
31 #include "gunixcredentialsmessage.h"
32 #include <unistd.h>
33 #endif
34
35 #include "giotypes.h"
36 #include "gsocket.h"
37 #include "gdbusprivate.h"
38 #include "gdbusmessage.h"
39 #include "gdbuserror.h"
40 #include "gdbusintrospection.h"
41 #include "gasyncresult.h"
42 #include "gsimpleasyncresult.h"
43 #include "ginputstream.h"
44 #include "giostream.h"
45 #include "gsocketcontrolmessage.h"
46
47 #ifdef G_OS_UNIX
48 #include <unistd.h>
49 #include "gunixfdmessage.h"
50 #include "gunixconnection.h"
51 #endif
52
53 #include "glibintl.h"
54 #include "gioalias.h"
55
56 /* ---------------------------------------------------------------------------------------------------- */
57
58 static gchar *
59 hexdump (const gchar *data, gsize len, guint indent)
60 {
61  guint n, m;
62  GString *ret;
63
64  ret = g_string_new (NULL);
65
66  for (n = 0; n < len; n += 16)
67    {
68      g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
69
70      for (m = n; m < n + 16; m++)
71        {
72          if (m > n && (m%4) == 0)
73            g_string_append_c (ret, ' ');
74          if (m < len)
75            g_string_append_printf (ret, "%02x ", (guchar) data[m]);
76          else
77            g_string_append (ret, "   ");
78        }
79
80      g_string_append (ret, "   ");
81
82      for (m = n; m < len && m < n + 16; m++)
83        g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
84
85      g_string_append_c (ret, '\n');
86    }
87
88  return g_string_free (ret, FALSE);
89 }
90
91 /* ---------------------------------------------------------------------------------------------------- */
92
93 /* Unfortunately ancillary messages are discarded when reading from a
94  * socket using the GSocketInputStream abstraction. So we provide a
95  * very GInputStream-ish API that uses GSocket in this case (very
96  * similar to GSocketInputStream).
97  */
98
99 typedef struct
100 {
101   GSocket *socket;
102   GCancellable *cancellable;
103
104   void *buffer;
105   gsize count;
106
107   GSocketControlMessage ***messages;
108   gint *num_messages;
109
110   GSimpleAsyncResult *simple;
111
112   gboolean from_mainloop;
113 } ReadWithControlData;
114
115 static void
116 read_with_control_data_free (ReadWithControlData *data)
117 {
118   g_object_unref (data->socket);
119   if (data->cancellable != NULL)
120     g_object_unref (data->cancellable);
121   g_free (data);
122 }
123
124 static gboolean
125 _g_socket_read_with_control_messages_ready (GSocket      *socket,
126                                             GIOCondition  condition,
127                                             gpointer      user_data)
128 {
129   ReadWithControlData *data = user_data;
130   GError *error;
131   gssize result;
132   GInputVector vector;
133
134   error = NULL;
135   vector.buffer = data->buffer;
136   vector.size = data->count;
137   result = g_socket_receive_message (data->socket,
138                                      NULL, /* address */
139                                      &vector,
140                                      1,
141                                      data->messages,
142                                      data->num_messages,
143                                      NULL,
144                                      data->cancellable,
145                                      &error);
146   if (result >= 0)
147     {
148       g_simple_async_result_set_op_res_gssize (data->simple, result);
149     }
150   else
151     {
152       g_assert (error != NULL);
153       g_simple_async_result_set_from_error (data->simple, error);
154       g_error_free (error);
155     }
156
157   if (data->from_mainloop)
158     g_simple_async_result_complete (data->simple);
159   else
160     g_simple_async_result_complete_in_idle (data->simple);
161
162   return FALSE;
163 }
164
165 static void
166 _g_socket_read_with_control_messages (GSocket                 *socket,
167                                       void                    *buffer,
168                                       gsize                    count,
169                                       GSocketControlMessage ***messages,
170                                       gint                    *num_messages,
171                                       gint                     io_priority,
172                                       GCancellable            *cancellable,
173                                       GAsyncReadyCallback      callback,
174                                       gpointer                 user_data)
175 {
176   ReadWithControlData *data;
177
178   data = g_new0 (ReadWithControlData, 1);
179   data->socket = g_object_ref (socket);
180   data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
181   data->buffer = buffer;
182   data->count = count;
183   data->messages = messages;
184   data->num_messages = num_messages;
185
186   data->simple = g_simple_async_result_new (G_OBJECT (socket),
187                                             callback,
188                                             user_data,
189                                             _g_socket_read_with_control_messages);
190
191   if (!g_socket_condition_check (socket, G_IO_IN))
192     {
193       GSource *source;
194       data->from_mainloop = TRUE;
195       source = g_socket_create_source (data->socket,
196                                        G_IO_IN | G_IO_HUP | G_IO_ERR,
197                                        cancellable);
198       g_source_set_callback (source,
199                              (GSourceFunc) _g_socket_read_with_control_messages_ready,
200                              data,
201                              (GDestroyNotify) read_with_control_data_free);
202       g_source_attach (source, g_main_context_get_thread_default ());
203       g_source_unref (source);
204     }
205   else
206     {
207       _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
208       read_with_control_data_free (data);
209     }
210 }
211
212 static gssize
213 _g_socket_read_with_control_messages_finish (GSocket       *socket,
214                                              GAsyncResult  *result,
215                                              GError       **error)
216 {
217   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
218
219   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
220   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
221
222   if (g_simple_async_result_propagate_error (simple, error))
223       return -1;
224   else
225     return g_simple_async_result_get_op_res_gssize (simple);
226 }
227
228 /* ---------------------------------------------------------------------------------------------------- */
229
230 G_LOCK_DEFINE_STATIC (shared_thread_lock);
231
232 typedef struct
233 {
234   gint num_users;
235   GThread *thread;
236   GMainContext *context;
237   GMainLoop *loop;
238 } SharedThreadData;
239
240 static SharedThreadData *shared_thread_data = NULL;
241
242 static gpointer
243 shared_thread_func (gpointer data)
244 {
245   g_main_context_push_thread_default (shared_thread_data->context);
246   g_main_loop_run (shared_thread_data->loop);
247   g_main_context_pop_thread_default (shared_thread_data->context);
248   return NULL;
249 }
250
251 typedef void (*GDBusSharedThreadFunc) (gpointer user_data);
252
253 typedef struct
254 {
255   GDBusSharedThreadFunc func;
256   gpointer              user_data;
257   gboolean              done;
258 } CallerData;
259
260 static gboolean
261 invoke_caller (gpointer user_data)
262 {
263   CallerData *data = user_data;
264   data->func (data->user_data);
265   data->done = TRUE;
266   return FALSE;
267 }
268
269 static void
270 _g_dbus_shared_thread_ref (GDBusSharedThreadFunc func,
271                            gpointer              user_data)
272 {
273   GError *error;
274   GSource *idle_source;
275   CallerData *data;
276
277   G_LOCK (shared_thread_lock);
278
279   if (shared_thread_data != NULL)
280     {
281       shared_thread_data->num_users += 1;
282       goto have_thread;
283     }
284
285   shared_thread_data = g_new0 (SharedThreadData, 1);
286   shared_thread_data->num_users = 1;
287
288   error = NULL;
289   shared_thread_data->context = g_main_context_new ();
290   shared_thread_data->loop = g_main_loop_new (shared_thread_data->context, FALSE);
291   shared_thread_data->thread = g_thread_create (shared_thread_func,
292                                                 NULL,
293                                                 TRUE,
294                                                 &error);
295   g_assert_no_error (error);
296
297  have_thread:
298
299   data = g_new0 (CallerData, 1);
300   data->func = func;
301   data->user_data = user_data;
302   data->done = FALSE;
303
304   idle_source = g_idle_source_new ();
305   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
306   g_source_set_callback (idle_source,
307                          invoke_caller,
308                          data,
309                          NULL);
310   g_source_attach (idle_source, shared_thread_data->context);
311   g_source_unref (idle_source);
312
313   /* wait for the user code to run.. hmm.. probably use a condition variable instead */
314   while (!data->done)
315     g_thread_yield ();
316
317   g_free (data);
318
319   G_UNLOCK (shared_thread_lock);
320 }
321
322 static void
323 _g_dbus_shared_thread_unref (void)
324 {
325   /* TODO: actually destroy the shared thread here */
326 #if 0
327   G_LOCK (shared_thread_lock);
328   g_assert (shared_thread_data != NULL);
329   shared_thread_data->num_users -= 1;
330   if (shared_thread_data->num_users == 0)
331     {
332       g_main_loop_quit (shared_thread_data->loop);
333       //g_thread_join (shared_thread_data->thread);
334       g_main_loop_unref (shared_thread_data->loop);
335       g_main_context_unref (shared_thread_data->context);
336       g_free (shared_thread_data);
337       shared_thread_data = NULL;
338       G_UNLOCK (shared_thread_lock);
339     }
340   else
341     {
342       G_UNLOCK (shared_thread_lock);
343     }
344 #endif
345 }
346
347 /* ---------------------------------------------------------------------------------------------------- */
348
349 struct GDBusWorker
350 {
351   volatile gint                       ref_count;
352   gboolean                            stopped;
353   GIOStream                          *stream;
354   GDBusCapabilityFlags                capabilities;
355   GCancellable                       *cancellable;
356   GDBusWorkerMessageReceivedCallback  message_received_callback;
357   GDBusWorkerDisconnectedCallback     disconnected_callback;
358   gpointer                            user_data;
359
360   GThread                            *thread;
361
362   /* if not NULL, stream is GSocketConnection */
363   GSocket *socket;
364
365   /* used for reading */
366   GMutex                             *read_lock;
367   gchar                              *read_buffer;
368   gsize                               read_buffer_allocated_size;
369   gsize                               read_buffer_cur_size;
370   gsize                               read_buffer_bytes_wanted;
371   GUnixFDList                        *read_fd_list;
372   GSocketControlMessage             **read_ancillary_messages;
373   gint                                read_num_ancillary_messages;
374
375   /* used for writing */
376   GMutex                             *write_lock;
377   GQueue                             *write_queue;
378   gboolean                            write_is_pending;
379 };
380
381 struct _MessageToWriteData ;
382 typedef struct _MessageToWriteData MessageToWriteData;
383
384 static void message_to_write_data_free (MessageToWriteData *data);
385
386 static GDBusWorker *
387 _g_dbus_worker_ref (GDBusWorker *worker)
388 {
389   g_atomic_int_inc (&worker->ref_count);
390   return worker;
391 }
392
393 static void
394 _g_dbus_worker_unref (GDBusWorker *worker)
395 {
396   if (g_atomic_int_dec_and_test (&worker->ref_count))
397     {
398       _g_dbus_shared_thread_unref ();
399
400       g_object_unref (worker->stream);
401
402       g_mutex_free (worker->read_lock);
403       g_object_unref (worker->cancellable);
404       if (worker->read_fd_list != NULL)
405         g_object_unref (worker->read_fd_list);
406
407       g_mutex_free (worker->write_lock);
408       g_queue_foreach (worker->write_queue,
409                        (GFunc) message_to_write_data_free,
410                        NULL);
411       g_queue_free (worker->write_queue);
412       g_free (worker);
413     }
414 }
415
416 static void
417 _g_dbus_worker_emit_disconnected (GDBusWorker  *worker,
418                                   gboolean      remote_peer_vanished,
419                                   GError       *error)
420 {
421   if (!worker->stopped)
422     worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
423 }
424
425 static void
426 _g_dbus_worker_emit_message (GDBusWorker  *worker,
427                              GDBusMessage *message)
428 {
429   if (!worker->stopped)
430     worker->message_received_callback (worker, message, worker->user_data);
431 }
432
433 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
434
435 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
436 static void
437 _g_dbus_worker_do_read_cb (GInputStream  *input_stream,
438                            GAsyncResult  *res,
439                            gpointer       user_data)
440 {
441   GDBusWorker *worker = user_data;
442   GError *error;
443   gssize bytes_read;
444
445   g_mutex_lock (worker->read_lock);
446
447   /* If already stopped, don't even process the reply */
448   if (worker->stopped)
449     goto out;
450
451   error = NULL;
452   if (worker->socket == NULL)
453     bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
454                                              res,
455                                              &error);
456   else
457     bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
458                                                               res,
459                                                               &error);
460   if (worker->read_num_ancillary_messages > 0)
461     {
462       gint n;
463       for (n = 0; n < worker->read_num_ancillary_messages; n++)
464         {
465           GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
466
467           if (FALSE)
468             {
469             }
470 #ifdef G_OS_UNIX
471           else if (G_IS_UNIX_FD_MESSAGE (control_message))
472             {
473               GUnixFDMessage *fd_message;
474               gint *fds;
475               gint num_fds;
476
477               fd_message = G_UNIX_FD_MESSAGE (control_message);
478               fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
479               if (worker->read_fd_list == NULL)
480                 {
481                   worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
482                 }
483               else
484                 {
485                   gint n;
486                   for (n = 0; n < num_fds; n++)
487                     {
488                       /* TODO: really want a append_steal() */
489                       g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
490                       close (fds[n]);
491                     }
492                 }
493               g_free (fds);
494             }
495           else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
496             {
497               /* do nothing */
498             }
499 #endif
500           else
501             {
502               if (error == NULL)
503                 {
504                   g_set_error (&error,
505                                G_IO_ERROR,
506                                G_IO_ERROR_FAILED,
507                                "Unexpected ancillary message of type %s received from peer",
508                                g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
509                   _g_dbus_worker_emit_disconnected (worker, TRUE, error);
510                   g_error_free (error);
511                   g_object_unref (control_message);
512                   n++;
513                   while (n < worker->read_num_ancillary_messages)
514                     g_object_unref (worker->read_ancillary_messages[n++]);
515                   g_free (worker->read_ancillary_messages);
516                   goto out;
517                 }
518             }
519           g_object_unref (control_message);
520         }
521       g_free (worker->read_ancillary_messages);
522     }
523
524   if (bytes_read == -1)
525     {
526       _g_dbus_worker_emit_disconnected (worker, TRUE, error);
527       g_error_free (error);
528       goto out;
529     }
530
531 #if 0
532   g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
533            (gint) bytes_read,
534            g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
535            g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
536            g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
537                                      G_IO_IN | G_IO_OUT | G_IO_HUP),
538            worker->stream,
539            worker);
540 #endif
541
542   /* TODO: hmm, hmm... */
543   if (bytes_read == 0)
544     {
545       g_set_error (&error,
546                    G_IO_ERROR,
547                    G_IO_ERROR_FAILED,
548                    "Underlying GIOStream returned 0 bytes on an async read");
549       _g_dbus_worker_emit_disconnected (worker, TRUE, error);
550       g_error_free (error);
551       goto out;
552     }
553
554   worker->read_buffer_cur_size += bytes_read;
555   if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
556     {
557       /* OK, got what we asked for! */
558       if (worker->read_buffer_bytes_wanted == 16)
559         {
560           gssize message_len;
561           /* OK, got the header - determine how many more bytes are needed */
562           error = NULL;
563           message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
564                                                      16,
565                                                      &error);
566           if (message_len == -1)
567             {
568               g_warning ("_g_dbus_worker_do_read_cb: error determing bytes needed: %s", error->message);
569               _g_dbus_worker_emit_disconnected (worker, FALSE, error);
570               g_error_free (error);
571               goto out;
572             }
573
574           worker->read_buffer_bytes_wanted = message_len;
575           _g_dbus_worker_do_read_unlocked (worker);
576         }
577       else
578         {
579           GDBusMessage *message;
580           error = NULL;
581
582           /* TODO: use connection->priv->auth to decode the message */
583
584           message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
585                                                   worker->read_buffer_cur_size,
586                                                   &error);
587           if (message == NULL)
588             {
589               _g_dbus_worker_emit_disconnected (worker, FALSE, error);
590               g_error_free (error);
591               goto out;
592             }
593
594           if (worker->read_fd_list != NULL)
595             {
596               g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
597               worker->read_fd_list = NULL;
598             }
599
600           if (G_UNLIKELY (_g_dbus_debug_message ()))
601             {
602               gchar *s;
603               g_print ("========================================================================\n"
604                        "GDBus-debug:Message:\n"
605                        "  <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
606                        worker->read_buffer_cur_size);
607               s = g_dbus_message_print (message, 2);
608               g_print ("%s", s);
609               g_free (s);
610               s = hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
611               g_print ("%s\n", s);
612               g_free (s);
613             }
614
615           /* yay, got a message, go deliver it */
616           _g_dbus_worker_emit_message (worker, message);
617           g_object_unref (message);
618
619           /* start reading another message! */
620           worker->read_buffer_bytes_wanted = 0;
621           worker->read_buffer_cur_size = 0;
622           _g_dbus_worker_do_read_unlocked (worker);
623         }
624     }
625   else
626     {
627       /* didn't get all the bytes we requested - so repeat the request... */
628       _g_dbus_worker_do_read_unlocked (worker);
629     }
630
631  out:
632   g_mutex_unlock (worker->read_lock);
633
634   /* gives up the reference acquired when calling g_input_stream_read_async() */
635   _g_dbus_worker_unref (worker);
636 }
637
638 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
639 static void
640 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
641 {
642   /* if bytes_wanted is zero, it means start reading a message */
643   if (worker->read_buffer_bytes_wanted == 0)
644     {
645       worker->read_buffer_cur_size = 0;
646       worker->read_buffer_bytes_wanted = 16;
647     }
648
649   /* ensure we have a (big enough) buffer */
650   if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
651     {
652       /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
653       worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
654       worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
655     }
656
657   if (worker->socket == NULL)
658     g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
659                                worker->read_buffer + worker->read_buffer_cur_size,
660                                worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
661                                G_PRIORITY_DEFAULT,
662                                worker->cancellable,
663                                (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
664                                _g_dbus_worker_ref (worker));
665   else
666     {
667       worker->read_ancillary_messages = NULL;
668       worker->read_num_ancillary_messages = 0;
669       _g_socket_read_with_control_messages (worker->socket,
670                                             worker->read_buffer + worker->read_buffer_cur_size,
671                                             worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
672                                             &worker->read_ancillary_messages,
673                                             &worker->read_num_ancillary_messages,
674                                             G_PRIORITY_DEFAULT,
675                                             worker->cancellable,
676                                             (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
677                                             _g_dbus_worker_ref (worker));
678     }
679 }
680
681 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
682 static void
683 _g_dbus_worker_do_read (GDBusWorker *worker)
684 {
685   g_mutex_lock (worker->read_lock);
686   _g_dbus_worker_do_read_unlocked (worker);
687   g_mutex_unlock (worker->read_lock);
688 }
689
690 /* ---------------------------------------------------------------------------------------------------- */
691
692 struct _MessageToWriteData
693 {
694   GDBusMessage *message;
695   gchar        *blob;
696   gsize         blob_size;
697 };
698
699 static void
700 message_to_write_data_free (MessageToWriteData *data)
701 {
702   g_object_unref (data->message);
703   g_free (data->blob);
704   g_free (data);
705 }
706
707 /* ---------------------------------------------------------------------------------------------------- */
708
709 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
710 static gboolean
711 write_message (GDBusWorker         *worker,
712                MessageToWriteData  *data,
713                GError             **error)
714 {
715   gboolean ret;
716
717   g_return_val_if_fail (data->blob_size > 16, FALSE);
718
719   ret = FALSE;
720
721   /* First, the initial 16 bytes - special case UNIX sockets here
722    * since it may involve writing an ancillary message with file
723    * descriptors
724    */
725 #ifdef G_OS_UNIX
726   {
727     GOutputVector vector;
728     GSocketControlMessage *message;
729     GUnixFDList *fd_list;
730     gssize bytes_written;
731
732     fd_list = g_dbus_message_get_unix_fd_list (data->message);
733
734     message = NULL;
735     if (fd_list != NULL)
736       {
737         if (!G_IS_UNIX_CONNECTION (worker->stream))
738           {
739             g_set_error (error,
740                          G_IO_ERROR,
741                          G_IO_ERROR_INVALID_ARGUMENT,
742                          "Tried sending a file descriptor on unsupported stream of type %s",
743                          g_type_name (G_TYPE_FROM_INSTANCE (worker->stream)));
744             goto out;
745           }
746         else if (!(worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
747           {
748             g_set_error_literal (error,
749                                  G_IO_ERROR,
750                                  G_IO_ERROR_INVALID_ARGUMENT,
751                                  "Tried sending a file descriptor but remote peer does not support this capability");
752             goto out;
753           }
754         message = g_unix_fd_message_new_with_fd_list (fd_list);
755       }
756
757     vector.buffer = data->blob;
758     vector.size = 16;
759
760     bytes_written = g_socket_send_message (worker->socket,
761                                            NULL, /* address */
762                                            &vector,
763                                            1,
764                                            message != NULL ? &message : NULL,
765                                            message != NULL ? 1 : 0,
766                                            G_SOCKET_MSG_NONE,
767                                            worker->cancellable,
768                                            error);
769     if (bytes_written == -1)
770       {
771         g_prefix_error (error, _("Error writing first 16 bytes of message to socket: "));
772         if (message != NULL)
773           g_object_unref (message);
774         goto out;
775       }
776     if (message != NULL)
777       g_object_unref (message);
778
779     if (bytes_written < 16)
780       {
781         /* TODO: I think this needs to be handled ... are we guaranteed that the ancillary
782          * messages are sent?
783          */
784         g_assert_not_reached ();
785       }
786   }
787 #else
788   /* write the first 16 bytes (guaranteed to return an error if everything can't be written) */
789   if (!g_output_stream_write_all (g_io_stream_get_output_stream (worker->stream),
790                                   (const gchar *) data->blob,
791                                   16,
792                                   NULL, /* bytes_written */
793                                   worker->cancellable, /* cancellable */
794                                   error))
795     goto out;
796 #endif
797
798   /* Then write the rest of the message (guaranteed to return an error if everything can't be written) */
799   if (!g_output_stream_write_all (g_io_stream_get_output_stream (worker->stream),
800                                   (const gchar *) data->blob + 16,
801                                   data->blob_size - 16,
802                                   NULL, /* bytes_written */
803                                   worker->cancellable, /* cancellable */
804                                   error))
805     goto out;
806
807   ret = TRUE;
808
809   if (G_UNLIKELY (_g_dbus_debug_message ()))
810     {
811       gchar *s;
812       g_print ("========================================================================\n"
813                "GDBus-debug:Message:\n"
814                "  >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
815                data->blob_size);
816       s = g_dbus_message_print (data->message, 2);
817       g_print ("%s", s);
818       g_free (s);
819       s = hexdump (data->blob, data->blob_size, 2);
820       g_print ("%s\n", s);
821       g_free (s);
822     }
823
824  out:
825   return ret;
826 }
827
828 /* ---------------------------------------------------------------------------------------------------- */
829
830 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
831 static gboolean
832 write_message_in_idle_cb (gpointer user_data)
833 {
834   GDBusWorker *worker = user_data;
835   gboolean more_writes_are_pending;
836   MessageToWriteData *data;
837   GError *error;
838
839   g_mutex_lock (worker->write_lock);
840
841   data = g_queue_pop_head (worker->write_queue);
842   g_assert (data != NULL);
843
844   error = NULL;
845   if (!write_message (worker,
846                       data,
847                       &error))
848     {
849       /* TODO: handle */
850       _g_dbus_worker_emit_disconnected (worker, TRUE, error);
851       g_error_free (error);
852     }
853   message_to_write_data_free (data);
854
855   more_writes_are_pending = (g_queue_get_length (worker->write_queue) > 0);
856
857   worker->write_is_pending = more_writes_are_pending;
858   g_mutex_unlock (worker->write_lock);
859
860   return more_writes_are_pending;
861 }
862
863 /* ---------------------------------------------------------------------------------------------------- */
864
865 /* can be called from any thread - steals blob */
866 void
867 _g_dbus_worker_send_message (GDBusWorker    *worker,
868                              GDBusMessage   *message,
869                              gchar          *blob,
870                              gsize           blob_len)
871 {
872   MessageToWriteData *data;
873
874   g_return_if_fail (G_IS_DBUS_MESSAGE (message));
875   g_return_if_fail (blob != NULL);
876   g_return_if_fail (blob_len > 16);
877
878   data = g_new0 (MessageToWriteData, 1);
879   data->message = g_object_ref (message);
880   data->blob = blob; /* steal! */
881   data->blob_size = blob_len;
882
883   g_mutex_lock (worker->write_lock);
884   g_queue_push_tail (worker->write_queue, data);
885   if (!worker->write_is_pending)
886     {
887       GSource *idle_source;
888
889       worker->write_is_pending = TRUE;
890
891       idle_source = g_idle_source_new ();
892       g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
893       g_source_set_callback (idle_source,
894                              write_message_in_idle_cb,
895                              _g_dbus_worker_ref (worker),
896                              (GDestroyNotify) _g_dbus_worker_unref);
897       g_source_attach (idle_source, shared_thread_data->context);
898       g_source_unref (idle_source);
899     }
900   g_mutex_unlock (worker->write_lock);
901 }
902
903 /* ---------------------------------------------------------------------------------------------------- */
904
905 static void
906 _g_dbus_worker_thread_begin_func (gpointer user_data)
907 {
908   GDBusWorker *worker = user_data;
909
910   worker->thread = g_thread_self ();
911
912   /* begin reading */
913   _g_dbus_worker_do_read (worker);
914 }
915
916 GDBusWorker *
917 _g_dbus_worker_new (GIOStream                          *stream,
918                     GDBusCapabilityFlags                capabilities,
919                     GDBusWorkerMessageReceivedCallback  message_received_callback,
920                     GDBusWorkerDisconnectedCallback     disconnected_callback,
921                     gpointer                            user_data)
922 {
923   GDBusWorker *worker;
924
925   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
926   g_return_val_if_fail (message_received_callback != NULL, NULL);
927   g_return_val_if_fail (disconnected_callback != NULL, NULL);
928
929   worker = g_new0 (GDBusWorker, 1);
930   worker->ref_count = 1;
931
932   worker->read_lock = g_mutex_new ();
933   worker->message_received_callback = message_received_callback;
934   worker->disconnected_callback = disconnected_callback;
935   worker->user_data = user_data;
936   worker->stream = g_object_ref (stream);
937   worker->capabilities = capabilities;
938   worker->cancellable = g_cancellable_new ();
939
940   worker->write_lock = g_mutex_new ();
941   worker->write_queue = g_queue_new ();
942
943   if (G_IS_SOCKET_CONNECTION (worker->stream))
944     worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
945
946   _g_dbus_shared_thread_ref (_g_dbus_worker_thread_begin_func, worker);
947
948   return worker;
949 }
950
951 /* This can be called from any thread - frees worker - guarantees no callbacks
952  * will ever be issued again
953  */
954 void
955 _g_dbus_worker_stop (GDBusWorker *worker)
956 {
957   /* If we're called in the worker thread it means we are called from
958    * a worker callback. This is fine, we just can't lock in that case since
959    * we're already holding the lock...
960    */
961   if (g_thread_self () != worker->thread)
962     g_mutex_lock (worker->read_lock);
963   worker->stopped = TRUE;
964   if (g_thread_self () != worker->thread)
965     g_mutex_unlock (worker->read_lock);
966
967   g_cancellable_cancel (worker->cancellable);
968   _g_dbus_worker_unref (worker);
969 }
970
971 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
972 #define G_DBUS_DEBUG_MESSAGE        (1<<1)
973 #define G_DBUS_DEBUG_ALL            0xffffffff
974 static gint _gdbus_debug_flags = 0;
975
976 gboolean
977 _g_dbus_debug_authentication (void)
978 {
979   _g_dbus_initialize ();
980   return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
981 }
982
983 gboolean
984 _g_dbus_debug_message (void)
985 {
986   _g_dbus_initialize ();
987   return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
988 }
989
990 /*
991  * _g_dbus_initialize:
992  *
993  * Does various one-time init things such as
994  *
995  *  - registering the G_DBUS_ERROR error domain
996  *  - parses the G_DBUS_DEBUG environment variable
997  */
998 void
999 _g_dbus_initialize (void)
1000 {
1001   static volatile gsize initialized = 0;
1002
1003   if (g_once_init_enter (&initialized))
1004     {
1005       volatile GQuark g_dbus_error_domain;
1006       const gchar *debug;
1007
1008       g_dbus_error_domain = G_DBUS_ERROR;
1009
1010       debug = g_getenv ("G_DBUS_DEBUG");
1011       if (debug != NULL)
1012         {
1013           gchar **tokens;
1014           guint n;
1015           tokens = g_strsplit (debug, ",", 0);
1016           for (n = 0; tokens[n] != NULL; n++)
1017             {
1018               if (g_strcmp0 (tokens[n], "authentication") == 0)
1019                 _gdbus_debug_flags |= G_DBUS_DEBUG_AUTHENTICATION;
1020               else if (g_strcmp0 (tokens[n], "message") == 0)
1021                 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1022               else if (g_strcmp0 (tokens[n], "all") == 0)
1023                 _gdbus_debug_flags |= G_DBUS_DEBUG_ALL;
1024             }
1025           g_strfreev (tokens);
1026         }
1027
1028       g_once_init_leave (&initialized, 1);
1029     }
1030 }
1031
1032 /* ---------------------------------------------------------------------------------------------------- */
1033
1034 gchar *
1035 _g_dbus_compute_complete_signature (GDBusArgInfo **args,
1036                                     gboolean       include_parentheses)
1037 {
1038   GString *s;
1039   guint n;
1040
1041   if (include_parentheses)
1042     s = g_string_new ("(");
1043   else
1044     s = g_string_new ("");
1045   if (args != NULL)
1046     for (n = 0; args[n] != NULL; n++)
1047       g_string_append (s, args[n]->signature);
1048
1049   if (include_parentheses)
1050     g_string_append_c (s, ')');
1051
1052   return g_string_free (s, FALSE);
1053 }
1054
1055 #define __G_DBUS_PRIVATE_C__
1056 #include "gioaliasdef.c"