b7d9336c5a72adaae579028c8227bed4fd59175d
[platform/upstream/glib.git] / gio / gdbusprivate.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2010 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 #include "giotypes.h"
29 #include "gsocket.h"
30 #include "gdbusprivate.h"
31 #include "gdbusmessage.h"
32 #include "gdbuserror.h"
33 #include "gdbusintrospection.h"
34 #include "gasyncresult.h"
35 #include "gsimpleasyncresult.h"
36 #include "ginputstream.h"
37 #include "gmemoryinputstream.h"
38 #include "giostream.h"
39 #include "glib/gstdio.h"
40 #include "gsocketcontrolmessage.h"
41 #include "gsocketconnection.h"
42 #include "gsocketoutputstream.h"
43
44 #ifdef G_OS_UNIX
45 #include "gunixfdmessage.h"
46 #include "gunixconnection.h"
47 #include "gunixcredentialsmessage.h"
48 #endif
49
50 #ifdef G_OS_WIN32
51 #include <windows.h>
52 #endif
53
54 #include "glibintl.h"
55
56 static gboolean _g_dbus_worker_do_initial_read (gpointer data);
57
58 /* ---------------------------------------------------------------------------------------------------- */
59
60 gchar *
61 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
62 {
63  guint n, m;
64  GString *ret;
65
66  ret = g_string_new (NULL);
67
68  for (n = 0; n < len; n += 16)
69    {
70      g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
71
72      for (m = n; m < n + 16; m++)
73        {
74          if (m > n && (m%4) == 0)
75            g_string_append_c (ret, ' ');
76          if (m < len)
77            g_string_append_printf (ret, "%02x ", (guchar) data[m]);
78          else
79            g_string_append (ret, "   ");
80        }
81
82      g_string_append (ret, "   ");
83
84      for (m = n; m < len && m < n + 16; m++)
85        g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
86
87      g_string_append_c (ret, '\n');
88    }
89
90  return g_string_free (ret, FALSE);
91 }
92
93 /* ---------------------------------------------------------------------------------------------------- */
94
95 /* Unfortunately ancillary messages are discarded when reading from a
96  * socket using the GSocketInputStream abstraction. So we provide a
97  * very GInputStream-ish API that uses GSocket in this case (very
98  * similar to GSocketInputStream).
99  */
100
101 typedef struct
102 {
103   GSocket *socket;
104   GCancellable *cancellable;
105
106   void *buffer;
107   gsize count;
108
109   GSocketControlMessage ***messages;
110   gint *num_messages;
111
112   GSimpleAsyncResult *simple;
113
114   gboolean from_mainloop;
115 } ReadWithControlData;
116
117 static void
118 read_with_control_data_free (ReadWithControlData *data)
119 {
120   g_object_unref (data->socket);
121   if (data->cancellable != NULL)
122     g_object_unref (data->cancellable);
123   g_object_unref (data->simple);
124   g_free (data);
125 }
126
127 static gboolean
128 _g_socket_read_with_control_messages_ready (GSocket      *socket,
129                                             GIOCondition  condition,
130                                             gpointer      user_data)
131 {
132   ReadWithControlData *data = user_data;
133   GError *error;
134   gssize result;
135   GInputVector vector;
136
137   error = NULL;
138   vector.buffer = data->buffer;
139   vector.size = data->count;
140   result = g_socket_receive_message (data->socket,
141                                      NULL, /* address */
142                                      &vector,
143                                      1,
144                                      data->messages,
145                                      data->num_messages,
146                                      NULL,
147                                      data->cancellable,
148                                      &error);
149   if (result >= 0)
150     {
151       g_simple_async_result_set_op_res_gssize (data->simple, result);
152     }
153   else
154     {
155       g_assert (error != NULL);
156       g_simple_async_result_take_error (data->simple, error);
157     }
158
159   if (data->from_mainloop)
160     g_simple_async_result_complete (data->simple);
161   else
162     g_simple_async_result_complete_in_idle (data->simple);
163
164   return FALSE;
165 }
166
167 static void
168 _g_socket_read_with_control_messages (GSocket                 *socket,
169                                       void                    *buffer,
170                                       gsize                    count,
171                                       GSocketControlMessage ***messages,
172                                       gint                    *num_messages,
173                                       gint                     io_priority,
174                                       GCancellable            *cancellable,
175                                       GAsyncReadyCallback      callback,
176                                       gpointer                 user_data)
177 {
178   ReadWithControlData *data;
179
180   data = g_new0 (ReadWithControlData, 1);
181   data->socket = g_object_ref (socket);
182   data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
183   data->buffer = buffer;
184   data->count = count;
185   data->messages = messages;
186   data->num_messages = num_messages;
187
188   data->simple = g_simple_async_result_new (G_OBJECT (socket),
189                                             callback,
190                                             user_data,
191                                             _g_socket_read_with_control_messages);
192   g_simple_async_result_set_check_cancellable (data->simple, cancellable);
193
194   if (!g_socket_condition_check (socket, G_IO_IN))
195     {
196       GSource *source;
197       data->from_mainloop = TRUE;
198       source = g_socket_create_source (data->socket,
199                                        G_IO_IN | G_IO_HUP | G_IO_ERR,
200                                        cancellable);
201       g_source_set_callback (source,
202                              (GSourceFunc) _g_socket_read_with_control_messages_ready,
203                              data,
204                              (GDestroyNotify) read_with_control_data_free);
205       g_source_attach (source, g_main_context_get_thread_default ());
206       g_source_unref (source);
207     }
208   else
209     {
210       _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
211       read_with_control_data_free (data);
212     }
213 }
214
215 static gssize
216 _g_socket_read_with_control_messages_finish (GSocket       *socket,
217                                              GAsyncResult  *result,
218                                              GError       **error)
219 {
220   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
221
222   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
223   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
224
225   if (g_simple_async_result_propagate_error (simple, error))
226       return -1;
227   else
228     return g_simple_async_result_get_op_res_gssize (simple);
229 }
230
231 /* ---------------------------------------------------------------------------------------------------- */
232
233 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
234
235 static GPtrArray *ensured_classes = NULL;
236
237 static void
238 ensure_type (GType gtype)
239 {
240   g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
241 }
242
243 static void
244 release_required_types (void)
245 {
246   g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
247   g_ptr_array_unref (ensured_classes);
248   ensured_classes = NULL;
249 }
250
251 static void
252 ensure_required_types (void)
253 {
254   g_assert (ensured_classes == NULL);
255   ensured_classes = g_ptr_array_new ();
256   ensure_type (G_TYPE_SIMPLE_ASYNC_RESULT);
257   ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
258 }
259 /* ---------------------------------------------------------------------------------------------------- */
260
261 typedef struct
262 {
263   volatile gint refcount;
264   GThread *thread;
265   GMainContext *context;
266   GMainLoop *loop;
267 } SharedThreadData;
268
269 static gpointer
270 gdbus_shared_thread_func (gpointer user_data)
271 {
272   SharedThreadData *data = user_data;
273
274   g_main_context_push_thread_default (data->context);
275   g_main_loop_run (data->loop);
276   g_main_context_pop_thread_default (data->context);
277
278   release_required_types ();
279
280   return NULL;
281 }
282
283 /* ---------------------------------------------------------------------------------------------------- */
284
285 static SharedThreadData *
286 _g_dbus_shared_thread_ref (void)
287 {
288   static gsize shared_thread_data = 0;
289   SharedThreadData *ret;
290
291   if (g_once_init_enter (&shared_thread_data))
292     {
293       SharedThreadData *data;
294
295       /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
296       ensure_required_types ();
297
298       data = g_new0 (SharedThreadData, 1);
299       data->refcount = 0;
300       
301       data->context = g_main_context_new ();
302       data->loop = g_main_loop_new (data->context, FALSE);
303       data->thread = g_thread_new ("gdbus",
304                                    gdbus_shared_thread_func,
305                                    data);
306       /* We can cast between gsize and gpointer safely */
307       g_once_init_leave (&shared_thread_data, (gsize) data);
308     }
309
310   ret = (SharedThreadData*) shared_thread_data;
311   g_atomic_int_inc (&ret->refcount);
312   return ret;
313 }
314
315 static void
316 _g_dbus_shared_thread_unref (SharedThreadData *data)
317 {
318   /* TODO: actually destroy the shared thread here */
319 #if 0
320   g_assert (data != NULL);
321   if (g_atomic_int_dec_and_test (&data->refcount))
322     {
323       g_main_loop_quit (data->loop);
324       //g_thread_join (data->thread);
325       g_main_loop_unref (data->loop);
326       g_main_context_unref (data->context);
327     }
328 #endif
329 }
330
331 /* ---------------------------------------------------------------------------------------------------- */
332
333 typedef enum {
334     PENDING_NONE = 0,
335     PENDING_WRITE,
336     PENDING_FLUSH,
337     PENDING_CLOSE
338 } OutputPending;
339
340 struct GDBusWorker
341 {
342   volatile gint                       ref_count;
343
344   SharedThreadData                   *shared_thread_data;
345
346   /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
347   volatile gint                       stopped;
348
349   /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
350    * only affects messages received from the other peer (since GDBusServer is the
351    * only user) - we might want it to affect messages sent to the other peer too?
352    */
353   gboolean                            frozen;
354   GDBusCapabilityFlags                capabilities;
355   GQueue                             *received_messages_while_frozen;
356
357   GIOStream                          *stream;
358   GCancellable                       *cancellable;
359   GDBusWorkerMessageReceivedCallback  message_received_callback;
360   GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
361   GDBusWorkerDisconnectedCallback     disconnected_callback;
362   gpointer                            user_data;
363
364   /* if not NULL, stream is GSocketConnection */
365   GSocket *socket;
366
367   /* used for reading */
368   GMutex                              read_lock;
369   gchar                              *read_buffer;
370   gsize                               read_buffer_allocated_size;
371   gsize                               read_buffer_cur_size;
372   gsize                               read_buffer_bytes_wanted;
373   GUnixFDList                        *read_fd_list;
374   GSocketControlMessage             **read_ancillary_messages;
375   gint                                read_num_ancillary_messages;
376
377   /* Whether an async write, flush or close, or none of those, is pending.
378    * Only the worker thread may change its value, and only with the write_lock.
379    * Other threads may read its value when holding the write_lock.
380    * The worker thread may read its value at any time.
381    */
382   OutputPending                       output_pending;
383   /* used for writing */
384   GMutex                              write_lock;
385   /* queue of MessageToWriteData, protected by write_lock */
386   GQueue                             *write_queue;
387   /* protected by write_lock */
388   guint64                             write_num_messages_written;
389   /* number of messages we'd written out last time we flushed;
390    * protected by write_lock
391    */
392   guint64                             write_num_messages_flushed;
393   /* list of FlushData, protected by write_lock */
394   GList                              *write_pending_flushes;
395   /* list of CloseData, protected by write_lock */
396   GList                              *pending_close_attempts;
397   /* no lock - only used from the worker thread */
398   gboolean                            close_expected;
399 };
400
401 static void _g_dbus_worker_unref (GDBusWorker *worker);
402
403 /* ---------------------------------------------------------------------------------------------------- */
404
405 typedef struct
406 {
407   GMutex  mutex;
408   GCond   cond;
409   guint64 number_to_wait_for;
410   GError *error;
411 } FlushData;
412
413 struct _MessageToWriteData ;
414 typedef struct _MessageToWriteData MessageToWriteData;
415
416 static void message_to_write_data_free (MessageToWriteData *data);
417
418 static void read_message_print_transport_debug (gssize bytes_read,
419                                                 GDBusWorker *worker);
420
421 static void write_message_print_transport_debug (gssize bytes_written,
422                                                  MessageToWriteData *data);
423
424 typedef struct {
425     GDBusWorker *worker;
426     GCancellable *cancellable;
427     GSimpleAsyncResult *result;
428 } CloseData;
429
430 static void close_data_free (CloseData *close_data)
431 {
432   if (close_data->cancellable != NULL)
433     g_object_unref (close_data->cancellable);
434
435   if (close_data->result != NULL)
436     g_object_unref (close_data->result);
437
438   _g_dbus_worker_unref (close_data->worker);
439   g_slice_free (CloseData, close_data);
440 }
441
442 /* ---------------------------------------------------------------------------------------------------- */
443
444 static GDBusWorker *
445 _g_dbus_worker_ref (GDBusWorker *worker)
446 {
447   g_atomic_int_inc (&worker->ref_count);
448   return worker;
449 }
450
451 static void
452 _g_dbus_worker_unref (GDBusWorker *worker)
453 {
454   if (g_atomic_int_dec_and_test (&worker->ref_count))
455     {
456       g_assert (worker->write_pending_flushes == NULL);
457
458       _g_dbus_shared_thread_unref (worker->shared_thread_data);
459
460       g_object_unref (worker->stream);
461
462       g_mutex_clear (&worker->read_lock);
463       g_object_unref (worker->cancellable);
464       if (worker->read_fd_list != NULL)
465         g_object_unref (worker->read_fd_list);
466
467       g_queue_free_full (worker->received_messages_while_frozen, (GDestroyNotify) g_object_unref);
468       g_mutex_clear (&worker->write_lock);
469       g_queue_free_full (worker->write_queue, (GDestroyNotify) message_to_write_data_free);
470       g_free (worker->read_buffer);
471
472       g_free (worker);
473     }
474 }
475
476 static void
477 _g_dbus_worker_emit_disconnected (GDBusWorker  *worker,
478                                   gboolean      remote_peer_vanished,
479                                   GError       *error)
480 {
481   if (!g_atomic_int_get (&worker->stopped))
482     worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
483 }
484
485 static void
486 _g_dbus_worker_emit_message_received (GDBusWorker  *worker,
487                                       GDBusMessage *message)
488 {
489   if (!g_atomic_int_get (&worker->stopped))
490     worker->message_received_callback (worker, message, worker->user_data);
491 }
492
493 static GDBusMessage *
494 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker  *worker,
495                                               GDBusMessage *message)
496 {
497   GDBusMessage *ret;
498   if (!g_atomic_int_get (&worker->stopped))
499     ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
500   else
501     ret = message;
502   return ret;
503 }
504
505 /* can only be called from private thread with read-lock held - takes ownership of @message */
506 static void
507 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker  *worker,
508                                                   GDBusMessage *message)
509 {
510   if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
511     {
512       /* queue up */
513       g_queue_push_tail (worker->received_messages_while_frozen, message);
514     }
515   else
516     {
517       /* not frozen, nor anything in queue */
518       _g_dbus_worker_emit_message_received (worker, message);
519       g_object_unref (message);
520     }
521 }
522
523 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
524 static gboolean
525 unfreeze_in_idle_cb (gpointer user_data)
526 {
527   GDBusWorker *worker = user_data;
528   GDBusMessage *message;
529
530   g_mutex_lock (&worker->read_lock);
531   if (worker->frozen)
532     {
533       while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
534         {
535           _g_dbus_worker_emit_message_received (worker, message);
536           g_object_unref (message);
537         }
538       worker->frozen = FALSE;
539     }
540   else
541     {
542       g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
543     }
544   g_mutex_unlock (&worker->read_lock);
545   return FALSE;
546 }
547
548 /* can be called from any thread */
549 void
550 _g_dbus_worker_unfreeze (GDBusWorker *worker)
551 {
552   GSource *idle_source;
553   idle_source = g_idle_source_new ();
554   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
555   g_source_set_callback (idle_source,
556                          unfreeze_in_idle_cb,
557                          _g_dbus_worker_ref (worker),
558                          (GDestroyNotify) _g_dbus_worker_unref);
559   g_source_attach (idle_source, worker->shared_thread_data->context);
560   g_source_unref (idle_source);
561 }
562
563 /* ---------------------------------------------------------------------------------------------------- */
564
565 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
566
567 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
568 static void
569 _g_dbus_worker_do_read_cb (GInputStream  *input_stream,
570                            GAsyncResult  *res,
571                            gpointer       user_data)
572 {
573   GDBusWorker *worker = user_data;
574   GError *error;
575   gssize bytes_read;
576
577   g_mutex_lock (&worker->read_lock);
578
579   /* If already stopped, don't even process the reply */
580   if (g_atomic_int_get (&worker->stopped))
581     goto out;
582
583   error = NULL;
584   if (worker->socket == NULL)
585     bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
586                                              res,
587                                              &error);
588   else
589     bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
590                                                               res,
591                                                               &error);
592   if (worker->read_num_ancillary_messages > 0)
593     {
594       gint n;
595       for (n = 0; n < worker->read_num_ancillary_messages; n++)
596         {
597           GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
598
599           if (FALSE)
600             {
601             }
602 #ifdef G_OS_UNIX
603           else if (G_IS_UNIX_FD_MESSAGE (control_message))
604             {
605               GUnixFDMessage *fd_message;
606               gint *fds;
607               gint num_fds;
608
609               fd_message = G_UNIX_FD_MESSAGE (control_message);
610               fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
611               if (worker->read_fd_list == NULL)
612                 {
613                   worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
614                 }
615               else
616                 {
617                   gint n;
618                   for (n = 0; n < num_fds; n++)
619                     {
620                       /* TODO: really want a append_steal() */
621                       g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
622                       (void) g_close (fds[n], NULL);
623                     }
624                 }
625               g_free (fds);
626             }
627           else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
628             {
629               /* do nothing */
630             }
631 #endif
632           else
633             {
634               if (error == NULL)
635                 {
636                   g_set_error (&error,
637                                G_IO_ERROR,
638                                G_IO_ERROR_FAILED,
639                                "Unexpected ancillary message of type %s received from peer",
640                                g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
641                   _g_dbus_worker_emit_disconnected (worker, TRUE, error);
642                   g_error_free (error);
643                   g_object_unref (control_message);
644                   n++;
645                   while (n < worker->read_num_ancillary_messages)
646                     g_object_unref (worker->read_ancillary_messages[n++]);
647                   g_free (worker->read_ancillary_messages);
648                   goto out;
649                 }
650             }
651           g_object_unref (control_message);
652         }
653       g_free (worker->read_ancillary_messages);
654     }
655
656   if (bytes_read == -1)
657     {
658       if (G_UNLIKELY (_g_dbus_debug_transport ()))
659         {
660           _g_dbus_debug_print_lock ();
661           g_print ("========================================================================\n"
662                    "GDBus-debug:Transport:\n"
663                    "  ---- READ ERROR on stream of type %s:\n"
664                    "  ---- %s %d: %s\n",
665                    g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))),
666                    g_quark_to_string (error->domain), error->code,
667                    error->message);
668           _g_dbus_debug_print_unlock ();
669         }
670
671       /* Every async read that uses this callback uses worker->cancellable
672        * as its GCancellable. worker->cancellable gets cancelled if and only
673        * if the GDBusConnection tells us to close (either via
674        * _g_dbus_worker_stop, which is called on last-unref, or directly),
675        * so a cancelled read must mean our connection was closed locally.
676        *
677        * If we're closing, other errors are possible - notably,
678        * G_IO_ERROR_CLOSED can be seen if we close the stream with an async
679        * read in-flight. It seems sensible to treat all read errors during
680        * closing as an expected thing that doesn't trip exit-on-close.
681        *
682        * Because close_expected can't be set until we get into the worker
683        * thread, but the cancellable is signalled sooner (from another
684        * thread), we do still need to check the error.
685        */
686       if (worker->close_expected ||
687           g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
688         _g_dbus_worker_emit_disconnected (worker, FALSE, NULL);
689       else
690         _g_dbus_worker_emit_disconnected (worker, TRUE, error);
691
692       g_error_free (error);
693       goto out;
694     }
695
696 #if 0
697   g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
698            (gint) bytes_read,
699            g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
700            g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
701            g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
702                                      G_IO_IN | G_IO_OUT | G_IO_HUP),
703            worker->stream,
704            worker);
705 #endif
706
707   /* TODO: hmm, hmm... */
708   if (bytes_read == 0)
709     {
710       g_set_error (&error,
711                    G_IO_ERROR,
712                    G_IO_ERROR_FAILED,
713                    "Underlying GIOStream returned 0 bytes on an async read");
714       _g_dbus_worker_emit_disconnected (worker, TRUE, error);
715       g_error_free (error);
716       goto out;
717     }
718
719   read_message_print_transport_debug (bytes_read, worker);
720
721   worker->read_buffer_cur_size += bytes_read;
722   if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
723     {
724       /* OK, got what we asked for! */
725       if (worker->read_buffer_bytes_wanted == 16)
726         {
727           gssize message_len;
728           /* OK, got the header - determine how many more bytes are needed */
729           error = NULL;
730           message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
731                                                      16,
732                                                      &error);
733           if (message_len == -1)
734             {
735               g_warning ("_g_dbus_worker_do_read_cb: error determining bytes needed: %s", error->message);
736               _g_dbus_worker_emit_disconnected (worker, FALSE, error);
737               g_error_free (error);
738               goto out;
739             }
740
741           worker->read_buffer_bytes_wanted = message_len;
742           _g_dbus_worker_do_read_unlocked (worker);
743         }
744       else
745         {
746           GDBusMessage *message;
747           error = NULL;
748
749           /* TODO: use connection->priv->auth to decode the message */
750
751           message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
752                                                   worker->read_buffer_cur_size,
753                                                   worker->capabilities,
754                                                   &error);
755           if (message == NULL)
756             {
757               gchar *s;
758               s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
759               g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
760                          "The error is: %s\n"
761                          "The payload is as follows:\n"
762                          "%s\n",
763                          worker->read_buffer_cur_size,
764                          error->message,
765                          s);
766               g_free (s);
767               _g_dbus_worker_emit_disconnected (worker, FALSE, error);
768               g_error_free (error);
769               goto out;
770             }
771
772 #ifdef G_OS_UNIX
773           if (worker->read_fd_list != NULL)
774             {
775               g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
776               g_object_unref (worker->read_fd_list);
777               worker->read_fd_list = NULL;
778             }
779 #endif
780
781           if (G_UNLIKELY (_g_dbus_debug_message ()))
782             {
783               gchar *s;
784               _g_dbus_debug_print_lock ();
785               g_print ("========================================================================\n"
786                        "GDBus-debug:Message:\n"
787                        "  <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
788                        worker->read_buffer_cur_size);
789               s = g_dbus_message_print (message, 2);
790               g_print ("%s", s);
791               g_free (s);
792               if (G_UNLIKELY (_g_dbus_debug_payload ()))
793                 {
794                   s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
795                   g_print ("%s\n", s);
796                   g_free (s);
797                 }
798               _g_dbus_debug_print_unlock ();
799             }
800
801           /* yay, got a message, go deliver it */
802           _g_dbus_worker_queue_or_deliver_received_message (worker, message);
803
804           /* start reading another message! */
805           worker->read_buffer_bytes_wanted = 0;
806           worker->read_buffer_cur_size = 0;
807           _g_dbus_worker_do_read_unlocked (worker);
808         }
809     }
810   else
811     {
812       /* didn't get all the bytes we requested - so repeat the request... */
813       _g_dbus_worker_do_read_unlocked (worker);
814     }
815
816  out:
817   g_mutex_unlock (&worker->read_lock);
818
819   /* gives up the reference acquired when calling g_input_stream_read_async() */
820   _g_dbus_worker_unref (worker);
821 }
822
823 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
824 static void
825 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
826 {
827   /* Note that we do need to keep trying to read even if close_expected is
828    * true, because only failing a read causes us to signal 'closed'.
829    */
830
831   /* if bytes_wanted is zero, it means start reading a message */
832   if (worker->read_buffer_bytes_wanted == 0)
833     {
834       worker->read_buffer_cur_size = 0;
835       worker->read_buffer_bytes_wanted = 16;
836     }
837
838   /* ensure we have a (big enough) buffer */
839   if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
840     {
841       /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
842       worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
843       worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
844     }
845
846   if (worker->socket == NULL)
847     g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
848                                worker->read_buffer + worker->read_buffer_cur_size,
849                                worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
850                                G_PRIORITY_DEFAULT,
851                                worker->cancellable,
852                                (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
853                                _g_dbus_worker_ref (worker));
854   else
855     {
856       worker->read_ancillary_messages = NULL;
857       worker->read_num_ancillary_messages = 0;
858       _g_socket_read_with_control_messages (worker->socket,
859                                             worker->read_buffer + worker->read_buffer_cur_size,
860                                             worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
861                                             &worker->read_ancillary_messages,
862                                             &worker->read_num_ancillary_messages,
863                                             G_PRIORITY_DEFAULT,
864                                             worker->cancellable,
865                                             (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
866                                             _g_dbus_worker_ref (worker));
867     }
868 }
869
870 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
871 static gboolean
872 _g_dbus_worker_do_initial_read (gpointer data)
873 {
874   GDBusWorker *worker = data;
875   g_mutex_lock (&worker->read_lock);
876   _g_dbus_worker_do_read_unlocked (worker);
877   g_mutex_unlock (&worker->read_lock);
878   return FALSE;
879 }
880
881 /* ---------------------------------------------------------------------------------------------------- */
882
883 struct _MessageToWriteData
884 {
885   GDBusWorker  *worker;
886   GDBusMessage *message;
887   gchar        *blob;
888   gsize         blob_size;
889
890   gsize               total_written;
891   GSimpleAsyncResult *simple;
892
893 };
894
895 static void
896 message_to_write_data_free (MessageToWriteData *data)
897 {
898   _g_dbus_worker_unref (data->worker);
899   if (data->message)
900     g_object_unref (data->message);
901   g_free (data->blob);
902   g_free (data);
903 }
904
905 /* ---------------------------------------------------------------------------------------------------- */
906
907 static void write_message_continue_writing (MessageToWriteData *data);
908
909 /* called in private thread shared by all GDBusConnection instances
910  *
911  * write-lock is not held on entry
912  * output_pending is PENDING_WRITE on entry
913  */
914 static void
915 write_message_async_cb (GObject      *source_object,
916                         GAsyncResult *res,
917                         gpointer      user_data)
918 {
919   MessageToWriteData *data = user_data;
920   GSimpleAsyncResult *simple;
921   gssize bytes_written;
922   GError *error;
923
924   /* Note: we can't access data->simple after calling g_async_result_complete () because the
925    * callback can free @data and we're not completing in idle. So use a copy of the pointer.
926    */
927   simple = data->simple;
928
929   error = NULL;
930   bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
931                                                 res,
932                                                 &error);
933   if (bytes_written == -1)
934     {
935       g_simple_async_result_take_error (simple, error);
936       g_simple_async_result_complete (simple);
937       g_object_unref (simple);
938       goto out;
939     }
940   g_assert (bytes_written > 0); /* zero is never returned */
941
942   write_message_print_transport_debug (bytes_written, data);
943
944   data->total_written += bytes_written;
945   g_assert (data->total_written <= data->blob_size);
946   if (data->total_written == data->blob_size)
947     {
948       g_simple_async_result_complete (simple);
949       g_object_unref (simple);
950       goto out;
951     }
952
953   write_message_continue_writing (data);
954
955  out:
956   ;
957 }
958
959 /* called in private thread shared by all GDBusConnection instances
960  *
961  * write-lock is not held on entry
962  * output_pending is PENDING_WRITE on entry
963  */
964 #ifdef G_OS_UNIX
965 static gboolean
966 on_socket_ready (GSocket      *socket,
967                  GIOCondition  condition,
968                  gpointer      user_data)
969 {
970   MessageToWriteData *data = user_data;
971   write_message_continue_writing (data);
972   return FALSE; /* remove source */
973 }
974 #endif
975
976 /* called in private thread shared by all GDBusConnection instances
977  *
978  * write-lock is not held on entry
979  * output_pending is PENDING_WRITE on entry
980  */
981 static void
982 write_message_continue_writing (MessageToWriteData *data)
983 {
984   GOutputStream *ostream;
985 #ifdef G_OS_UNIX
986   GSimpleAsyncResult *simple;
987   GUnixFDList *fd_list;
988 #endif
989
990 #ifdef G_OS_UNIX
991   /* Note: we can't access data->simple after calling g_async_result_complete () because the
992    * callback can free @data and we're not completing in idle. So use a copy of the pointer.
993    */
994   simple = data->simple;
995 #endif
996
997   ostream = g_io_stream_get_output_stream (data->worker->stream);
998 #ifdef G_OS_UNIX
999   fd_list = g_dbus_message_get_unix_fd_list (data->message);
1000 #endif
1001
1002   g_assert (!g_output_stream_has_pending (ostream));
1003   g_assert_cmpint (data->total_written, <, data->blob_size);
1004
1005   if (FALSE)
1006     {
1007     }
1008 #ifdef G_OS_UNIX
1009   else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
1010     {
1011       GOutputVector vector;
1012       GSocketControlMessage *control_message;
1013       gssize bytes_written;
1014       GError *error;
1015
1016       vector.buffer = data->blob;
1017       vector.size = data->blob_size;
1018
1019       control_message = NULL;
1020       if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
1021         {
1022           if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
1023             {
1024               g_simple_async_result_set_error (simple,
1025                                                G_IO_ERROR,
1026                                                G_IO_ERROR_FAILED,
1027                                                "Tried sending a file descriptor but remote peer does not support this capability");
1028               g_simple_async_result_complete (simple);
1029               g_object_unref (simple);
1030               goto out;
1031             }
1032           control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1033         }
1034
1035       error = NULL;
1036       bytes_written = g_socket_send_message (data->worker->socket,
1037                                              NULL, /* address */
1038                                              &vector,
1039                                              1,
1040                                              control_message != NULL ? &control_message : NULL,
1041                                              control_message != NULL ? 1 : 0,
1042                                              G_SOCKET_MSG_NONE,
1043                                              data->worker->cancellable,
1044                                              &error);
1045       if (control_message != NULL)
1046         g_object_unref (control_message);
1047
1048       if (bytes_written == -1)
1049         {
1050           /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1051           if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1052             {
1053               GSource *source;
1054               source = g_socket_create_source (data->worker->socket,
1055                                                G_IO_OUT | G_IO_HUP | G_IO_ERR,
1056                                                data->worker->cancellable);
1057               g_source_set_callback (source,
1058                                      (GSourceFunc) on_socket_ready,
1059                                      data,
1060                                      NULL); /* GDestroyNotify */
1061               g_source_attach (source, g_main_context_get_thread_default ());
1062               g_source_unref (source);
1063               g_error_free (error);
1064               goto out;
1065             }
1066           g_simple_async_result_take_error (simple, error);
1067           g_simple_async_result_complete (simple);
1068           g_object_unref (simple);
1069           goto out;
1070         }
1071       g_assert (bytes_written > 0); /* zero is never returned */
1072
1073       write_message_print_transport_debug (bytes_written, data);
1074
1075       data->total_written += bytes_written;
1076       g_assert (data->total_written <= data->blob_size);
1077       if (data->total_written == data->blob_size)
1078         {
1079           g_simple_async_result_complete (simple);
1080           g_object_unref (simple);
1081           goto out;
1082         }
1083
1084       write_message_continue_writing (data);
1085     }
1086 #endif
1087   else
1088     {
1089 #ifdef G_OS_UNIX
1090       if (fd_list != NULL)
1091         {
1092           g_simple_async_result_set_error (simple,
1093                                            G_IO_ERROR,
1094                                            G_IO_ERROR_FAILED,
1095                                            "Tried sending a file descriptor on unsupported stream of type %s",
1096                                            g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1097           g_simple_async_result_complete (simple);
1098           g_object_unref (simple);
1099           goto out;
1100         }
1101 #endif
1102
1103       g_output_stream_write_async (ostream,
1104                                    (const gchar *) data->blob + data->total_written,
1105                                    data->blob_size - data->total_written,
1106                                    G_PRIORITY_DEFAULT,
1107                                    data->worker->cancellable,
1108                                    write_message_async_cb,
1109                                    data);
1110     }
1111 #ifdef G_OS_UNIX
1112  out:
1113 #endif
1114   ;
1115 }
1116
1117 /* called in private thread shared by all GDBusConnection instances
1118  *
1119  * write-lock is not held on entry
1120  * output_pending is PENDING_WRITE on entry
1121  */
1122 static void
1123 write_message_async (GDBusWorker         *worker,
1124                      MessageToWriteData  *data,
1125                      GAsyncReadyCallback  callback,
1126                      gpointer             user_data)
1127 {
1128   data->simple = g_simple_async_result_new (NULL,
1129                                             callback,
1130                                             user_data,
1131                                             write_message_async);
1132   data->total_written = 0;
1133   write_message_continue_writing (data);
1134 }
1135
1136 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1137 static gboolean
1138 write_message_finish (GAsyncResult   *res,
1139                       GError        **error)
1140 {
1141   g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1142   if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1143     return FALSE;
1144   else
1145     return TRUE;
1146 }
1147 /* ---------------------------------------------------------------------------------------------------- */
1148
1149 static void continue_writing (GDBusWorker *worker);
1150
1151 typedef struct
1152 {
1153   GDBusWorker *worker;
1154   GList *flushers;
1155 } FlushAsyncData;
1156
1157 static void
1158 flush_data_list_complete (const GList  *flushers,
1159                           const GError *error)
1160 {
1161   const GList *l;
1162
1163   for (l = flushers; l != NULL; l = l->next)
1164     {
1165       FlushData *f = l->data;
1166
1167       f->error = error != NULL ? g_error_copy (error) : NULL;
1168
1169       g_mutex_lock (&f->mutex);
1170       g_cond_signal (&f->cond);
1171       g_mutex_unlock (&f->mutex);
1172     }
1173 }
1174
1175 /* called in private thread shared by all GDBusConnection instances
1176  *
1177  * write-lock is not held on entry
1178  * output_pending is PENDING_FLUSH on entry
1179  */
1180 static void
1181 ostream_flush_cb (GObject      *source_object,
1182                   GAsyncResult *res,
1183                   gpointer      user_data)
1184 {
1185   FlushAsyncData *data = user_data;
1186   GError *error;
1187
1188   error = NULL;
1189   g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1190                                 res,
1191                                 &error);
1192
1193   if (error == NULL)
1194     {
1195       if (G_UNLIKELY (_g_dbus_debug_transport ()))
1196         {
1197           _g_dbus_debug_print_lock ();
1198           g_print ("========================================================================\n"
1199                    "GDBus-debug:Transport:\n"
1200                    "  ---- FLUSHED stream of type %s\n",
1201                    g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1202           _g_dbus_debug_print_unlock ();
1203         }
1204     }
1205
1206   g_assert (data->flushers != NULL);
1207   flush_data_list_complete (data->flushers, error);
1208   g_list_free (data->flushers);
1209
1210   if (error != NULL)
1211     g_error_free (error);
1212
1213   /* Make sure we tell folks that we don't have additional
1214      flushes pending */
1215   g_mutex_lock (&data->worker->write_lock);
1216   data->worker->write_num_messages_flushed = data->worker->write_num_messages_written;
1217   g_assert (data->worker->output_pending == PENDING_FLUSH);
1218   data->worker->output_pending = PENDING_NONE;
1219   g_mutex_unlock (&data->worker->write_lock);
1220
1221   /* OK, cool, finally kick off the next write */
1222   continue_writing (data->worker);
1223
1224   _g_dbus_worker_unref (data->worker);
1225   g_free (data);
1226 }
1227
1228 /* called in private thread shared by all GDBusConnection instances
1229  *
1230  * write-lock is not held on entry
1231  * output_pending is PENDING_FLUSH on entry
1232  */
1233 static void
1234 start_flush (FlushAsyncData *data)
1235 {
1236   g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1237                                G_PRIORITY_DEFAULT,
1238                                data->worker->cancellable,
1239                                ostream_flush_cb,
1240                                data);
1241 }
1242
1243 /* called in private thread shared by all GDBusConnection instances
1244  *
1245  * write-lock is held on entry
1246  * output_pending is PENDING_NONE on entry
1247  */
1248 static void
1249 message_written_unlocked (GDBusWorker *worker,
1250                           MessageToWriteData *message_data)
1251 {
1252   if (G_UNLIKELY (_g_dbus_debug_message ()))
1253     {
1254       gchar *s;
1255       _g_dbus_debug_print_lock ();
1256       g_print ("========================================================================\n"
1257                "GDBus-debug:Message:\n"
1258                "  >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1259                message_data->blob_size);
1260       s = g_dbus_message_print (message_data->message, 2);
1261       g_print ("%s", s);
1262       g_free (s);
1263       if (G_UNLIKELY (_g_dbus_debug_payload ()))
1264         {
1265           s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1266           g_print ("%s\n", s);
1267           g_free (s);
1268         }
1269       _g_dbus_debug_print_unlock ();
1270     }
1271
1272   worker->write_num_messages_written += 1;
1273 }
1274
1275 /* called in private thread shared by all GDBusConnection instances
1276  *
1277  * write-lock is held on entry
1278  * output_pending is PENDING_NONE on entry
1279  *
1280  * Returns: non-%NULL, setting @output_pending, if we need to flush now
1281  */
1282 static FlushAsyncData *
1283 prepare_flush_unlocked (GDBusWorker *worker)
1284 {
1285   GList *l;
1286   GList *ll;
1287   GList *flushers;
1288
1289   flushers = NULL;
1290   for (l = worker->write_pending_flushes; l != NULL; l = ll)
1291     {
1292       FlushData *f = l->data;
1293       ll = l->next;
1294
1295       if (f->number_to_wait_for == worker->write_num_messages_written)
1296         {
1297           flushers = g_list_append (flushers, f);
1298           worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1299         }
1300     }
1301   if (flushers != NULL)
1302     {
1303       g_assert (worker->output_pending == PENDING_NONE);
1304       worker->output_pending = PENDING_FLUSH;
1305     }
1306
1307   if (flushers != NULL)
1308     {
1309       FlushAsyncData *data;
1310
1311       data = g_new0 (FlushAsyncData, 1);
1312       data->worker = _g_dbus_worker_ref (worker);
1313       data->flushers = flushers;
1314       return data;
1315     }
1316
1317   return NULL;
1318 }
1319
1320 /* called in private thread shared by all GDBusConnection instances
1321  *
1322  * write-lock is not held on entry
1323  * output_pending is PENDING_WRITE on entry
1324  */
1325 static void
1326 write_message_cb (GObject       *source_object,
1327                   GAsyncResult  *res,
1328                   gpointer       user_data)
1329 {
1330   MessageToWriteData *data = user_data;
1331   GError *error;
1332
1333   g_mutex_lock (&data->worker->write_lock);
1334   g_assert (data->worker->output_pending == PENDING_WRITE);
1335   data->worker->output_pending = PENDING_NONE;
1336
1337   error = NULL;
1338   if (!write_message_finish (res, &error))
1339     {
1340       g_mutex_unlock (&data->worker->write_lock);
1341
1342       /* TODO: handle */
1343       _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1344       g_error_free (error);
1345
1346       g_mutex_lock (&data->worker->write_lock);
1347     }
1348
1349   message_written_unlocked (data->worker, data);
1350
1351   g_mutex_unlock (&data->worker->write_lock);
1352
1353   continue_writing (data->worker);
1354
1355   message_to_write_data_free (data);
1356 }
1357
1358 /* called in private thread shared by all GDBusConnection instances
1359  *
1360  * write-lock is not held on entry
1361  * output_pending is PENDING_CLOSE on entry
1362  */
1363 static void
1364 iostream_close_cb (GObject      *source_object,
1365                    GAsyncResult *res,
1366                    gpointer      user_data)
1367 {
1368   GDBusWorker *worker = user_data;
1369   GError *error = NULL;
1370   GList *pending_close_attempts, *pending_flush_attempts;
1371   GQueue *send_queue;
1372
1373   g_io_stream_close_finish (worker->stream, res, &error);
1374
1375   g_mutex_lock (&worker->write_lock);
1376
1377   pending_close_attempts = worker->pending_close_attempts;
1378   worker->pending_close_attempts = NULL;
1379
1380   pending_flush_attempts = worker->write_pending_flushes;
1381   worker->write_pending_flushes = NULL;
1382
1383   send_queue = worker->write_queue;
1384   worker->write_queue = g_queue_new ();
1385
1386   g_assert (worker->output_pending == PENDING_CLOSE);
1387   worker->output_pending = PENDING_NONE;
1388
1389   g_mutex_unlock (&worker->write_lock);
1390
1391   while (pending_close_attempts != NULL)
1392     {
1393       CloseData *close_data = pending_close_attempts->data;
1394
1395       pending_close_attempts = g_list_delete_link (pending_close_attempts,
1396                                                    pending_close_attempts);
1397
1398       if (close_data->result != NULL)
1399         {
1400           if (error != NULL)
1401             g_simple_async_result_set_from_error (close_data->result, error);
1402
1403           /* this must be in an idle because the result is likely to be
1404            * intended for another thread
1405            */
1406           g_simple_async_result_complete_in_idle (close_data->result);
1407         }
1408
1409       close_data_free (close_data);
1410     }
1411
1412   g_clear_error (&error);
1413
1414   /* all messages queued for sending are discarded */
1415   g_queue_free_full (send_queue, (GDestroyNotify) message_to_write_data_free);
1416   /* all queued flushes fail */
1417   error = g_error_new (G_IO_ERROR, G_IO_ERROR_CANCELLED,
1418                        _("Operation was cancelled"));
1419   flush_data_list_complete (pending_flush_attempts, error);
1420   g_list_free (pending_flush_attempts);
1421   g_clear_error (&error);
1422
1423   _g_dbus_worker_unref (worker);
1424 }
1425
1426 /* called in private thread shared by all GDBusConnection instances
1427  *
1428  * write-lock is not held on entry
1429  * output_pending must be PENDING_NONE on entry
1430  */
1431 static void
1432 continue_writing (GDBusWorker *worker)
1433 {
1434   MessageToWriteData *data;
1435   FlushAsyncData *flush_async_data;
1436
1437  write_next:
1438   /* we mustn't try to write two things at once */
1439   g_assert (worker->output_pending == PENDING_NONE);
1440
1441   g_mutex_lock (&worker->write_lock);
1442
1443   data = NULL;
1444   flush_async_data = NULL;
1445
1446   /* if we want to close the connection, that takes precedence */
1447   if (worker->pending_close_attempts != NULL)
1448     {
1449       worker->close_expected = TRUE;
1450       worker->output_pending = PENDING_CLOSE;
1451
1452       g_io_stream_close_async (worker->stream, G_PRIORITY_DEFAULT,
1453                                NULL, iostream_close_cb,
1454                                _g_dbus_worker_ref (worker));
1455     }
1456   else
1457     {
1458       flush_async_data = prepare_flush_unlocked (worker);
1459
1460       if (flush_async_data == NULL)
1461         {
1462           data = g_queue_pop_head (worker->write_queue);
1463
1464           if (data != NULL)
1465             worker->output_pending = PENDING_WRITE;
1466         }
1467     }
1468
1469   g_mutex_unlock (&worker->write_lock);
1470
1471   /* Note that write_lock is only used for protecting the @write_queue
1472    * and @output_pending fields of the GDBusWorker struct ... which we
1473    * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1474    *
1475    * Therefore, it's fine to drop it here when calling back into user
1476    * code and then writing the message out onto the GIOStream since this
1477    * function only runs on the worker thread.
1478    */
1479
1480   if (flush_async_data != NULL)
1481     {
1482       start_flush (flush_async_data);
1483       g_assert (data == NULL);
1484     }
1485   else if (data != NULL)
1486     {
1487       GDBusMessage *old_message;
1488       guchar *new_blob;
1489       gsize new_blob_size;
1490       GError *error;
1491
1492       old_message = data->message;
1493       data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1494       if (data->message == old_message)
1495         {
1496           /* filters had no effect - do nothing */
1497         }
1498       else if (data->message == NULL)
1499         {
1500           /* filters dropped message */
1501           g_mutex_lock (&worker->write_lock);
1502           worker->output_pending = PENDING_NONE;
1503           g_mutex_unlock (&worker->write_lock);
1504           message_to_write_data_free (data);
1505           goto write_next;
1506         }
1507       else
1508         {
1509           /* filters altered the message -> reencode */
1510           error = NULL;
1511           new_blob = g_dbus_message_to_blob (data->message,
1512                                              &new_blob_size,
1513                                              worker->capabilities,
1514                                              &error);
1515           if (new_blob == NULL)
1516             {
1517               /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1518                * the old message instead
1519                */
1520               g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1521                          g_dbus_message_get_serial (data->message),
1522                          error->message);
1523               g_error_free (error);
1524             }
1525           else
1526             {
1527               g_free (data->blob);
1528               data->blob = (gchar *) new_blob;
1529               data->blob_size = new_blob_size;
1530             }
1531         }
1532
1533       write_message_async (worker,
1534                            data,
1535                            write_message_cb,
1536                            data);
1537     }
1538 }
1539
1540 /* called in private thread shared by all GDBusConnection instances
1541  *
1542  * write-lock is not held on entry
1543  * output_pending may be anything
1544  */
1545 static gboolean
1546 continue_writing_in_idle_cb (gpointer user_data)
1547 {
1548   GDBusWorker *worker = user_data;
1549
1550   /* Because this is the worker thread, we can read this struct member
1551    * without holding the lock: no other thread ever modifies it.
1552    */
1553   if (worker->output_pending == PENDING_NONE)
1554     continue_writing (worker);
1555
1556   return FALSE;
1557 }
1558
1559 /*
1560  * @write_data: (transfer full) (allow-none):
1561  * @flush_data: (transfer full) (allow-none):
1562  * @close_data: (transfer full) (allow-none):
1563  *
1564  * Can be called from any thread
1565  *
1566  * write_lock is held on entry
1567  * output_pending may be anything
1568  */
1569 static void
1570 schedule_writing_unlocked (GDBusWorker        *worker,
1571                            MessageToWriteData *write_data,
1572                            FlushData          *flush_data,
1573                            CloseData          *close_data)
1574 {
1575   if (write_data != NULL)
1576     g_queue_push_tail (worker->write_queue, write_data);
1577
1578   if (flush_data != NULL)
1579     worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, flush_data);
1580
1581   if (close_data != NULL)
1582     worker->pending_close_attempts = g_list_prepend (worker->pending_close_attempts,
1583                                                      close_data);
1584
1585   /* If we had output pending, the next bit of output will happen
1586    * automatically when it finishes, so we only need to do this
1587    * if nothing was pending.
1588    *
1589    * The idle callback will re-check that output_pending is still
1590    * PENDING_NONE, to guard against output starting before the idle.
1591    */
1592   if (worker->output_pending == PENDING_NONE)
1593     {
1594       GSource *idle_source;
1595       idle_source = g_idle_source_new ();
1596       g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1597       g_source_set_callback (idle_source,
1598                              continue_writing_in_idle_cb,
1599                              _g_dbus_worker_ref (worker),
1600                              (GDestroyNotify) _g_dbus_worker_unref);
1601       g_source_attach (idle_source, worker->shared_thread_data->context);
1602       g_source_unref (idle_source);
1603     }
1604 }
1605
1606 /* ---------------------------------------------------------------------------------------------------- */
1607
1608 /* can be called from any thread - steals blob
1609  *
1610  * write_lock is not held on entry
1611  * output_pending may be anything
1612  */
1613 void
1614 _g_dbus_worker_send_message (GDBusWorker    *worker,
1615                              GDBusMessage   *message,
1616                              gchar          *blob,
1617                              gsize           blob_len)
1618 {
1619   MessageToWriteData *data;
1620
1621   g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1622   g_return_if_fail (blob != NULL);
1623   g_return_if_fail (blob_len > 16);
1624
1625   data = g_new0 (MessageToWriteData, 1);
1626   data->worker = _g_dbus_worker_ref (worker);
1627   data->message = g_object_ref (message);
1628   data->blob = blob; /* steal! */
1629   data->blob_size = blob_len;
1630
1631   g_mutex_lock (&worker->write_lock);
1632   schedule_writing_unlocked (worker, data, NULL, NULL);
1633   g_mutex_unlock (&worker->write_lock);
1634 }
1635
1636 /* ---------------------------------------------------------------------------------------------------- */
1637
1638 GDBusWorker *
1639 _g_dbus_worker_new (GIOStream                              *stream,
1640                     GDBusCapabilityFlags                    capabilities,
1641                     gboolean                                initially_frozen,
1642                     GDBusWorkerMessageReceivedCallback      message_received_callback,
1643                     GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1644                     GDBusWorkerDisconnectedCallback         disconnected_callback,
1645                     gpointer                                user_data)
1646 {
1647   GDBusWorker *worker;
1648   GSource *idle_source;
1649
1650   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1651   g_return_val_if_fail (message_received_callback != NULL, NULL);
1652   g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1653   g_return_val_if_fail (disconnected_callback != NULL, NULL);
1654
1655   worker = g_new0 (GDBusWorker, 1);
1656   worker->ref_count = 1;
1657
1658   g_mutex_init (&worker->read_lock);
1659   worker->message_received_callback = message_received_callback;
1660   worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1661   worker->disconnected_callback = disconnected_callback;
1662   worker->user_data = user_data;
1663   worker->stream = g_object_ref (stream);
1664   worker->capabilities = capabilities;
1665   worker->cancellable = g_cancellable_new ();
1666   worker->output_pending = PENDING_NONE;
1667
1668   worker->frozen = initially_frozen;
1669   worker->received_messages_while_frozen = g_queue_new ();
1670
1671   g_mutex_init (&worker->write_lock);
1672   worker->write_queue = g_queue_new ();
1673
1674   if (G_IS_SOCKET_CONNECTION (worker->stream))
1675     worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1676
1677   worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1678
1679   /* begin reading */
1680   idle_source = g_idle_source_new ();
1681   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1682   g_source_set_callback (idle_source,
1683                          _g_dbus_worker_do_initial_read,
1684                          _g_dbus_worker_ref (worker),
1685                          (GDestroyNotify) _g_dbus_worker_unref);
1686   g_source_attach (idle_source, worker->shared_thread_data->context);
1687   g_source_unref (idle_source);
1688
1689   return worker;
1690 }
1691
1692 /* ---------------------------------------------------------------------------------------------------- */
1693
1694 /* can be called from any thread
1695  *
1696  * write_lock is not held on entry
1697  * output_pending may be anything
1698  */
1699 void
1700 _g_dbus_worker_close (GDBusWorker         *worker,
1701                       GCancellable        *cancellable,
1702                       GSimpleAsyncResult  *result)
1703 {
1704   CloseData *close_data;
1705
1706   close_data = g_slice_new0 (CloseData);
1707   close_data->worker = _g_dbus_worker_ref (worker);
1708   close_data->cancellable =
1709       (cancellable == NULL ? NULL : g_object_ref (cancellable));
1710   close_data->result = (result == NULL ? NULL : g_object_ref (result));
1711
1712   /* Don't set worker->close_expected here - we're in the wrong thread.
1713    * It'll be set before the actual close happens.
1714    */
1715   g_cancellable_cancel (worker->cancellable);
1716   g_mutex_lock (&worker->write_lock);
1717   schedule_writing_unlocked (worker, NULL, NULL, close_data);
1718   g_mutex_unlock (&worker->write_lock);
1719 }
1720
1721 /* This can be called from any thread - frees worker. Note that
1722  * callbacks might still happen if called from another thread than the
1723  * worker - use your own synchronization primitive in the callbacks.
1724  *
1725  * write_lock is not held on entry
1726  * output_pending may be anything
1727  */
1728 void
1729 _g_dbus_worker_stop (GDBusWorker *worker)
1730 {
1731   g_atomic_int_set (&worker->stopped, TRUE);
1732
1733   /* Cancel any pending operations and schedule a close of the underlying I/O
1734    * stream in the worker thread
1735    */
1736   _g_dbus_worker_close (worker, NULL, NULL);
1737
1738   /* _g_dbus_worker_close holds a ref until after an idle in the worker
1739    * thread has run, so we no longer need to unref in an idle like in
1740    * commit 322e25b535
1741    */
1742   _g_dbus_worker_unref (worker);
1743 }
1744
1745 /* ---------------------------------------------------------------------------------------------------- */
1746
1747 /* can be called from any thread (except the worker thread) - blocks
1748  * calling thread until all queued outgoing messages are written and
1749  * the transport has been flushed
1750  *
1751  * write_lock is not held on entry
1752  * output_pending may be anything
1753  */
1754 gboolean
1755 _g_dbus_worker_flush_sync (GDBusWorker    *worker,
1756                            GCancellable   *cancellable,
1757                            GError        **error)
1758 {
1759   gboolean ret;
1760   FlushData *data;
1761   guint64 pending_writes;
1762
1763   data = NULL;
1764   ret = TRUE;
1765
1766   g_mutex_lock (&worker->write_lock);
1767
1768   /* if the queue is empty, no write is in-flight and we haven't written
1769    * anything since the last flush, then there's nothing to wait for
1770    */
1771   pending_writes = g_queue_get_length (worker->write_queue);
1772
1773   /* if a write is in-flight, we shouldn't be satisfied until the first
1774    * flush operation that follows it
1775    */
1776   if (worker->output_pending == PENDING_WRITE)
1777     pending_writes += 1;
1778
1779   if (pending_writes > 0 ||
1780       worker->write_num_messages_written != worker->write_num_messages_flushed)
1781     {
1782       data = g_new0 (FlushData, 1);
1783       g_mutex_init (&data->mutex);
1784       g_cond_init (&data->cond);
1785       data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
1786       g_mutex_lock (&data->mutex);
1787
1788       schedule_writing_unlocked (worker, NULL, data, NULL);
1789     }
1790   g_mutex_unlock (&worker->write_lock);
1791
1792   if (data != NULL)
1793     {
1794       g_cond_wait (&data->cond, &data->mutex);
1795       g_mutex_unlock (&data->mutex);
1796
1797       /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1798       g_cond_clear (&data->cond);
1799       g_mutex_clear (&data->mutex);
1800       if (data->error != NULL)
1801         {
1802           ret = FALSE;
1803           g_propagate_error (error, data->error);
1804         }
1805       g_free (data);
1806     }
1807
1808   return ret;
1809 }
1810
1811 /* ---------------------------------------------------------------------------------------------------- */
1812
1813 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1814 #define G_DBUS_DEBUG_TRANSPORT      (1<<1)
1815 #define G_DBUS_DEBUG_MESSAGE        (1<<2)
1816 #define G_DBUS_DEBUG_PAYLOAD        (1<<3)
1817 #define G_DBUS_DEBUG_CALL           (1<<4)
1818 #define G_DBUS_DEBUG_SIGNAL         (1<<5)
1819 #define G_DBUS_DEBUG_INCOMING       (1<<6)
1820 #define G_DBUS_DEBUG_RETURN         (1<<7)
1821 #define G_DBUS_DEBUG_EMISSION       (1<<8)
1822 #define G_DBUS_DEBUG_ADDRESS        (1<<9)
1823
1824 static gint _gdbus_debug_flags = 0;
1825
1826 gboolean
1827 _g_dbus_debug_authentication (void)
1828 {
1829   _g_dbus_initialize ();
1830   return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1831 }
1832
1833 gboolean
1834 _g_dbus_debug_transport (void)
1835 {
1836   _g_dbus_initialize ();
1837   return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1838 }
1839
1840 gboolean
1841 _g_dbus_debug_message (void)
1842 {
1843   _g_dbus_initialize ();
1844   return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1845 }
1846
1847 gboolean
1848 _g_dbus_debug_payload (void)
1849 {
1850   _g_dbus_initialize ();
1851   return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1852 }
1853
1854 gboolean
1855 _g_dbus_debug_call (void)
1856 {
1857   _g_dbus_initialize ();
1858   return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1859 }
1860
1861 gboolean
1862 _g_dbus_debug_signal (void)
1863 {
1864   _g_dbus_initialize ();
1865   return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1866 }
1867
1868 gboolean
1869 _g_dbus_debug_incoming (void)
1870 {
1871   _g_dbus_initialize ();
1872   return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1873 }
1874
1875 gboolean
1876 _g_dbus_debug_return (void)
1877 {
1878   _g_dbus_initialize ();
1879   return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1880 }
1881
1882 gboolean
1883 _g_dbus_debug_emission (void)
1884 {
1885   _g_dbus_initialize ();
1886   return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1887 }
1888
1889 gboolean
1890 _g_dbus_debug_address (void)
1891 {
1892   _g_dbus_initialize ();
1893   return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1894 }
1895
1896 G_LOCK_DEFINE_STATIC (print_lock);
1897
1898 void
1899 _g_dbus_debug_print_lock (void)
1900 {
1901   G_LOCK (print_lock);
1902 }
1903
1904 void
1905 _g_dbus_debug_print_unlock (void)
1906 {
1907   G_UNLOCK (print_lock);
1908 }
1909
1910 /*
1911  * _g_dbus_initialize:
1912  *
1913  * Does various one-time init things such as
1914  *
1915  *  - registering the G_DBUS_ERROR error domain
1916  *  - parses the G_DBUS_DEBUG environment variable
1917  */
1918 void
1919 _g_dbus_initialize (void)
1920 {
1921   static volatile gsize initialized = 0;
1922
1923   if (g_once_init_enter (&initialized))
1924     {
1925       volatile GQuark g_dbus_error_domain;
1926       const gchar *debug;
1927
1928       g_dbus_error_domain = G_DBUS_ERROR;
1929       (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1930
1931       debug = g_getenv ("G_DBUS_DEBUG");
1932       if (debug != NULL)
1933         {
1934           const GDebugKey keys[] = {
1935             { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1936             { "transport",      G_DBUS_DEBUG_TRANSPORT      },
1937             { "message",        G_DBUS_DEBUG_MESSAGE        },
1938             { "payload",        G_DBUS_DEBUG_PAYLOAD        },
1939             { "call",           G_DBUS_DEBUG_CALL           },
1940             { "signal",         G_DBUS_DEBUG_SIGNAL         },
1941             { "incoming",       G_DBUS_DEBUG_INCOMING       },
1942             { "return",         G_DBUS_DEBUG_RETURN         },
1943             { "emission",       G_DBUS_DEBUG_EMISSION       },
1944             { "address",        G_DBUS_DEBUG_ADDRESS        }
1945           };
1946
1947           _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1948           if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1949             _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1950         }
1951
1952       g_once_init_leave (&initialized, 1);
1953     }
1954 }
1955
1956 /* ---------------------------------------------------------------------------------------------------- */
1957
1958 GVariantType *
1959 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1960 {
1961   const GVariantType *arg_types[256];
1962   guint n;
1963
1964   if (args)
1965     for (n = 0; args[n] != NULL; n++)
1966       {
1967         /* DBus places a hard limit of 255 on signature length.
1968          * therefore number of args must be less than 256.
1969          */
1970         g_assert (n < 256);
1971
1972         arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1973
1974         if G_UNLIKELY (arg_types[n] == NULL)
1975           return NULL;
1976       }
1977   else
1978     n = 0;
1979
1980   return g_variant_type_new_tuple (arg_types, n);
1981 }
1982
1983 /* ---------------------------------------------------------------------------------------------------- */
1984
1985 #ifdef G_OS_WIN32
1986
1987 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1988
1989 gchar *
1990 _g_dbus_win32_get_user_sid (void)
1991 {
1992   HANDLE h;
1993   TOKEN_USER *user;
1994   DWORD token_information_len;
1995   PSID psid;
1996   gchar *sid;
1997   gchar *ret;
1998
1999   ret = NULL;
2000   user = NULL;
2001   h = INVALID_HANDLE_VALUE;
2002
2003   if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
2004     {
2005       g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
2006       goto out;
2007     }
2008
2009   /* Get length of buffer */
2010   token_information_len = 0;
2011   if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
2012     {
2013       if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
2014         {
2015           g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2016           goto out;
2017         }
2018     }
2019   user = g_malloc (token_information_len);
2020   if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
2021     {
2022       g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2023       goto out;
2024     }
2025
2026   psid = user->User.Sid;
2027   if (!IsValidSid (psid))
2028     {
2029       g_warning ("Invalid SID");
2030       goto out;
2031     }
2032
2033   if (!ConvertSidToStringSidA (psid, &sid))
2034     {
2035       g_warning ("Invalid SID");
2036       goto out;
2037     }
2038
2039   ret = g_strdup (sid);
2040   LocalFree (sid);
2041
2042 out:
2043   g_free (user);
2044   if (h != INVALID_HANDLE_VALUE)
2045     CloseHandle (h);
2046   return ret;
2047 }
2048 #endif
2049
2050 /* ---------------------------------------------------------------------------------------------------- */
2051
2052 gchar *
2053 _g_dbus_get_machine_id (GError **error)
2054 {
2055 #ifdef G_OS_WIN32
2056   HW_PROFILE_INFOA info;
2057   char *src, *dest, *res;
2058   int i;
2059
2060   if (!GetCurrentHwProfileA (&info))
2061     {
2062       char *message = g_win32_error_message (GetLastError ());
2063       g_set_error (error,
2064                    G_IO_ERROR,
2065                    G_IO_ERROR_FAILED,
2066                    _("Unable to get Hardware profile: %s"), message);
2067       g_free (message);
2068       return NULL;
2069     }
2070
2071   /* Form: {12340001-4980-1920-6788-123456789012} */
2072   src = &info.szHwProfileGuid[0];
2073
2074   res = g_malloc (32+1);
2075   dest = res;
2076
2077   src++; /* Skip { */
2078   for (i = 0; i < 8; i++)
2079     *dest++ = *src++;
2080   src++; /* Skip - */
2081   for (i = 0; i < 4; i++)
2082     *dest++ = *src++;
2083   src++; /* Skip - */
2084   for (i = 0; i < 4; i++)
2085     *dest++ = *src++;
2086   src++; /* Skip - */
2087   for (i = 0; i < 4; i++)
2088     *dest++ = *src++;
2089   src++; /* Skip - */
2090   for (i = 0; i < 12; i++)
2091     *dest++ = *src++;
2092   *dest = 0;
2093
2094   return res;
2095 #else
2096   gchar *ret;
2097   GError *first_error;
2098   /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2099   ret = NULL;
2100   first_error = NULL;
2101   if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2102                             &ret,
2103                             NULL,
2104                             &first_error) &&
2105       !g_file_get_contents ("/etc/machine-id",
2106                             &ret,
2107                             NULL,
2108                             NULL))
2109     {
2110       g_propagate_prefixed_error (error, first_error,
2111                                   _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2112     }
2113   else
2114     {
2115       /* ignore the error from the first try, if any */
2116       g_clear_error (&first_error);
2117       /* TODO: validate value */
2118       g_strstrip (ret);
2119     }
2120   return ret;
2121 #endif
2122 }
2123
2124 /* ---------------------------------------------------------------------------------------------------- */
2125
2126 gchar *
2127 _g_dbus_enum_to_string (GType enum_type, gint value)
2128 {
2129   gchar *ret;
2130   GEnumClass *klass;
2131   GEnumValue *enum_value;
2132
2133   klass = g_type_class_ref (enum_type);
2134   enum_value = g_enum_get_value (klass, value);
2135   if (enum_value != NULL)
2136     ret = g_strdup (enum_value->value_nick);
2137   else
2138     ret = g_strdup_printf ("unknown (value %d)", value);
2139   g_type_class_unref (klass);
2140   return ret;
2141 }
2142
2143 /* ---------------------------------------------------------------------------------------------------- */
2144
2145 static void
2146 write_message_print_transport_debug (gssize bytes_written,
2147                                      MessageToWriteData *data)
2148 {
2149   if (G_LIKELY (!_g_dbus_debug_transport ()))
2150     goto out;
2151
2152   _g_dbus_debug_print_lock ();
2153   g_print ("========================================================================\n"
2154            "GDBus-debug:Transport:\n"
2155            "  >>>> WROTE %" G_GSSIZE_FORMAT " bytes of message with serial %d and\n"
2156            "       size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
2157            bytes_written,
2158            g_dbus_message_get_serial (data->message),
2159            data->blob_size,
2160            data->total_written,
2161            g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
2162   _g_dbus_debug_print_unlock ();
2163  out:
2164   ;
2165 }
2166
2167 /* ---------------------------------------------------------------------------------------------------- */
2168
2169 static void
2170 read_message_print_transport_debug (gssize bytes_read,
2171                                     GDBusWorker *worker)
2172 {
2173   gsize size;
2174   gint32 serial;
2175   gint32 message_length;
2176
2177   if (G_LIKELY (!_g_dbus_debug_transport ()))
2178     goto out;
2179
2180   size = bytes_read + worker->read_buffer_cur_size;
2181   serial = 0;
2182   message_length = 0;
2183   if (size >= 16)
2184     message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2185   if (size >= 1)
2186     {
2187       switch (worker->read_buffer[0])
2188         {
2189         case 'l':
2190           if (size >= 12)
2191             serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2192           break;
2193         case 'B':
2194           if (size >= 12)
2195             serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2196           break;
2197         default:
2198           /* an error will be set elsewhere if this happens */
2199           goto out;
2200         }
2201     }
2202
2203     _g_dbus_debug_print_lock ();
2204   g_print ("========================================================================\n"
2205            "GDBus-debug:Transport:\n"
2206            "  <<<< READ %" G_GSSIZE_FORMAT " bytes of message with serial %d and\n"
2207            "       size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
2208            bytes_read,
2209            serial,
2210            message_length,
2211            worker->read_buffer_cur_size,
2212            g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
2213   _g_dbus_debug_print_unlock ();
2214  out:
2215   ;
2216 }
2217
2218 /* ---------------------------------------------------------------------------------------------------- */
2219
2220 gboolean
2221 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2222                                      GValue                *return_accu,
2223                                      const GValue          *handler_return,
2224                                      gpointer               dummy)
2225 {
2226   gboolean continue_emission;
2227   gboolean signal_return;
2228
2229   signal_return = g_value_get_boolean (handler_return);
2230   g_value_set_boolean (return_accu, signal_return);
2231   continue_emission = signal_return;
2232
2233   return continue_emission;
2234 }