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