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