[Sending] sender in outgoing message set.
[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 "glib/gstdio.h"
43 #include "gsocketcontrolmessage.h"
44 #include "gsocketconnection.h"
45 #include "gkdbusconnection.h"
46 #include "gsocketoutputstream.h"
47
48 #ifdef G_OS_UNIX
49 #include "gunixfdmessage.h"
50 #include "gunixconnection.h"
51 #include "gunixcredentialsmessage.h"
52 #endif
53
54 #ifdef G_OS_WIN32
55 #include <windows.h>
56 #endif
57
58 #include "glibintl.h"
59
60 static gboolean _g_dbus_worker_do_initial_read (gpointer data);
61
62 /* ---------------------------------------------------------------------------------------------------- */
63
64 gchar *
65 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
66 {
67  guint n, m;
68  GString *ret;
69
70  ret = g_string_new (NULL);
71
72  for (n = 0; n < len; n += 16)
73    {
74      g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
75
76      for (m = n; m < n + 16; m++)
77        {
78          if (m > n && (m%4) == 0)
79            g_string_append_c (ret, ' ');
80          if (m < len)
81            g_string_append_printf (ret, "%02x ", (guchar) data[m]);
82          else
83            g_string_append (ret, "   ");
84        }
85
86      g_string_append (ret, "   ");
87
88      for (m = n; m < len && m < n + 16; m++)
89        g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
90
91      g_string_append_c (ret, '\n');
92    }
93
94  return g_string_free (ret, FALSE);
95 }
96
97 /* ---------------------------------------------------------------------------------------------------- */
98
99 /* Unfortunately ancillary messages are discarded when reading from a
100  * socket using the GSocketInputStream abstraction. So we provide a
101  * very GInputStream-ish API that uses GSocket in this case (very
102  * similar to GSocketInputStream).
103  */
104
105 typedef struct
106 {
107   GSocket *socket;
108   GCancellable *cancellable;
109
110   void *buffer;
111   gsize count;
112
113   GSocketControlMessage ***messages;
114   gint *num_messages;
115
116   GSimpleAsyncResult *simple;
117
118   gboolean from_mainloop;
119 } ReadWithControlData;
120
121 static void
122 read_with_control_data_free (ReadWithControlData *data)
123 {
124   g_object_unref (data->socket);
125   if (data->cancellable != NULL)
126     g_object_unref (data->cancellable);
127   g_object_unref (data->simple);
128   g_free (data);
129 }
130
131 static gboolean
132 _g_socket_read_with_control_messages_ready (GSocket      *socket,
133                                             GIOCondition  condition,
134                                             gpointer      user_data)
135 {
136   ReadWithControlData *data = user_data;
137   GError *error;
138   gssize result;
139   GInputVector vector;
140
141   error = NULL;
142   vector.buffer = data->buffer;
143   vector.size = data->count;
144   result = g_socket_receive_message (data->socket,
145                                      NULL, /* address */
146                                      &vector,
147                                      1,
148                                      data->messages,
149                                      data->num_messages,
150                                      NULL,
151                                      data->cancellable,
152                                      &error);
153   if (result >= 0)
154     {
155       g_simple_async_result_set_op_res_gssize (data->simple, result);
156     }
157   else
158     {
159       g_assert (error != NULL);
160       g_simple_async_result_take_error (data->simple, error);
161     }
162
163   if (data->from_mainloop)
164     g_simple_async_result_complete (data->simple);
165   else
166     g_simple_async_result_complete_in_idle (data->simple);
167
168   return FALSE;
169 }
170
171 static void
172 _g_socket_read_with_control_messages (GSocket                 *socket,
173                                       void                    *buffer,
174                                       gsize                    count,
175                                       GSocketControlMessage ***messages,
176                                       gint                    *num_messages,
177                                       gint                     io_priority,
178                                       GCancellable            *cancellable,
179                                       GAsyncReadyCallback      callback,
180                                       gpointer                 user_data)
181 {
182   ReadWithControlData *data;
183
184   data = g_new0 (ReadWithControlData, 1);
185   data->socket = g_object_ref (socket);
186   data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
187   data->buffer = buffer;
188   data->count = count;
189   data->messages = messages;
190   data->num_messages = num_messages;
191
192   data->simple = g_simple_async_result_new (G_OBJECT (socket),
193                                             callback,
194                                             user_data,
195                                             _g_socket_read_with_control_messages);
196   g_simple_async_result_set_check_cancellable (data->simple, cancellable);
197
198   if (!g_socket_condition_check (socket, G_IO_IN))
199     {
200       GSource *source;
201       data->from_mainloop = TRUE;
202       source = g_socket_create_source (data->socket,
203                                        G_IO_IN | G_IO_HUP | G_IO_ERR,
204                                        cancellable);
205       g_source_set_callback (source,
206                              (GSourceFunc) _g_socket_read_with_control_messages_ready,
207                              data,
208                              (GDestroyNotify) read_with_control_data_free);
209       g_source_attach (source, g_main_context_get_thread_default ());
210       g_source_unref (source);
211     }
212   else
213     {
214       _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
215       read_with_control_data_free (data);
216     }
217 }
218
219 static gssize
220 _g_socket_read_with_control_messages_finish (GSocket       *socket,
221                                              GAsyncResult  *result,
222                                              GError       **error)
223 {
224   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
225
226   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
227   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
228
229   if (g_simple_async_result_propagate_error (simple, error))
230       return -1;
231   else
232     return g_simple_async_result_get_op_res_gssize (simple);
233 }
234
235 /* ---------------------------------------------------------------------------------------------------- */
236
237 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
238
239 static GPtrArray *ensured_classes = NULL;
240
241 static void
242 ensure_type (GType gtype)
243 {
244   g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
245 }
246
247 static void
248 release_required_types (void)
249 {
250   g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
251   g_ptr_array_unref (ensured_classes);
252   ensured_classes = NULL;
253 }
254
255 static void
256 ensure_required_types (void)
257 {
258   g_assert (ensured_classes == NULL);
259   ensured_classes = g_ptr_array_new ();
260   ensure_type (G_TYPE_SIMPLE_ASYNC_RESULT);
261   ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
262 }
263 /* ---------------------------------------------------------------------------------------------------- */
264
265 typedef struct
266 {
267   volatile gint refcount;
268   GThread *thread;
269   GMainContext *context;
270   GMainLoop *loop;
271 } SharedThreadData;
272
273 static gpointer
274 gdbus_shared_thread_func (gpointer user_data)
275 {
276   SharedThreadData *data = user_data;
277
278   g_main_context_push_thread_default (data->context);
279   g_main_loop_run (data->loop);
280   g_main_context_pop_thread_default (data->context);
281
282   release_required_types ();
283
284   return NULL;
285 }
286
287 /* ---------------------------------------------------------------------------------------------------- */
288
289 static SharedThreadData *
290 _g_dbus_shared_thread_ref (void)
291 {
292   static gsize shared_thread_data = 0;
293   SharedThreadData *ret;
294
295   if (g_once_init_enter (&shared_thread_data))
296     {
297       SharedThreadData *data;
298
299       /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
300       ensure_required_types ();
301
302       data = g_new0 (SharedThreadData, 1);
303       data->refcount = 0;
304       
305       data->context = g_main_context_new ();
306       data->loop = g_main_loop_new (data->context, FALSE);
307       data->thread = g_thread_new ("gdbus",
308                                    gdbus_shared_thread_func,
309                                    data);
310       /* We can cast between gsize and gpointer safely */
311       g_once_init_leave (&shared_thread_data, (gsize) data);
312     }
313
314   ret = (SharedThreadData*) shared_thread_data;
315   g_atomic_int_inc (&ret->refcount);
316   return ret;
317 }
318
319 static void
320 _g_dbus_shared_thread_unref (SharedThreadData *data)
321 {
322   /* TODO: actually destroy the shared thread here */
323 #if 0
324   g_assert (data != NULL);
325   if (g_atomic_int_dec_and_test (&data->refcount))
326     {
327       g_main_loop_quit (data->loop);
328       //g_thread_join (data->thread);
329       g_main_loop_unref (data->loop);
330       g_main_context_unref (data->context);
331     }
332 #endif
333 }
334
335 /* ---------------------------------------------------------------------------------------------------- */
336
337 typedef enum {
338     PENDING_NONE = 0,
339     PENDING_WRITE,
340     PENDING_FLUSH,
341     PENDING_CLOSE
342 } OutputPending;
343
344 struct GDBusWorker
345 {
346   volatile gint                       ref_count;
347
348   SharedThreadData                   *shared_thread_data;
349
350   /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
351   volatile gint                       stopped;
352
353   /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
354    * only affects messages received from the other peer (since GDBusServer is the
355    * only user) - we might want it to affect messages sent to the other peer too?
356    */
357   gboolean                            frozen;
358   GDBusCapabilityFlags                capabilities;
359   GQueue                             *received_messages_while_frozen;
360
361   GIOStream                          *stream;
362   GCancellable                       *cancellable;
363   GDBusWorkerMessageReceivedCallback  message_received_callback;
364   GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
365   GDBusWorkerDisconnectedCallback     disconnected_callback;
366   gpointer                            user_data;
367
368   /* if GSocket and GKdbus are NULL, stream is GSocketConnection */
369   GSocket *socket;
370   GKdbus  *kdbus;
371
372   /* used for reading */
373   GMutex                              read_lock;
374   gchar                              *read_buffer;
375   gsize                               read_buffer_allocated_size;
376   gsize                               read_buffer_cur_size;
377   gsize                               read_buffer_bytes_wanted;
378   GUnixFDList                        *read_fd_list;
379   GSocketControlMessage             **read_ancillary_messages;
380   gint                                read_num_ancillary_messages;
381
382   /* Whether an async write, flush or close, or none of those, is pending.
383    * Only the worker thread may change its value, and only with the write_lock.
384    * Other threads may read its value when holding the write_lock.
385    * The worker thread may read its value at any time.
386    */
387   OutputPending                       output_pending;
388   /* used for writing */
389   GMutex                              write_lock;
390   /* queue of MessageToWriteData, protected by write_lock */
391   GQueue                             *write_queue;
392   /* protected by write_lock */
393   guint64                             write_num_messages_written;
394   /* number of messages we'd written out last time we flushed;
395    * protected by write_lock
396    */
397   guint64                             write_num_messages_flushed;
398   /* list of FlushData, protected by write_lock */
399   GList                              *write_pending_flushes;
400   /* list of CloseData, protected by write_lock */
401   GList                              *pending_close_attempts;
402   /* no lock - only used from the worker thread */
403   gboolean                            close_expected;
404 };
405
406 static void _g_dbus_worker_unref (GDBusWorker *worker);
407
408 /* ---------------------------------------------------------------------------------------------------- */
409
410 typedef struct
411 {
412   GMutex  mutex;
413   GCond   cond;
414   guint64 number_to_wait_for;
415   GError *error;
416 } FlushData;
417
418 struct _MessageToWriteData ;
419 typedef struct _MessageToWriteData MessageToWriteData;
420
421 static void message_to_write_data_free (MessageToWriteData *data);
422
423 static void read_message_print_transport_debug (gssize bytes_read,
424                                                 GDBusWorker *worker);
425
426 static void write_message_print_transport_debug (gssize bytes_written,
427                                                  MessageToWriteData *data);
428
429 typedef struct {
430     GDBusWorker *worker;
431     GCancellable *cancellable;
432     GSimpleAsyncResult *result;
433 } CloseData;
434
435 static void close_data_free (CloseData *close_data)
436 {
437   if (close_data->cancellable != NULL)
438     g_object_unref (close_data->cancellable);
439
440   if (close_data->result != NULL)
441     g_object_unref (close_data->result);
442
443   _g_dbus_worker_unref (close_data->worker);
444   g_slice_free (CloseData, close_data);
445 }
446
447 /* ---------------------------------------------------------------------------------------------------- */
448
449 static GDBusWorker *
450 _g_dbus_worker_ref (GDBusWorker *worker)
451 {
452   g_atomic_int_inc (&worker->ref_count);
453   return worker;
454 }
455
456 static void
457 _g_dbus_worker_unref (GDBusWorker *worker)
458 {
459   if (g_atomic_int_dec_and_test (&worker->ref_count))
460     {
461       g_assert (worker->write_pending_flushes == NULL);
462
463       _g_dbus_shared_thread_unref (worker->shared_thread_data);
464
465       g_object_unref (worker->stream);
466
467       g_mutex_clear (&worker->read_lock);
468       g_object_unref (worker->cancellable);
469       if (worker->read_fd_list != NULL)
470         g_object_unref (worker->read_fd_list);
471
472       g_queue_free_full (worker->received_messages_while_frozen, (GDestroyNotify) g_object_unref);
473       g_mutex_clear (&worker->write_lock);
474       g_queue_free_full (worker->write_queue, (GDestroyNotify) message_to_write_data_free);
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 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                       (void) g_close (fds[n], NULL);
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 determining 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 #ifdef G_OS_UNIX
970 static gboolean
971 on_socket_ready (GSocket      *socket,
972                  GIOCondition  condition,
973                  gpointer      user_data)
974 {
975   MessageToWriteData *data = user_data;
976   write_message_continue_writing (data);
977   return FALSE; /* remove source */
978 }
979 #endif
980
981 /* called in private thread shared by all GDBusConnection instances
982  *
983  * write-lock is not held on entry
984  * output_pending is PENDING_WRITE on entry
985  */
986 static void
987 write_message_continue_writing (MessageToWriteData *data)
988 {
989 #ifdef G_OS_UNIX
990   GSimpleAsyncResult *simple;
991   simple = data->simple;
992 #endif
993
994   if (G_IS_KDBUS_CONNECTION (data->worker->stream))
995     {
996       GError *error;
997       error = NULL;
998       data->total_written = g_kdbus_send_message(data->worker, data->worker->kdbus, data->message, data->blob, data->blob_size, &error);
999       
1000       if (data->total_written == data->blob_size)
1001         {
1002           g_simple_async_result_complete (simple);
1003           g_object_unref (simple);
1004           goto out;
1005         }
1006     }
1007   else
1008     {
1009       GOutputStream *ostream;
1010 #ifdef G_OS_UNIX
1011       GUnixFDList *fd_list;
1012 #endif
1013
1014       ostream = g_io_stream_get_output_stream (data->worker->stream);
1015 #ifdef G_OS_UNIX
1016       fd_list = g_dbus_message_get_unix_fd_list (data->message);
1017 #endif
1018
1019       g_assert (!g_output_stream_has_pending (ostream));
1020       g_assert_cmpint (data->total_written, <, data->blob_size);
1021
1022       if (FALSE)
1023         {
1024         }
1025 #ifdef G_OS_UNIX
1026       else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
1027         {
1028            GOutputVector vector;
1029            GSocketControlMessage *control_message;
1030            gssize bytes_written;
1031            GError *error;
1032
1033            vector.buffer = data->blob;
1034            vector.size = data->blob_size;
1035
1036            control_message = NULL;
1037            if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
1038              {
1039                if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
1040                  {
1041                    g_simple_async_result_set_error (simple,
1042                                                     G_IO_ERROR,
1043                                                     G_IO_ERROR_FAILED,
1044                                                     "Tried sending a file descriptor but remote peer does not support this capability");
1045                    g_simple_async_result_complete (simple);
1046                    g_object_unref (simple);
1047                    goto out;
1048                  }
1049                 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1050               }
1051
1052             error = NULL;
1053             bytes_written = g_socket_send_message (data->worker->socket,
1054                                                   NULL, /* address */
1055                                                   &vector,
1056                                                   1,
1057                                                   control_message != NULL ? &control_message : NULL,
1058                                                   control_message != NULL ? 1 : 0,
1059                                                   G_SOCKET_MSG_NONE,
1060                                                   data->worker->cancellable,
1061                                                   &error);
1062            if (control_message != NULL)
1063              g_object_unref (control_message);
1064
1065            if (bytes_written == -1)
1066              {
1067                /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1068                if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1069                  {
1070                    GSource *source;
1071                    source = g_socket_create_source (data->worker->socket,
1072                                                     G_IO_OUT | G_IO_HUP | G_IO_ERR,
1073                                                     data->worker->cancellable);
1074                    g_source_set_callback (source,
1075                                           (GSourceFunc) on_socket_ready,
1076                                           data,
1077                                           NULL); /* GDestroyNotify */
1078                    g_source_attach (source, g_main_context_get_thread_default ());
1079                    g_source_unref (source);
1080                    g_error_free (error);
1081                    goto out;
1082                  }
1083                g_simple_async_result_take_error (simple, error);
1084                g_simple_async_result_complete (simple);
1085                g_object_unref (simple);
1086                goto out;
1087              }
1088            g_assert (bytes_written > 0); /* zero is never returned */
1089
1090            write_message_print_transport_debug (bytes_written, data);
1091
1092            data->total_written += bytes_written;
1093            g_assert (data->total_written <= data->blob_size);
1094            if (data->total_written == data->blob_size)
1095              {
1096                g_simple_async_result_complete (simple);
1097                g_object_unref (simple);
1098                goto out;
1099              }
1100
1101            write_message_continue_writing (data);
1102          }
1103 #endif
1104        else
1105          {
1106 #ifdef G_OS_UNIX
1107            if (fd_list != NULL)
1108              {
1109                g_simple_async_result_set_error (simple,
1110                                                 G_IO_ERROR,
1111                                                 G_IO_ERROR_FAILED,
1112                                                 "Tried sending a file descriptor on unsupported stream of type %s",
1113                                                 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1114                g_simple_async_result_complete (simple);
1115                g_object_unref (simple);
1116                goto out;
1117              }
1118 #endif
1119
1120             g_output_stream_write_async (ostream,
1121                                         (const gchar *) data->blob + data->total_written,
1122                                         data->blob_size - data->total_written,
1123                                         G_PRIORITY_DEFAULT,
1124                                         data->worker->cancellable,
1125                                         write_message_async_cb,
1126                                         data);
1127          }
1128     }
1129 #ifdef G_OS_UNIX
1130  out:
1131 #endif
1132   ;
1133 }
1134
1135 /* called in private thread shared by all GDBusConnection instances
1136  *
1137  * write-lock is not held on entry
1138  * output_pending is PENDING_WRITE on entry
1139  */
1140 static void
1141 write_message_async (GDBusWorker         *worker,
1142                      MessageToWriteData  *data,
1143                      GAsyncReadyCallback  callback,
1144                      gpointer             user_data)
1145 {
1146   data->simple = g_simple_async_result_new (NULL,
1147                                             callback,
1148                                             user_data,
1149                                             write_message_async);
1150   data->total_written = 0;
1151   write_message_continue_writing (data);
1152 }
1153
1154 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1155 static gboolean
1156 write_message_finish (GAsyncResult   *res,
1157                       GError        **error)
1158 {
1159   g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1160   if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1161     return FALSE;
1162   else
1163     return TRUE;
1164 }
1165 /* ---------------------------------------------------------------------------------------------------- */
1166
1167 static void continue_writing (GDBusWorker *worker);
1168
1169 typedef struct
1170 {
1171   GDBusWorker *worker;
1172   GList *flushers;
1173 } FlushAsyncData;
1174
1175 static void
1176 flush_data_list_complete (const GList  *flushers,
1177                           const GError *error)
1178 {
1179   const GList *l;
1180
1181   for (l = flushers; l != NULL; l = l->next)
1182     {
1183       FlushData *f = l->data;
1184
1185       f->error = error != NULL ? g_error_copy (error) : NULL;
1186
1187       g_mutex_lock (&f->mutex);
1188       g_cond_signal (&f->cond);
1189       g_mutex_unlock (&f->mutex);
1190     }
1191 }
1192
1193 /* called in private thread shared by all GDBusConnection instances
1194  *
1195  * write-lock is not held on entry
1196  * output_pending is PENDING_FLUSH on entry
1197  */
1198 static void
1199 ostream_flush_cb (GObject      *source_object,
1200                   GAsyncResult *res,
1201                   gpointer      user_data)
1202 {
1203   FlushAsyncData *data = user_data;
1204   GError *error;
1205
1206   error = NULL;
1207   g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1208                                 res,
1209                                 &error);
1210
1211   if (error == NULL)
1212     {
1213       if (G_UNLIKELY (_g_dbus_debug_transport ()))
1214         {
1215           _g_dbus_debug_print_lock ();
1216           g_print ("========================================================================\n"
1217                    "GDBus-debug:Transport:\n"
1218                    "  ---- FLUSHED stream of type %s\n",
1219                    g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1220           _g_dbus_debug_print_unlock ();
1221         }
1222     }
1223
1224   g_assert (data->flushers != NULL);
1225   flush_data_list_complete (data->flushers, error);
1226   g_list_free (data->flushers);
1227
1228   if (error != NULL)
1229     g_error_free (error);
1230
1231   /* Make sure we tell folks that we don't have additional
1232      flushes pending */
1233   g_mutex_lock (&data->worker->write_lock);
1234   data->worker->write_num_messages_flushed = data->worker->write_num_messages_written;
1235   g_assert (data->worker->output_pending == PENDING_FLUSH);
1236   data->worker->output_pending = PENDING_NONE;
1237   g_mutex_unlock (&data->worker->write_lock);
1238
1239   /* OK, cool, finally kick off the next write */
1240   continue_writing (data->worker);
1241
1242   _g_dbus_worker_unref (data->worker);
1243   g_free (data);
1244 }
1245
1246 /* called in private thread shared by all GDBusConnection instances
1247  *
1248  * write-lock is not held on entry
1249  * output_pending is PENDING_FLUSH on entry
1250  */
1251 static void
1252 start_flush (FlushAsyncData *data)
1253 {
1254   g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1255                                G_PRIORITY_DEFAULT,
1256                                data->worker->cancellable,
1257                                ostream_flush_cb,
1258                                data);
1259 }
1260
1261 /* called in private thread shared by all GDBusConnection instances
1262  *
1263  * write-lock is held on entry
1264  * output_pending is PENDING_NONE on entry
1265  */
1266 static void
1267 message_written_unlocked (GDBusWorker *worker,
1268                           MessageToWriteData *message_data)
1269 {
1270   if (G_UNLIKELY (_g_dbus_debug_message ()))
1271     {
1272       gchar *s;
1273       _g_dbus_debug_print_lock ();
1274       g_print ("========================================================================\n"
1275                "GDBus-debug:Message:\n"
1276                "  >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1277                message_data->blob_size);
1278       s = g_dbus_message_print (message_data->message, 2);
1279       g_print ("%s", s);
1280       g_free (s);
1281       if (G_UNLIKELY (_g_dbus_debug_payload ()))
1282         {
1283           s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1284           g_print ("%s\n", s);
1285           g_free (s);
1286         }
1287       _g_dbus_debug_print_unlock ();
1288     }
1289
1290   worker->write_num_messages_written += 1;
1291 }
1292
1293 /* called in private thread shared by all GDBusConnection instances
1294  *
1295  * write-lock is held on entry
1296  * output_pending is PENDING_NONE on entry
1297  *
1298  * Returns: non-%NULL, setting @output_pending, if we need to flush now
1299  */
1300 static FlushAsyncData *
1301 prepare_flush_unlocked (GDBusWorker *worker)
1302 {
1303   GList *l;
1304   GList *ll;
1305   GList *flushers;
1306
1307   flushers = NULL;
1308   for (l = worker->write_pending_flushes; l != NULL; l = ll)
1309     {
1310       FlushData *f = l->data;
1311       ll = l->next;
1312
1313       if (f->number_to_wait_for == worker->write_num_messages_written)
1314         {
1315           flushers = g_list_append (flushers, f);
1316           worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1317         }
1318     }
1319   if (flushers != NULL)
1320     {
1321       g_assert (worker->output_pending == PENDING_NONE);
1322       worker->output_pending = PENDING_FLUSH;
1323     }
1324
1325   if (flushers != NULL)
1326     {
1327       FlushAsyncData *data;
1328
1329       data = g_new0 (FlushAsyncData, 1);
1330       data->worker = _g_dbus_worker_ref (worker);
1331       data->flushers = flushers;
1332       return data;
1333     }
1334
1335   return NULL;
1336 }
1337
1338 /* called in private thread shared by all GDBusConnection instances
1339  *
1340  * write-lock is not held on entry
1341  * output_pending is PENDING_WRITE on entry
1342  */
1343 static void
1344 write_message_cb (GObject       *source_object,
1345                   GAsyncResult  *res,
1346                   gpointer       user_data)
1347 {
1348   MessageToWriteData *data = user_data;
1349   GError *error;
1350
1351   g_mutex_lock (&data->worker->write_lock);
1352   g_assert (data->worker->output_pending == PENDING_WRITE);
1353   data->worker->output_pending = PENDING_NONE;
1354
1355   error = NULL;
1356   if (!write_message_finish (res, &error))
1357     {
1358       g_mutex_unlock (&data->worker->write_lock);
1359
1360       /* TODO: handle */
1361       _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1362       g_error_free (error);
1363
1364       g_mutex_lock (&data->worker->write_lock);
1365     }
1366
1367   message_written_unlocked (data->worker, data);
1368
1369   g_mutex_unlock (&data->worker->write_lock);
1370
1371   continue_writing (data->worker);
1372
1373   message_to_write_data_free (data);
1374 }
1375
1376 /* called in private thread shared by all GDBusConnection instances
1377  *
1378  * write-lock is not held on entry
1379  * output_pending is PENDING_CLOSE on entry
1380  */
1381 static void
1382 iostream_close_cb (GObject      *source_object,
1383                    GAsyncResult *res,
1384                    gpointer      user_data)
1385 {
1386   GDBusWorker *worker = user_data;
1387   GError *error = NULL;
1388   GList *pending_close_attempts, *pending_flush_attempts;
1389   GQueue *send_queue;
1390
1391   g_io_stream_close_finish (worker->stream, res, &error);
1392
1393   g_mutex_lock (&worker->write_lock);
1394
1395   pending_close_attempts = worker->pending_close_attempts;
1396   worker->pending_close_attempts = NULL;
1397
1398   pending_flush_attempts = worker->write_pending_flushes;
1399   worker->write_pending_flushes = NULL;
1400
1401   send_queue = worker->write_queue;
1402   worker->write_queue = g_queue_new ();
1403
1404   g_assert (worker->output_pending == PENDING_CLOSE);
1405   worker->output_pending = PENDING_NONE;
1406
1407   g_mutex_unlock (&worker->write_lock);
1408
1409   while (pending_close_attempts != NULL)
1410     {
1411       CloseData *close_data = pending_close_attempts->data;
1412
1413       pending_close_attempts = g_list_delete_link (pending_close_attempts,
1414                                                    pending_close_attempts);
1415
1416       if (close_data->result != NULL)
1417         {
1418           if (error != NULL)
1419             g_simple_async_result_set_from_error (close_data->result, error);
1420
1421           /* this must be in an idle because the result is likely to be
1422            * intended for another thread
1423            */
1424           g_simple_async_result_complete_in_idle (close_data->result);
1425         }
1426
1427       close_data_free (close_data);
1428     }
1429
1430   g_clear_error (&error);
1431
1432   /* all messages queued for sending are discarded */
1433   g_queue_free_full (send_queue, (GDestroyNotify) message_to_write_data_free);
1434   /* all queued flushes fail */
1435   error = g_error_new (G_IO_ERROR, G_IO_ERROR_CANCELLED,
1436                        _("Operation was cancelled"));
1437   flush_data_list_complete (pending_flush_attempts, error);
1438   g_list_free (pending_flush_attempts);
1439   g_clear_error (&error);
1440
1441   _g_dbus_worker_unref (worker);
1442 }
1443
1444 /* called in private thread shared by all GDBusConnection instances
1445  *
1446  * write-lock is not held on entry
1447  * output_pending must be PENDING_NONE on entry
1448  */
1449 static void
1450 continue_writing (GDBusWorker *worker)
1451 {
1452   MessageToWriteData *data;
1453   FlushAsyncData *flush_async_data;
1454
1455  write_next:
1456   /* we mustn't try to write two things at once */
1457   g_assert (worker->output_pending == PENDING_NONE);
1458
1459   g_mutex_lock (&worker->write_lock);
1460
1461   data = NULL;
1462   flush_async_data = NULL;
1463
1464   /* if we want to close the connection, that takes precedence */
1465   if (worker->pending_close_attempts != NULL)
1466     {
1467       worker->close_expected = TRUE;
1468       worker->output_pending = PENDING_CLOSE;
1469
1470       g_io_stream_close_async (worker->stream, G_PRIORITY_DEFAULT,
1471                                NULL, iostream_close_cb,
1472                                _g_dbus_worker_ref (worker));
1473     }
1474   else
1475     {
1476       flush_async_data = prepare_flush_unlocked (worker);
1477
1478       if (flush_async_data == NULL)
1479         {
1480           data = g_queue_pop_head (worker->write_queue);
1481
1482           if (data != NULL)
1483             worker->output_pending = PENDING_WRITE;
1484         }
1485     }
1486
1487   g_mutex_unlock (&worker->write_lock);
1488
1489   /* Note that write_lock is only used for protecting the @write_queue
1490    * and @output_pending fields of the GDBusWorker struct ... which we
1491    * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1492    *
1493    * Therefore, it's fine to drop it here when calling back into user
1494    * code and then writing the message out onto the GIOStream since this
1495    * function only runs on the worker thread.
1496    */
1497
1498   if (flush_async_data != NULL)
1499     {
1500       start_flush (flush_async_data);
1501       g_assert (data == NULL);
1502     }
1503   else if (data != NULL)
1504     {
1505       GDBusMessage *old_message;
1506       guchar *new_blob;
1507       gsize new_blob_size;
1508       GError *error;
1509
1510       old_message = data->message;
1511       data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1512       if (data->message == old_message)
1513         {
1514           /* filters had no effect - do nothing */
1515         }
1516       else if (data->message == NULL)
1517         {
1518           /* filters dropped message */
1519           g_mutex_lock (&worker->write_lock);
1520           worker->output_pending = PENDING_NONE;
1521           g_mutex_unlock (&worker->write_lock);
1522           message_to_write_data_free (data);
1523           goto write_next;
1524         }
1525       else
1526         {
1527           /* filters altered the message -> reencode */
1528           error = NULL;
1529           new_blob = g_dbus_message_to_blob (data->message,
1530                                              &new_blob_size,
1531                                              worker->capabilities,
1532                                              &error);
1533           if (new_blob == NULL)
1534             {
1535               /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1536                * the old message instead
1537                */
1538               g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1539                          g_dbus_message_get_serial (data->message),
1540                          error->message);
1541               g_error_free (error);
1542             }
1543           else
1544             {
1545               g_free (data->blob);
1546               data->blob = (gchar *) new_blob;
1547               data->blob_size = new_blob_size;
1548             }
1549         }
1550
1551       write_message_async (worker,
1552                            data,
1553                            write_message_cb,
1554                            data);
1555     }
1556 }
1557
1558 /* called in private thread shared by all GDBusConnection instances
1559  *
1560  * write-lock is not held on entry
1561  * output_pending may be anything
1562  */
1563 static gboolean
1564 continue_writing_in_idle_cb (gpointer user_data)
1565 {
1566   GDBusWorker *worker = user_data;
1567
1568   /* Because this is the worker thread, we can read this struct member
1569    * without holding the lock: no other thread ever modifies it.
1570    */
1571   if (worker->output_pending == PENDING_NONE)
1572     continue_writing (worker);
1573
1574   return FALSE;
1575 }
1576
1577 /*
1578  * @write_data: (transfer full) (allow-none):
1579  * @flush_data: (transfer full) (allow-none):
1580  * @close_data: (transfer full) (allow-none):
1581  *
1582  * Can be called from any thread
1583  *
1584  * write_lock is held on entry
1585  * output_pending may be anything
1586  */
1587 static void
1588 schedule_writing_unlocked (GDBusWorker        *worker,
1589                            MessageToWriteData *write_data,
1590                            FlushData          *flush_data,
1591                            CloseData          *close_data)
1592 {
1593   if (write_data != NULL)
1594     g_queue_push_tail (worker->write_queue, write_data);
1595
1596   if (flush_data != NULL)
1597     worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, flush_data);
1598
1599   if (close_data != NULL)
1600     worker->pending_close_attempts = g_list_prepend (worker->pending_close_attempts,
1601                                                      close_data);
1602
1603   /* If we had output pending, the next bit of output will happen
1604    * automatically when it finishes, so we only need to do this
1605    * if nothing was pending.
1606    *
1607    * The idle callback will re-check that output_pending is still
1608    * PENDING_NONE, to guard against output starting before the idle.
1609    */
1610   if (worker->output_pending == PENDING_NONE)
1611     {
1612       GSource *idle_source;
1613       idle_source = g_idle_source_new ();
1614       g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1615       g_source_set_callback (idle_source,
1616                              continue_writing_in_idle_cb,
1617                              _g_dbus_worker_ref (worker),
1618                              (GDestroyNotify) _g_dbus_worker_unref);
1619       g_source_attach (idle_source, worker->shared_thread_data->context);
1620       g_source_unref (idle_source);
1621     }
1622 }
1623
1624 /* ---------------------------------------------------------------------------------------------------- */
1625
1626 /* can be called from any thread - steals blob
1627  *
1628  * write_lock is not held on entry
1629  * output_pending may be anything
1630  */
1631 void
1632 _g_dbus_worker_send_message (GDBusWorker    *worker,
1633                              GDBusMessage   *message,
1634                              gchar          *blob,
1635                              gsize           blob_len)
1636 {
1637   MessageToWriteData *data;
1638
1639   g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1640   g_return_if_fail (blob != NULL);
1641   g_return_if_fail (blob_len > 16);
1642
1643   data = g_new0 (MessageToWriteData, 1);
1644   data->worker = _g_dbus_worker_ref (worker);
1645   data->message = g_object_ref (message);
1646   data->blob = blob; /* steal! */
1647   data->blob_size = blob_len;
1648
1649   g_mutex_lock (&worker->write_lock);
1650   schedule_writing_unlocked (worker, data, NULL, NULL);
1651   g_mutex_unlock (&worker->write_lock);
1652 }
1653
1654 /* ---------------------------------------------------------------------------------------------------- */
1655 GKdbus*        g_dbus_worker_get_kdbus    (GDBusWorker  *worker)
1656 {
1657   return worker->kdbus;
1658 }
1659
1660 GDBusWorker *
1661 _g_dbus_worker_new (GIOStream                              *stream,
1662                     GDBusCapabilityFlags                    capabilities,
1663                     gboolean                                initially_frozen,
1664                     GDBusWorkerMessageReceivedCallback      message_received_callback,
1665                     GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1666                     GDBusWorkerDisconnectedCallback         disconnected_callback,
1667                     gpointer                                user_data)
1668 {
1669   GDBusWorker *worker;
1670   GSource *idle_source;
1671
1672   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1673   g_return_val_if_fail (message_received_callback != NULL, NULL);
1674   g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1675   g_return_val_if_fail (disconnected_callback != NULL, NULL);
1676
1677   worker = g_new0 (GDBusWorker, 1);
1678   worker->ref_count = 1;
1679
1680   g_mutex_init (&worker->read_lock);
1681   worker->message_received_callback = message_received_callback;
1682   worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1683   worker->disconnected_callback = disconnected_callback;
1684   worker->user_data = user_data;
1685   worker->stream = g_object_ref (stream);
1686   worker->capabilities = capabilities;
1687   worker->cancellable = g_cancellable_new ();
1688   worker->output_pending = PENDING_NONE;
1689
1690   worker->frozen = initially_frozen;
1691   worker->received_messages_while_frozen = g_queue_new ();
1692
1693   g_mutex_init (&worker->write_lock);
1694   worker->write_queue = g_queue_new ();
1695
1696   if (G_IS_SOCKET_CONNECTION (worker->stream))
1697     worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1698
1699   if (G_IS_KDBUS_CONNECTION (worker->stream))
1700     worker->kdbus = g_kdbus_connection_get_kdbus (G_KDBUS_CONNECTION (worker->stream));
1701
1702   worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1703
1704   /* begin reading */
1705   idle_source = g_idle_source_new ();
1706   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1707   g_source_set_callback (idle_source,
1708                          _g_dbus_worker_do_initial_read,
1709                          _g_dbus_worker_ref (worker),
1710                          (GDestroyNotify) _g_dbus_worker_unref);
1711   g_source_attach (idle_source, worker->shared_thread_data->context);
1712   g_source_unref (idle_source);
1713
1714   return worker;
1715 }
1716
1717 /* ---------------------------------------------------------------------------------------------------- */
1718
1719 /* can be called from any thread
1720  *
1721  * write_lock is not held on entry
1722  * output_pending may be anything
1723  */
1724 void
1725 _g_dbus_worker_close (GDBusWorker         *worker,
1726                       GCancellable        *cancellable,
1727                       GSimpleAsyncResult  *result)
1728 {
1729   CloseData *close_data;
1730
1731   close_data = g_slice_new0 (CloseData);
1732   close_data->worker = _g_dbus_worker_ref (worker);
1733   close_data->cancellable =
1734       (cancellable == NULL ? NULL : g_object_ref (cancellable));
1735   close_data->result = (result == NULL ? NULL : g_object_ref (result));
1736
1737   /* Don't set worker->close_expected here - we're in the wrong thread.
1738    * It'll be set before the actual close happens.
1739    */
1740   g_cancellable_cancel (worker->cancellable);
1741   g_mutex_lock (&worker->write_lock);
1742   schedule_writing_unlocked (worker, NULL, NULL, close_data);
1743   g_mutex_unlock (&worker->write_lock);
1744 }
1745
1746 /* This can be called from any thread - frees worker. Note that
1747  * callbacks might still happen if called from another thread than the
1748  * worker - use your own synchronization primitive in the callbacks.
1749  *
1750  * write_lock is not held on entry
1751  * output_pending may be anything
1752  */
1753 void
1754 _g_dbus_worker_stop (GDBusWorker *worker)
1755 {
1756   g_atomic_int_set (&worker->stopped, TRUE);
1757
1758   /* Cancel any pending operations and schedule a close of the underlying I/O
1759    * stream in the worker thread
1760    */
1761   _g_dbus_worker_close (worker, NULL, NULL);
1762
1763   /* _g_dbus_worker_close holds a ref until after an idle in the worker
1764    * thread has run, so we no longer need to unref in an idle like in
1765    * commit 322e25b535
1766    */
1767   _g_dbus_worker_unref (worker);
1768 }
1769
1770 /* ---------------------------------------------------------------------------------------------------- */
1771
1772 /* can be called from any thread (except the worker thread) - blocks
1773  * calling thread until all queued outgoing messages are written and
1774  * the transport has been flushed
1775  *
1776  * write_lock is not held on entry
1777  * output_pending may be anything
1778  */
1779 gboolean
1780 _g_dbus_worker_flush_sync (GDBusWorker    *worker,
1781                            GCancellable   *cancellable,
1782                            GError        **error)
1783 {
1784   gboolean ret;
1785   FlushData *data;
1786   guint64 pending_writes;
1787
1788   data = NULL;
1789   ret = TRUE;
1790
1791   g_mutex_lock (&worker->write_lock);
1792
1793   /* if the queue is empty, no write is in-flight and we haven't written
1794    * anything since the last flush, then there's nothing to wait for
1795    */
1796   pending_writes = g_queue_get_length (worker->write_queue);
1797
1798   /* if a write is in-flight, we shouldn't be satisfied until the first
1799    * flush operation that follows it
1800    */
1801   if (worker->output_pending == PENDING_WRITE)
1802     pending_writes += 1;
1803
1804   if (pending_writes > 0 ||
1805       worker->write_num_messages_written != worker->write_num_messages_flushed)
1806     {
1807       data = g_new0 (FlushData, 1);
1808       g_mutex_init (&data->mutex);
1809       g_cond_init (&data->cond);
1810       data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
1811       g_mutex_lock (&data->mutex);
1812
1813       schedule_writing_unlocked (worker, NULL, data, NULL);
1814     }
1815   g_mutex_unlock (&worker->write_lock);
1816
1817   if (data != NULL)
1818     {
1819       g_cond_wait (&data->cond, &data->mutex);
1820       g_mutex_unlock (&data->mutex);
1821
1822       /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1823       g_cond_clear (&data->cond);
1824       g_mutex_clear (&data->mutex);
1825       if (data->error != NULL)
1826         {
1827           ret = FALSE;
1828           g_propagate_error (error, data->error);
1829         }
1830       g_free (data);
1831     }
1832
1833   return ret;
1834 }
1835
1836 /* ---------------------------------------------------------------------------------------------------- */
1837
1838 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1839 #define G_DBUS_DEBUG_TRANSPORT      (1<<1)
1840 #define G_DBUS_DEBUG_MESSAGE        (1<<2)
1841 #define G_DBUS_DEBUG_PAYLOAD        (1<<3)
1842 #define G_DBUS_DEBUG_CALL           (1<<4)
1843 #define G_DBUS_DEBUG_SIGNAL         (1<<5)
1844 #define G_DBUS_DEBUG_INCOMING       (1<<6)
1845 #define G_DBUS_DEBUG_RETURN         (1<<7)
1846 #define G_DBUS_DEBUG_EMISSION       (1<<8)
1847 #define G_DBUS_DEBUG_ADDRESS        (1<<9)
1848
1849 static gint _gdbus_debug_flags = 0;
1850
1851 gboolean
1852 _g_dbus_debug_authentication (void)
1853 {
1854   _g_dbus_initialize ();
1855   return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1856 }
1857
1858 gboolean
1859 _g_dbus_debug_transport (void)
1860 {
1861   _g_dbus_initialize ();
1862   return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1863 }
1864
1865 gboolean
1866 _g_dbus_debug_message (void)
1867 {
1868   _g_dbus_initialize ();
1869   return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1870 }
1871
1872 gboolean
1873 _g_dbus_debug_payload (void)
1874 {
1875   _g_dbus_initialize ();
1876   return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1877 }
1878
1879 gboolean
1880 _g_dbus_debug_call (void)
1881 {
1882   _g_dbus_initialize ();
1883   return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1884 }
1885
1886 gboolean
1887 _g_dbus_debug_signal (void)
1888 {
1889   _g_dbus_initialize ();
1890   return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1891 }
1892
1893 gboolean
1894 _g_dbus_debug_incoming (void)
1895 {
1896   _g_dbus_initialize ();
1897   return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1898 }
1899
1900 gboolean
1901 _g_dbus_debug_return (void)
1902 {
1903   _g_dbus_initialize ();
1904   return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1905 }
1906
1907 gboolean
1908 _g_dbus_debug_emission (void)
1909 {
1910   _g_dbus_initialize ();
1911   return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1912 }
1913
1914 gboolean
1915 _g_dbus_debug_address (void)
1916 {
1917   _g_dbus_initialize ();
1918   return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1919 }
1920
1921 G_LOCK_DEFINE_STATIC (print_lock);
1922
1923 void
1924 _g_dbus_debug_print_lock (void)
1925 {
1926   G_LOCK (print_lock);
1927 }
1928
1929 void
1930 _g_dbus_debug_print_unlock (void)
1931 {
1932   G_UNLOCK (print_lock);
1933 }
1934
1935 /*
1936  * _g_dbus_initialize:
1937  *
1938  * Does various one-time init things such as
1939  *
1940  *  - registering the G_DBUS_ERROR error domain
1941  *  - parses the G_DBUS_DEBUG environment variable
1942  */
1943 void
1944 _g_dbus_initialize (void)
1945 {
1946   static volatile gsize initialized = 0;
1947
1948   if (g_once_init_enter (&initialized))
1949     {
1950       volatile GQuark g_dbus_error_domain;
1951       const gchar *debug;
1952
1953       g_dbus_error_domain = G_DBUS_ERROR;
1954       (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1955
1956       debug = g_getenv ("G_DBUS_DEBUG");
1957       if (debug != NULL)
1958         {
1959           const GDebugKey keys[] = {
1960             { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1961             { "transport",      G_DBUS_DEBUG_TRANSPORT      },
1962             { "message",        G_DBUS_DEBUG_MESSAGE        },
1963             { "payload",        G_DBUS_DEBUG_PAYLOAD        },
1964             { "call",           G_DBUS_DEBUG_CALL           },
1965             { "signal",         G_DBUS_DEBUG_SIGNAL         },
1966             { "incoming",       G_DBUS_DEBUG_INCOMING       },
1967             { "return",         G_DBUS_DEBUG_RETURN         },
1968             { "emission",       G_DBUS_DEBUG_EMISSION       },
1969             { "address",        G_DBUS_DEBUG_ADDRESS        }
1970           };
1971
1972           _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1973           if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1974             _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1975         }
1976
1977       g_once_init_leave (&initialized, 1);
1978     }
1979 }
1980
1981 /* ---------------------------------------------------------------------------------------------------- */
1982
1983 GVariantType *
1984 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1985 {
1986   const GVariantType *arg_types[256];
1987   guint n;
1988
1989   if (args)
1990     for (n = 0; args[n] != NULL; n++)
1991       {
1992         /* DBus places a hard limit of 255 on signature length.
1993          * therefore number of args must be less than 256.
1994          */
1995         g_assert (n < 256);
1996
1997         arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1998
1999         if G_UNLIKELY (arg_types[n] == NULL)
2000           return NULL;
2001       }
2002   else
2003     n = 0;
2004
2005   return g_variant_type_new_tuple (arg_types, n);
2006 }
2007
2008 /* ---------------------------------------------------------------------------------------------------- */
2009
2010 #ifdef G_OS_WIN32
2011
2012 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
2013
2014 gchar *
2015 _g_dbus_win32_get_user_sid (void)
2016 {
2017   HANDLE h;
2018   TOKEN_USER *user;
2019   DWORD token_information_len;
2020   PSID psid;
2021   gchar *sid;
2022   gchar *ret;
2023
2024   ret = NULL;
2025   user = NULL;
2026   h = INVALID_HANDLE_VALUE;
2027
2028   if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
2029     {
2030       g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
2031       goto out;
2032     }
2033
2034   /* Get length of buffer */
2035   token_information_len = 0;
2036   if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
2037     {
2038       if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
2039         {
2040           g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2041           goto out;
2042         }
2043     }
2044   user = g_malloc (token_information_len);
2045   if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
2046     {
2047       g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2048       goto out;
2049     }
2050
2051   psid = user->User.Sid;
2052   if (!IsValidSid (psid))
2053     {
2054       g_warning ("Invalid SID");
2055       goto out;
2056     }
2057
2058   if (!ConvertSidToStringSidA (psid, &sid))
2059     {
2060       g_warning ("Invalid SID");
2061       goto out;
2062     }
2063
2064   ret = g_strdup (sid);
2065   LocalFree (sid);
2066
2067 out:
2068   g_free (user);
2069   if (h != INVALID_HANDLE_VALUE)
2070     CloseHandle (h);
2071   return ret;
2072 }
2073 #endif
2074
2075 /* ---------------------------------------------------------------------------------------------------- */
2076
2077 gchar *
2078 _g_dbus_get_machine_id (GError **error)
2079 {
2080 #ifdef G_OS_WIN32
2081   HW_PROFILE_INFOA info;
2082   char *src, *dest, *res;
2083   int i;
2084
2085   if (!GetCurrentHwProfileA (&info))
2086     {
2087       char *message = g_win32_error_message (GetLastError ());
2088       g_set_error (error,
2089                    G_IO_ERROR,
2090                    G_IO_ERROR_FAILED,
2091                    _("Unable to get Hardware profile: %s"), message);
2092       g_free (message);
2093       return NULL;
2094     }
2095
2096   /* Form: {12340001-4980-1920-6788-123456789012} */
2097   src = &info.szHwProfileGuid[0];
2098
2099   res = g_malloc (32+1);
2100   dest = res;
2101
2102   src++; /* Skip { */
2103   for (i = 0; i < 8; i++)
2104     *dest++ = *src++;
2105   src++; /* Skip - */
2106   for (i = 0; i < 4; i++)
2107     *dest++ = *src++;
2108   src++; /* Skip - */
2109   for (i = 0; i < 4; i++)
2110     *dest++ = *src++;
2111   src++; /* Skip - */
2112   for (i = 0; i < 4; i++)
2113     *dest++ = *src++;
2114   src++; /* Skip - */
2115   for (i = 0; i < 12; i++)
2116     *dest++ = *src++;
2117   *dest = 0;
2118
2119   return res;
2120 #else
2121   gchar *ret;
2122   GError *first_error;
2123   /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2124   ret = NULL;
2125   first_error = NULL;
2126   if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2127                             &ret,
2128                             NULL,
2129                             &first_error) &&
2130       !g_file_get_contents ("/etc/machine-id",
2131                             &ret,
2132                             NULL,
2133                             NULL))
2134     {
2135       g_propagate_prefixed_error (error, first_error,
2136                                   _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2137     }
2138   else
2139     {
2140       /* ignore the error from the first try, if any */
2141       g_clear_error (&first_error);
2142       /* TODO: validate value */
2143       g_strstrip (ret);
2144     }
2145   return ret;
2146 #endif
2147 }
2148
2149 /* ---------------------------------------------------------------------------------------------------- */
2150
2151 gchar *
2152 _g_dbus_enum_to_string (GType enum_type, gint value)
2153 {
2154   gchar *ret;
2155   GEnumClass *klass;
2156   GEnumValue *enum_value;
2157
2158   klass = g_type_class_ref (enum_type);
2159   enum_value = g_enum_get_value (klass, value);
2160   if (enum_value != NULL)
2161     ret = g_strdup (enum_value->value_nick);
2162   else
2163     ret = g_strdup_printf ("unknown (value %d)", value);
2164   g_type_class_unref (klass);
2165   return ret;
2166 }
2167
2168 /* ---------------------------------------------------------------------------------------------------- */
2169
2170 static void
2171 write_message_print_transport_debug (gssize bytes_written,
2172                                      MessageToWriteData *data)
2173 {
2174   if (G_LIKELY (!_g_dbus_debug_transport ()))
2175     goto out;
2176
2177   _g_dbus_debug_print_lock ();
2178   g_print ("========================================================================\n"
2179            "GDBus-debug:Transport:\n"
2180            "  >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2181            "       size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
2182            bytes_written,
2183            g_dbus_message_get_serial (data->message),
2184            data->blob_size,
2185            data->total_written,
2186            g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
2187   _g_dbus_debug_print_unlock ();
2188  out:
2189   ;
2190 }
2191
2192 /* ---------------------------------------------------------------------------------------------------- */
2193
2194 static void
2195 read_message_print_transport_debug (gssize bytes_read,
2196                                     GDBusWorker *worker)
2197 {
2198   gsize size;
2199   gint32 serial;
2200   gint32 message_length;
2201
2202   if (G_LIKELY (!_g_dbus_debug_transport ()))
2203     goto out;
2204
2205   size = bytes_read + worker->read_buffer_cur_size;
2206   serial = 0;
2207   message_length = 0;
2208   if (size >= 16)
2209     message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2210   if (size >= 1)
2211     {
2212       switch (worker->read_buffer[0])
2213         {
2214         case 'l':
2215           if (size >= 12)
2216             serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2217           break;
2218         case 'B':
2219           if (size >= 12)
2220             serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2221           break;
2222         default:
2223           /* an error will be set elsewhere if this happens */
2224           goto out;
2225         }
2226     }
2227
2228     _g_dbus_debug_print_lock ();
2229   g_print ("========================================================================\n"
2230            "GDBus-debug:Transport:\n"
2231            "  <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2232            "       size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
2233            bytes_read,
2234            serial,
2235            message_length,
2236            worker->read_buffer_cur_size,
2237            g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
2238   _g_dbus_debug_print_unlock ();
2239  out:
2240   ;
2241 }
2242
2243 /* ---------------------------------------------------------------------------------------------------- */
2244
2245 gboolean
2246 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2247                                      GValue                *return_accu,
2248                                      const GValue          *handler_return,
2249                                      gpointer               dummy)
2250 {
2251   gboolean continue_emission;
2252   gboolean signal_return;
2253
2254   signal_return = g_value_get_boolean (handler_return);
2255   g_value_set_boolean (return_accu, signal_return);
2256   continue_emission = signal_return;
2257
2258   return continue_emission;
2259 }