GDBusWorker: combine num_writes_pending with flush_pending
[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   GError *error = NULL;
291   SharedThreadData *ret;
292
293   if (g_once_init_enter (&shared_thread_data))
294     {
295       SharedThreadData *data;
296
297       /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
298       ensure_required_types ();
299
300       data = g_new0 (SharedThreadData, 1);
301       data->refcount = 0;
302       
303       data->context = g_main_context_new ();
304       data->loop = g_main_loop_new (data->context, FALSE);
305       data->thread = g_thread_create (gdbus_shared_thread_func,
306                                       data,
307                                       TRUE,
308                                       &error);
309       g_assert_no_error (error);
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 struct GDBusWorker
338 {
339   volatile gint                       ref_count;
340
341   SharedThreadData                   *shared_thread_data;
342
343   gboolean                            stopped;
344
345   /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
346    * only affects messages received from the other peer (since GDBusServer is the
347    * only user) - we might want it to affect messages sent to the other peer too?
348    */
349   gboolean                            frozen;
350   GDBusCapabilityFlags                capabilities;
351   GQueue                             *received_messages_while_frozen;
352
353   GIOStream                          *stream;
354   GCancellable                       *cancellable;
355   GDBusWorkerMessageReceivedCallback  message_received_callback;
356   GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
357   GDBusWorkerDisconnectedCallback     disconnected_callback;
358   gpointer                            user_data;
359
360   /* if not NULL, stream is GSocketConnection */
361   GSocket *socket;
362
363   /* used for reading */
364   GMutex                             *read_lock;
365   gchar                              *read_buffer;
366   gsize                               read_buffer_allocated_size;
367   gsize                               read_buffer_cur_size;
368   gsize                               read_buffer_bytes_wanted;
369   GUnixFDList                        *read_fd_list;
370   GSocketControlMessage             **read_ancillary_messages;
371   gint                                read_num_ancillary_messages;
372
373   /* TRUE if an async write or flush is pending.
374    * Only the worker thread may change its value, and only with the write_lock.
375    * Other threads may read its value when holding the write_lock.
376    * The worker thread may read its value at any time.
377    */
378   gboolean                            output_pending;
379   /* used for writing */
380   GMutex                             *write_lock;
381   GQueue                             *write_queue;
382   guint64                             write_num_messages_written;
383   GList                              *write_pending_flushes;
384 };
385
386 /* ---------------------------------------------------------------------------------------------------- */
387
388 typedef struct
389 {
390   GMutex *mutex;
391   GCond *cond;
392   guint64 number_to_wait_for;
393   GError *error;
394 } FlushData;
395
396 struct _MessageToWriteData ;
397 typedef struct _MessageToWriteData MessageToWriteData;
398
399 static void message_to_write_data_free (MessageToWriteData *data);
400
401 static void read_message_print_transport_debug (gssize bytes_read,
402                                                 GDBusWorker *worker);
403
404 static void write_message_print_transport_debug (gssize bytes_written,
405                                                  MessageToWriteData *data);
406
407 /* ---------------------------------------------------------------------------------------------------- */
408
409 static GDBusWorker *
410 _g_dbus_worker_ref (GDBusWorker *worker)
411 {
412   g_atomic_int_inc (&worker->ref_count);
413   return worker;
414 }
415
416 static void
417 _g_dbus_worker_unref (GDBusWorker *worker)
418 {
419   if (g_atomic_int_dec_and_test (&worker->ref_count))
420     {
421       g_assert (worker->write_pending_flushes == NULL);
422
423       _g_dbus_shared_thread_unref (worker->shared_thread_data);
424
425       g_object_unref (worker->stream);
426
427       g_mutex_free (worker->read_lock);
428       g_object_unref (worker->cancellable);
429       if (worker->read_fd_list != NULL)
430         g_object_unref (worker->read_fd_list);
431
432       g_queue_foreach (worker->received_messages_while_frozen, (GFunc) g_object_unref, NULL);
433       g_queue_free (worker->received_messages_while_frozen);
434
435       g_mutex_free (worker->write_lock);
436       g_queue_foreach (worker->write_queue, (GFunc) message_to_write_data_free, NULL);
437       g_queue_free (worker->write_queue);
438
439       g_free (worker->read_buffer);
440
441       g_free (worker);
442     }
443 }
444
445 static void
446 _g_dbus_worker_emit_disconnected (GDBusWorker  *worker,
447                                   gboolean      remote_peer_vanished,
448                                   GError       *error)
449 {
450   if (!worker->stopped)
451     worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
452 }
453
454 static void
455 _g_dbus_worker_emit_message_received (GDBusWorker  *worker,
456                                       GDBusMessage *message)
457 {
458   if (!worker->stopped)
459     worker->message_received_callback (worker, message, worker->user_data);
460 }
461
462 static GDBusMessage *
463 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker  *worker,
464                                               GDBusMessage *message)
465 {
466   GDBusMessage *ret;
467   if (!worker->stopped)
468     ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
469   else
470     ret = message;
471   return ret;
472 }
473
474 /* can only be called from private thread with read-lock held - takes ownership of @message */
475 static void
476 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker  *worker,
477                                                   GDBusMessage *message)
478 {
479   if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
480     {
481       /* queue up */
482       g_queue_push_tail (worker->received_messages_while_frozen, message);
483     }
484   else
485     {
486       /* not frozen, nor anything in queue */
487       _g_dbus_worker_emit_message_received (worker, message);
488       g_object_unref (message);
489     }
490 }
491
492 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
493 static gboolean
494 unfreeze_in_idle_cb (gpointer user_data)
495 {
496   GDBusWorker *worker = user_data;
497   GDBusMessage *message;
498
499   g_mutex_lock (worker->read_lock);
500   if (worker->frozen)
501     {
502       while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
503         {
504           _g_dbus_worker_emit_message_received (worker, message);
505           g_object_unref (message);
506         }
507       worker->frozen = FALSE;
508     }
509   else
510     {
511       g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
512     }
513   g_mutex_unlock (worker->read_lock);
514   return FALSE;
515 }
516
517 /* can be called from any thread */
518 void
519 _g_dbus_worker_unfreeze (GDBusWorker *worker)
520 {
521   GSource *idle_source;
522   idle_source = g_idle_source_new ();
523   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
524   g_source_set_callback (idle_source,
525                          unfreeze_in_idle_cb,
526                          _g_dbus_worker_ref (worker),
527                          (GDestroyNotify) _g_dbus_worker_unref);
528   g_source_attach (idle_source, worker->shared_thread_data->context);
529   g_source_unref (idle_source);
530 }
531
532 /* ---------------------------------------------------------------------------------------------------- */
533
534 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
535
536 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
537 static void
538 _g_dbus_worker_do_read_cb (GInputStream  *input_stream,
539                            GAsyncResult  *res,
540                            gpointer       user_data)
541 {
542   GDBusWorker *worker = user_data;
543   GError *error;
544   gssize bytes_read;
545
546   g_mutex_lock (worker->read_lock);
547
548   /* If already stopped, don't even process the reply */
549   if (worker->stopped)
550     goto out;
551
552   error = NULL;
553   if (worker->socket == NULL)
554     bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
555                                              res,
556                                              &error);
557   else
558     bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
559                                                               res,
560                                                               &error);
561   if (worker->read_num_ancillary_messages > 0)
562     {
563       gint n;
564       for (n = 0; n < worker->read_num_ancillary_messages; n++)
565         {
566           GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
567
568           if (FALSE)
569             {
570             }
571 #ifdef G_OS_UNIX
572           else if (G_IS_UNIX_FD_MESSAGE (control_message))
573             {
574               GUnixFDMessage *fd_message;
575               gint *fds;
576               gint num_fds;
577
578               fd_message = G_UNIX_FD_MESSAGE (control_message);
579               fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
580               if (worker->read_fd_list == NULL)
581                 {
582                   worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
583                 }
584               else
585                 {
586                   gint n;
587                   for (n = 0; n < num_fds; n++)
588                     {
589                       /* TODO: really want a append_steal() */
590                       g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
591                       close (fds[n]);
592                     }
593                 }
594               g_free (fds);
595             }
596           else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
597             {
598               /* do nothing */
599             }
600 #endif
601           else
602             {
603               if (error == NULL)
604                 {
605                   g_set_error (&error,
606                                G_IO_ERROR,
607                                G_IO_ERROR_FAILED,
608                                "Unexpected ancillary message of type %s received from peer",
609                                g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
610                   _g_dbus_worker_emit_disconnected (worker, TRUE, error);
611                   g_error_free (error);
612                   g_object_unref (control_message);
613                   n++;
614                   while (n < worker->read_num_ancillary_messages)
615                     g_object_unref (worker->read_ancillary_messages[n++]);
616                   g_free (worker->read_ancillary_messages);
617                   goto out;
618                 }
619             }
620           g_object_unref (control_message);
621         }
622       g_free (worker->read_ancillary_messages);
623     }
624
625   if (bytes_read == -1)
626     {
627       _g_dbus_worker_emit_disconnected (worker, TRUE, error);
628       g_error_free (error);
629       goto out;
630     }
631
632 #if 0
633   g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
634            (gint) bytes_read,
635            g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
636            g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
637            g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
638                                      G_IO_IN | G_IO_OUT | G_IO_HUP),
639            worker->stream,
640            worker);
641 #endif
642
643   /* TODO: hmm, hmm... */
644   if (bytes_read == 0)
645     {
646       g_set_error (&error,
647                    G_IO_ERROR,
648                    G_IO_ERROR_FAILED,
649                    "Underlying GIOStream returned 0 bytes on an async read");
650       _g_dbus_worker_emit_disconnected (worker, TRUE, error);
651       g_error_free (error);
652       goto out;
653     }
654
655   read_message_print_transport_debug (bytes_read, worker);
656
657   worker->read_buffer_cur_size += bytes_read;
658   if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
659     {
660       /* OK, got what we asked for! */
661       if (worker->read_buffer_bytes_wanted == 16)
662         {
663           gssize message_len;
664           /* OK, got the header - determine how many more bytes are needed */
665           error = NULL;
666           message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
667                                                      16,
668                                                      &error);
669           if (message_len == -1)
670             {
671               g_warning ("_g_dbus_worker_do_read_cb: error determing bytes needed: %s", error->message);
672               _g_dbus_worker_emit_disconnected (worker, FALSE, error);
673               g_error_free (error);
674               goto out;
675             }
676
677           worker->read_buffer_bytes_wanted = message_len;
678           _g_dbus_worker_do_read_unlocked (worker);
679         }
680       else
681         {
682           GDBusMessage *message;
683           error = NULL;
684
685           /* TODO: use connection->priv->auth to decode the message */
686
687           message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
688                                                   worker->read_buffer_cur_size,
689                                                   worker->capabilities,
690                                                   &error);
691           if (message == NULL)
692             {
693               gchar *s;
694               s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
695               g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
696                          "The error is: %s\n"
697                          "The payload is as follows:\n"
698                          "%s\n",
699                          worker->read_buffer_cur_size,
700                          error->message,
701                          s);
702               g_free (s);
703               _g_dbus_worker_emit_disconnected (worker, FALSE, error);
704               g_error_free (error);
705               goto out;
706             }
707
708 #ifdef G_OS_UNIX
709           if (worker->read_fd_list != NULL)
710             {
711               g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
712               g_object_unref (worker->read_fd_list);
713               worker->read_fd_list = NULL;
714             }
715 #endif
716
717           if (G_UNLIKELY (_g_dbus_debug_message ()))
718             {
719               gchar *s;
720               _g_dbus_debug_print_lock ();
721               g_print ("========================================================================\n"
722                        "GDBus-debug:Message:\n"
723                        "  <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
724                        worker->read_buffer_cur_size);
725               s = g_dbus_message_print (message, 2);
726               g_print ("%s", s);
727               g_free (s);
728               if (G_UNLIKELY (_g_dbus_debug_payload ()))
729                 {
730                   s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
731                   g_print ("%s\n", s);
732                   g_free (s);
733                 }
734               _g_dbus_debug_print_unlock ();
735             }
736
737           /* yay, got a message, go deliver it */
738           _g_dbus_worker_queue_or_deliver_received_message (worker, message);
739
740           /* start reading another message! */
741           worker->read_buffer_bytes_wanted = 0;
742           worker->read_buffer_cur_size = 0;
743           _g_dbus_worker_do_read_unlocked (worker);
744         }
745     }
746   else
747     {
748       /* didn't get all the bytes we requested - so repeat the request... */
749       _g_dbus_worker_do_read_unlocked (worker);
750     }
751
752  out:
753   g_mutex_unlock (worker->read_lock);
754
755   /* gives up the reference acquired when calling g_input_stream_read_async() */
756   _g_dbus_worker_unref (worker);
757 }
758
759 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
760 static void
761 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
762 {
763   /* if bytes_wanted is zero, it means start reading a message */
764   if (worker->read_buffer_bytes_wanted == 0)
765     {
766       worker->read_buffer_cur_size = 0;
767       worker->read_buffer_bytes_wanted = 16;
768     }
769
770   /* ensure we have a (big enough) buffer */
771   if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
772     {
773       /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
774       worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
775       worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
776     }
777
778   if (worker->socket == NULL)
779     g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
780                                worker->read_buffer + worker->read_buffer_cur_size,
781                                worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
782                                G_PRIORITY_DEFAULT,
783                                worker->cancellable,
784                                (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
785                                _g_dbus_worker_ref (worker));
786   else
787     {
788       worker->read_ancillary_messages = NULL;
789       worker->read_num_ancillary_messages = 0;
790       _g_socket_read_with_control_messages (worker->socket,
791                                             worker->read_buffer + worker->read_buffer_cur_size,
792                                             worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
793                                             &worker->read_ancillary_messages,
794                                             &worker->read_num_ancillary_messages,
795                                             G_PRIORITY_DEFAULT,
796                                             worker->cancellable,
797                                             (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
798                                             _g_dbus_worker_ref (worker));
799     }
800 }
801
802 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
803 static gboolean
804 _g_dbus_worker_do_initial_read (gpointer data)
805 {
806   GDBusWorker *worker = data;
807   g_mutex_lock (worker->read_lock);
808   _g_dbus_worker_do_read_unlocked (worker);
809   g_mutex_unlock (worker->read_lock);
810   return FALSE;
811 }
812
813 /* ---------------------------------------------------------------------------------------------------- */
814
815 struct _MessageToWriteData
816 {
817   GDBusWorker  *worker;
818   GDBusMessage *message;
819   gchar        *blob;
820   gsize         blob_size;
821
822   gsize               total_written;
823   GSimpleAsyncResult *simple;
824
825 };
826
827 static void
828 message_to_write_data_free (MessageToWriteData *data)
829 {
830   _g_dbus_worker_unref (data->worker);
831   if (data->message)
832     g_object_unref (data->message);
833   g_free (data->blob);
834   g_free (data);
835 }
836
837 /* ---------------------------------------------------------------------------------------------------- */
838
839 static void write_message_continue_writing (MessageToWriteData *data);
840
841 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
842 static void
843 write_message_async_cb (GObject      *source_object,
844                         GAsyncResult *res,
845                         gpointer      user_data)
846 {
847   MessageToWriteData *data = user_data;
848   GSimpleAsyncResult *simple;
849   gssize bytes_written;
850   GError *error;
851
852   /* Note: we can't access data->simple after calling g_async_result_complete () because the
853    * callback can free @data and we're not completing in idle. So use a copy of the pointer.
854    */
855   simple = data->simple;
856
857   error = NULL;
858   bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
859                                                 res,
860                                                 &error);
861   if (bytes_written == -1)
862     {
863       g_simple_async_result_take_error (simple, error);
864       g_simple_async_result_complete (simple);
865       g_object_unref (simple);
866       goto out;
867     }
868   g_assert (bytes_written > 0); /* zero is never returned */
869
870   write_message_print_transport_debug (bytes_written, data);
871
872   data->total_written += bytes_written;
873   g_assert (data->total_written <= data->blob_size);
874   if (data->total_written == data->blob_size)
875     {
876       g_simple_async_result_complete (simple);
877       g_object_unref (simple);
878       goto out;
879     }
880
881   write_message_continue_writing (data);
882
883  out:
884   ;
885 }
886
887 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
888 static gboolean
889 on_socket_ready (GSocket      *socket,
890                  GIOCondition  condition,
891                  gpointer      user_data)
892 {
893   MessageToWriteData *data = user_data;
894   write_message_continue_writing (data);
895   return FALSE; /* remove source */
896 }
897
898 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
899 static void
900 write_message_continue_writing (MessageToWriteData *data)
901 {
902   GOutputStream *ostream;
903   GSimpleAsyncResult *simple;
904 #ifdef G_OS_UNIX
905   GUnixFDList *fd_list;
906 #endif
907
908   /* Note: we can't access data->simple after calling g_async_result_complete () because the
909    * callback can free @data and we're not completing in idle. So use a copy of the pointer.
910    */
911   simple = data->simple;
912
913   ostream = g_io_stream_get_output_stream (data->worker->stream);
914 #ifdef G_OS_UNIX
915   fd_list = g_dbus_message_get_unix_fd_list (data->message);
916 #endif
917
918   g_assert (!g_output_stream_has_pending (ostream));
919   g_assert_cmpint (data->total_written, <, data->blob_size);
920
921   if (FALSE)
922     {
923     }
924 #ifdef G_OS_UNIX
925   else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
926     {
927       GOutputVector vector;
928       GSocketControlMessage *control_message;
929       gssize bytes_written;
930       GError *error;
931
932       vector.buffer = data->blob;
933       vector.size = data->blob_size;
934
935       control_message = NULL;
936       if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
937         {
938           if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
939             {
940               g_simple_async_result_set_error (simple,
941                                                G_IO_ERROR,
942                                                G_IO_ERROR_FAILED,
943                                                "Tried sending a file descriptor but remote peer does not support this capability");
944               g_simple_async_result_complete (simple);
945               g_object_unref (simple);
946               goto out;
947             }
948           control_message = g_unix_fd_message_new_with_fd_list (fd_list);
949         }
950
951       error = NULL;
952       bytes_written = g_socket_send_message (data->worker->socket,
953                                              NULL, /* address */
954                                              &vector,
955                                              1,
956                                              control_message != NULL ? &control_message : NULL,
957                                              control_message != NULL ? 1 : 0,
958                                              G_SOCKET_MSG_NONE,
959                                              data->worker->cancellable,
960                                              &error);
961       if (control_message != NULL)
962         g_object_unref (control_message);
963
964       if (bytes_written == -1)
965         {
966           /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
967           if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
968             {
969               GSource *source;
970               source = g_socket_create_source (data->worker->socket,
971                                                G_IO_OUT | G_IO_HUP | G_IO_ERR,
972                                                data->worker->cancellable);
973               g_source_set_callback (source,
974                                      (GSourceFunc) on_socket_ready,
975                                      data,
976                                      NULL); /* GDestroyNotify */
977               g_source_attach (source, g_main_context_get_thread_default ());
978               g_source_unref (source);
979               g_error_free (error);
980               goto out;
981             }
982           g_simple_async_result_take_error (simple, error);
983           g_simple_async_result_complete (simple);
984           g_object_unref (simple);
985           goto out;
986         }
987       g_assert (bytes_written > 0); /* zero is never returned */
988
989       write_message_print_transport_debug (bytes_written, data);
990
991       data->total_written += bytes_written;
992       g_assert (data->total_written <= data->blob_size);
993       if (data->total_written == data->blob_size)
994         {
995           g_simple_async_result_complete (simple);
996           g_object_unref (simple);
997           goto out;
998         }
999
1000       write_message_continue_writing (data);
1001     }
1002 #endif
1003   else
1004     {
1005 #ifdef G_OS_UNIX
1006       if (fd_list != NULL)
1007         {
1008           g_simple_async_result_set_error (simple,
1009                                            G_IO_ERROR,
1010                                            G_IO_ERROR_FAILED,
1011                                            "Tried sending a file descriptor on unsupported stream of type %s",
1012                                            g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1013           g_simple_async_result_complete (simple);
1014           g_object_unref (simple);
1015           goto out;
1016         }
1017 #endif
1018
1019       g_output_stream_write_async (ostream,
1020                                    (const gchar *) data->blob + data->total_written,
1021                                    data->blob_size - data->total_written,
1022                                    G_PRIORITY_DEFAULT,
1023                                    data->worker->cancellable,
1024                                    write_message_async_cb,
1025                                    data);
1026     }
1027  out:
1028   ;
1029 }
1030
1031 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1032 static void
1033 write_message_async (GDBusWorker         *worker,
1034                      MessageToWriteData  *data,
1035                      GAsyncReadyCallback  callback,
1036                      gpointer             user_data)
1037 {
1038   data->simple = g_simple_async_result_new (NULL,
1039                                             callback,
1040                                             user_data,
1041                                             write_message_async);
1042   data->total_written = 0;
1043   write_message_continue_writing (data);
1044 }
1045
1046 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1047 static gboolean
1048 write_message_finish (GAsyncResult   *res,
1049                       GError        **error)
1050 {
1051   g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1052   if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1053     return FALSE;
1054   else
1055     return TRUE;
1056 }
1057 /* ---------------------------------------------------------------------------------------------------- */
1058
1059 static void maybe_write_next_message (GDBusWorker *worker);
1060
1061 typedef struct
1062 {
1063   GDBusWorker *worker;
1064   GList *flushers;
1065 } FlushAsyncData;
1066
1067 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1068 static void
1069 ostream_flush_cb (GObject      *source_object,
1070                   GAsyncResult *res,
1071                   gpointer      user_data)
1072 {
1073   FlushAsyncData *data = user_data;
1074   GError *error;
1075   GList *l;
1076
1077   error = NULL;
1078   g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1079                                 res,
1080                                 &error);
1081
1082   if (error == NULL)
1083     {
1084       if (G_UNLIKELY (_g_dbus_debug_transport ()))
1085         {
1086           _g_dbus_debug_print_lock ();
1087           g_print ("========================================================================\n"
1088                    "GDBus-debug:Transport:\n"
1089                    "  ---- FLUSHED stream of type %s\n",
1090                    g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1091           _g_dbus_debug_print_unlock ();
1092         }
1093     }
1094
1095   g_assert (data->flushers != NULL);
1096   for (l = data->flushers; l != NULL; l = l->next)
1097     {
1098       FlushData *f = l->data;
1099
1100       f->error = error != NULL ? g_error_copy (error) : NULL;
1101
1102       g_mutex_lock (f->mutex);
1103       g_cond_signal (f->cond);
1104       g_mutex_unlock (f->mutex);
1105     }
1106   g_list_free (data->flushers);
1107
1108   if (error != NULL)
1109     g_error_free (error);
1110
1111   /* Make sure we tell folks that we don't have additional
1112      flushes pending */
1113   g_mutex_lock (data->worker->write_lock);
1114   g_assert (data->worker->output_pending);
1115   data->worker->output_pending = FALSE;
1116   g_mutex_unlock (data->worker->write_lock);
1117
1118   /* OK, cool, finally kick off the next write */
1119   maybe_write_next_message (data->worker);
1120
1121   _g_dbus_worker_unref (data->worker);
1122   g_free (data);
1123 }
1124
1125 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1126 static void
1127 message_written (GDBusWorker *worker,
1128                  MessageToWriteData *message_data)
1129 {
1130   GList *l;
1131   GList *ll;
1132   GList *flushers;
1133
1134   /* first log the fact that we wrote a message */
1135   if (G_UNLIKELY (_g_dbus_debug_message ()))
1136     {
1137       gchar *s;
1138       _g_dbus_debug_print_lock ();
1139       g_print ("========================================================================\n"
1140                "GDBus-debug:Message:\n"
1141                "  >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1142                message_data->blob_size);
1143       s = g_dbus_message_print (message_data->message, 2);
1144       g_print ("%s", s);
1145       g_free (s);
1146       if (G_UNLIKELY (_g_dbus_debug_payload ()))
1147         {
1148           s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1149           g_print ("%s\n", s);
1150           g_free (s);
1151         }
1152       _g_dbus_debug_print_unlock ();
1153     }
1154
1155   /* then first wake up pending flushes and, if needed, flush the stream */
1156   flushers = NULL;
1157   g_mutex_lock (worker->write_lock);
1158   worker->write_num_messages_written += 1;
1159   for (l = worker->write_pending_flushes; l != NULL; l = ll)
1160     {
1161       FlushData *f = l->data;
1162       ll = l->next;
1163
1164       if (f->number_to_wait_for == worker->write_num_messages_written)
1165         {
1166           flushers = g_list_append (flushers, f);
1167           worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1168         }
1169     }
1170   if (flushers != NULL)
1171     {
1172       g_assert (!worker->output_pending);
1173       worker->output_pending = TRUE;
1174     }
1175   g_mutex_unlock (worker->write_lock);
1176
1177   if (flushers != NULL)
1178     {
1179       FlushAsyncData *data;
1180       data = g_new0 (FlushAsyncData, 1);
1181       data->worker = _g_dbus_worker_ref (worker);
1182       data->flushers = flushers;
1183       /* flush the stream before writing the next message */
1184       g_output_stream_flush_async (g_io_stream_get_output_stream (worker->stream),
1185                                    G_PRIORITY_DEFAULT,
1186                                    worker->cancellable,
1187                                    ostream_flush_cb,
1188                                    data);
1189     }
1190   else
1191     {
1192       /* kick off the next write! */
1193       maybe_write_next_message (worker);
1194     }
1195 }
1196
1197 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1198 static void
1199 write_message_cb (GObject       *source_object,
1200                   GAsyncResult  *res,
1201                   gpointer       user_data)
1202 {
1203   MessageToWriteData *data = user_data;
1204   GError *error;
1205
1206   g_mutex_lock (data->worker->write_lock);
1207   g_assert (data->worker->output_pending);
1208   data->worker->output_pending = FALSE;
1209   g_mutex_unlock (data->worker->write_lock);
1210
1211   error = NULL;
1212   if (!write_message_finish (res, &error))
1213     {
1214       /* TODO: handle */
1215       _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1216       g_error_free (error);
1217     }
1218
1219   /* this function will also kick of the next write (it might need to
1220    * flush so writing the next message might happen much later
1221    * e.g. async)
1222    */
1223   message_written (data->worker, data);
1224
1225   message_to_write_data_free (data);
1226 }
1227
1228 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1229 static void
1230 maybe_write_next_message (GDBusWorker *worker)
1231 {
1232   MessageToWriteData *data;
1233
1234  write_next:
1235   /* we mustn't try to write two things at once */
1236   g_assert (!worker->output_pending);
1237
1238   g_mutex_lock (worker->write_lock);
1239   data = g_queue_pop_head (worker->write_queue);
1240   if (data != NULL)
1241     worker->output_pending = TRUE;
1242   g_mutex_unlock (worker->write_lock);
1243
1244   /* Note that write_lock is only used for protecting the @write_queue
1245    * and @output_pending fields of the GDBusWorker struct ... which we
1246    * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1247    *
1248    * Therefore, it's fine to drop it here when calling back into user
1249    * code and then writing the message out onto the GIOStream since this
1250    * function only runs on the worker thread.
1251    */
1252   if (data != NULL)
1253     {
1254       GDBusMessage *old_message;
1255       guchar *new_blob;
1256       gsize new_blob_size;
1257       GError *error;
1258
1259       old_message = data->message;
1260       data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1261       if (data->message == old_message)
1262         {
1263           /* filters had no effect - do nothing */
1264         }
1265       else if (data->message == NULL)
1266         {
1267           /* filters dropped message */
1268           g_mutex_lock (worker->write_lock);
1269           worker->output_pending = FALSE;
1270           g_mutex_unlock (worker->write_lock);
1271           message_to_write_data_free (data);
1272           goto write_next;
1273         }
1274       else
1275         {
1276           /* filters altered the message -> reencode */
1277           error = NULL;
1278           new_blob = g_dbus_message_to_blob (data->message,
1279                                              &new_blob_size,
1280                                              worker->capabilities,
1281                                              &error);
1282           if (new_blob == NULL)
1283             {
1284               /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1285                * the old message instead
1286                */
1287               g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1288                          g_dbus_message_get_serial (data->message),
1289                          error->message);
1290               g_error_free (error);
1291             }
1292           else
1293             {
1294               g_free (data->blob);
1295               data->blob = (gchar *) new_blob;
1296               data->blob_size = new_blob_size;
1297             }
1298         }
1299
1300       write_message_async (worker,
1301                            data,
1302                            write_message_cb,
1303                            data);
1304     }
1305 }
1306
1307 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1308 static gboolean
1309 write_message_in_idle_cb (gpointer user_data)
1310 {
1311   GDBusWorker *worker = user_data;
1312
1313   /* Because this is the worker thread, we can read this struct member
1314    * without holding the lock: no other thread ever modifies it.
1315    */
1316   if (!worker->output_pending)
1317     maybe_write_next_message (worker);
1318
1319   return FALSE;
1320 }
1321
1322 /* ---------------------------------------------------------------------------------------------------- */
1323
1324 /* can be called from any thread - steals blob */
1325 void
1326 _g_dbus_worker_send_message (GDBusWorker    *worker,
1327                              GDBusMessage   *message,
1328                              gchar          *blob,
1329                              gsize           blob_len)
1330 {
1331   MessageToWriteData *data;
1332
1333   g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1334   g_return_if_fail (blob != NULL);
1335   g_return_if_fail (blob_len > 16);
1336
1337   data = g_new0 (MessageToWriteData, 1);
1338   data->worker = _g_dbus_worker_ref (worker);
1339   data->message = g_object_ref (message);
1340   data->blob = blob; /* steal! */
1341   data->blob_size = blob_len;
1342
1343   g_mutex_lock (worker->write_lock);
1344   g_queue_push_tail (worker->write_queue, data);
1345   if (!worker->output_pending)
1346     {
1347       GSource *idle_source;
1348       idle_source = g_idle_source_new ();
1349       g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1350       g_source_set_callback (idle_source,
1351                              write_message_in_idle_cb,
1352                              _g_dbus_worker_ref (worker),
1353                              (GDestroyNotify) _g_dbus_worker_unref);
1354       g_source_attach (idle_source, worker->shared_thread_data->context);
1355       g_source_unref (idle_source);
1356     }
1357   g_mutex_unlock (worker->write_lock);
1358 }
1359
1360 /* ---------------------------------------------------------------------------------------------------- */
1361
1362 GDBusWorker *
1363 _g_dbus_worker_new (GIOStream                              *stream,
1364                     GDBusCapabilityFlags                    capabilities,
1365                     gboolean                                initially_frozen,
1366                     GDBusWorkerMessageReceivedCallback      message_received_callback,
1367                     GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1368                     GDBusWorkerDisconnectedCallback         disconnected_callback,
1369                     gpointer                                user_data)
1370 {
1371   GDBusWorker *worker;
1372   GSource *idle_source;
1373
1374   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1375   g_return_val_if_fail (message_received_callback != NULL, NULL);
1376   g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1377   g_return_val_if_fail (disconnected_callback != NULL, NULL);
1378
1379   worker = g_new0 (GDBusWorker, 1);
1380   worker->ref_count = 1;
1381
1382   worker->read_lock = g_mutex_new ();
1383   worker->message_received_callback = message_received_callback;
1384   worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1385   worker->disconnected_callback = disconnected_callback;
1386   worker->user_data = user_data;
1387   worker->stream = g_object_ref (stream);
1388   worker->capabilities = capabilities;
1389   worker->cancellable = g_cancellable_new ();
1390   worker->output_pending = FALSE;
1391
1392   worker->frozen = initially_frozen;
1393   worker->received_messages_while_frozen = g_queue_new ();
1394
1395   worker->write_lock = g_mutex_new ();
1396   worker->write_queue = g_queue_new ();
1397
1398   if (G_IS_SOCKET_CONNECTION (worker->stream))
1399     worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1400
1401   worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1402
1403   /* begin reading */
1404   idle_source = g_idle_source_new ();
1405   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1406   g_source_set_callback (idle_source,
1407                          _g_dbus_worker_do_initial_read,
1408                          worker,
1409                          NULL);
1410   g_source_attach (idle_source, worker->shared_thread_data->context);
1411   g_source_unref (idle_source);
1412
1413   return worker;
1414 }
1415
1416 /* ---------------------------------------------------------------------------------------------------- */
1417
1418 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
1419 static gboolean
1420 unref_in_idle_cb (gpointer user_data)
1421 {
1422   GDBusWorker *worker = user_data;
1423   _g_dbus_worker_unref (worker);
1424   return FALSE;
1425 }
1426
1427 /* This can be called from any thread - frees worker. Note that
1428  * callbacks might still happen if called from another thread than the
1429  * worker - use your own synchronization primitive in the callbacks.
1430  */
1431 void
1432 _g_dbus_worker_stop (GDBusWorker *worker)
1433 {
1434   GSource *idle_source;
1435
1436   worker->stopped = TRUE;
1437   g_cancellable_cancel (worker->cancellable);
1438
1439   idle_source = g_idle_source_new ();
1440   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1441   g_source_set_callback (idle_source,
1442                          unref_in_idle_cb,
1443                          _g_dbus_worker_ref (worker),
1444                          (GDestroyNotify) _g_dbus_worker_unref);
1445   g_source_attach (idle_source, worker->shared_thread_data->context);
1446   g_source_unref (idle_source);
1447 }
1448
1449 /* ---------------------------------------------------------------------------------------------------- */
1450
1451 /* can be called from any thread (except the worker thread) - blocks
1452  * calling thread until all queued outgoing messages are written and
1453  * the transport has been flushed
1454  */
1455 gboolean
1456 _g_dbus_worker_flush_sync (GDBusWorker    *worker,
1457                            GCancellable   *cancellable,
1458                            GError        **error)
1459 {
1460   gboolean ret;
1461   FlushData *data;
1462
1463   data = NULL;
1464   ret = TRUE;
1465
1466   /* if the queue is empty, there's nothing to wait for */
1467   g_mutex_lock (worker->write_lock);
1468   if (g_queue_get_length (worker->write_queue) > 0)
1469     {
1470       data = g_new0 (FlushData, 1);
1471       data->mutex = g_mutex_new ();
1472       data->cond = g_cond_new ();
1473       data->number_to_wait_for = worker->write_num_messages_written + g_queue_get_length (worker->write_queue);
1474       g_mutex_lock (data->mutex);
1475       worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, data);
1476     }
1477   g_mutex_unlock (worker->write_lock);
1478
1479   if (data != NULL)
1480     {
1481       g_cond_wait (data->cond, data->mutex);
1482       g_mutex_unlock (data->mutex);
1483
1484       /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1485       g_cond_free (data->cond);
1486       g_mutex_free (data->mutex);
1487       if (data->error != NULL)
1488         {
1489           ret = FALSE;
1490           g_propagate_error (error, data->error);
1491         }
1492       g_free (data);
1493     }
1494
1495   return ret;
1496 }
1497
1498 /* ---------------------------------------------------------------------------------------------------- */
1499
1500 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1501 #define G_DBUS_DEBUG_TRANSPORT      (1<<1)
1502 #define G_DBUS_DEBUG_MESSAGE        (1<<2)
1503 #define G_DBUS_DEBUG_PAYLOAD        (1<<3)
1504 #define G_DBUS_DEBUG_CALL           (1<<4)
1505 #define G_DBUS_DEBUG_SIGNAL         (1<<5)
1506 #define G_DBUS_DEBUG_INCOMING       (1<<6)
1507 #define G_DBUS_DEBUG_RETURN         (1<<7)
1508 #define G_DBUS_DEBUG_EMISSION       (1<<8)
1509 #define G_DBUS_DEBUG_ADDRESS        (1<<9)
1510
1511 static gint _gdbus_debug_flags = 0;
1512
1513 gboolean
1514 _g_dbus_debug_authentication (void)
1515 {
1516   _g_dbus_initialize ();
1517   return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1518 }
1519
1520 gboolean
1521 _g_dbus_debug_transport (void)
1522 {
1523   _g_dbus_initialize ();
1524   return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1525 }
1526
1527 gboolean
1528 _g_dbus_debug_message (void)
1529 {
1530   _g_dbus_initialize ();
1531   return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1532 }
1533
1534 gboolean
1535 _g_dbus_debug_payload (void)
1536 {
1537   _g_dbus_initialize ();
1538   return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1539 }
1540
1541 gboolean
1542 _g_dbus_debug_call (void)
1543 {
1544   _g_dbus_initialize ();
1545   return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1546 }
1547
1548 gboolean
1549 _g_dbus_debug_signal (void)
1550 {
1551   _g_dbus_initialize ();
1552   return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1553 }
1554
1555 gboolean
1556 _g_dbus_debug_incoming (void)
1557 {
1558   _g_dbus_initialize ();
1559   return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1560 }
1561
1562 gboolean
1563 _g_dbus_debug_return (void)
1564 {
1565   _g_dbus_initialize ();
1566   return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1567 }
1568
1569 gboolean
1570 _g_dbus_debug_emission (void)
1571 {
1572   _g_dbus_initialize ();
1573   return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1574 }
1575
1576 gboolean
1577 _g_dbus_debug_address (void)
1578 {
1579   _g_dbus_initialize ();
1580   return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1581 }
1582
1583 G_LOCK_DEFINE_STATIC (print_lock);
1584
1585 void
1586 _g_dbus_debug_print_lock (void)
1587 {
1588   G_LOCK (print_lock);
1589 }
1590
1591 void
1592 _g_dbus_debug_print_unlock (void)
1593 {
1594   G_UNLOCK (print_lock);
1595 }
1596
1597 /*
1598  * _g_dbus_initialize:
1599  *
1600  * Does various one-time init things such as
1601  *
1602  *  - registering the G_DBUS_ERROR error domain
1603  *  - parses the G_DBUS_DEBUG environment variable
1604  */
1605 void
1606 _g_dbus_initialize (void)
1607 {
1608   static volatile gsize initialized = 0;
1609
1610   if (g_once_init_enter (&initialized))
1611     {
1612       volatile GQuark g_dbus_error_domain;
1613       const gchar *debug;
1614
1615       g_dbus_error_domain = G_DBUS_ERROR;
1616       (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1617
1618       debug = g_getenv ("G_DBUS_DEBUG");
1619       if (debug != NULL)
1620         {
1621           const GDebugKey keys[] = {
1622             { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1623             { "transport",      G_DBUS_DEBUG_TRANSPORT      },
1624             { "message",        G_DBUS_DEBUG_MESSAGE        },
1625             { "payload",        G_DBUS_DEBUG_PAYLOAD        },
1626             { "call",           G_DBUS_DEBUG_CALL           },
1627             { "signal",         G_DBUS_DEBUG_SIGNAL         },
1628             { "incoming",       G_DBUS_DEBUG_INCOMING       },
1629             { "return",         G_DBUS_DEBUG_RETURN         },
1630             { "emission",       G_DBUS_DEBUG_EMISSION       },
1631             { "address",        G_DBUS_DEBUG_ADDRESS        }
1632           };
1633
1634           _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1635           if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1636             _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1637         }
1638
1639       g_once_init_leave (&initialized, 1);
1640     }
1641 }
1642
1643 /* ---------------------------------------------------------------------------------------------------- */
1644
1645 GVariantType *
1646 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1647 {
1648   const GVariantType *arg_types[256];
1649   guint n;
1650
1651   if (args)
1652     for (n = 0; args[n] != NULL; n++)
1653       {
1654         /* DBus places a hard limit of 255 on signature length.
1655          * therefore number of args must be less than 256.
1656          */
1657         g_assert (n < 256);
1658
1659         arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1660
1661         if G_UNLIKELY (arg_types[n] == NULL)
1662           return NULL;
1663       }
1664   else
1665     n = 0;
1666
1667   return g_variant_type_new_tuple (arg_types, n);
1668 }
1669
1670 /* ---------------------------------------------------------------------------------------------------- */
1671
1672 #ifdef G_OS_WIN32
1673
1674 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1675
1676 gchar *
1677 _g_dbus_win32_get_user_sid (void)
1678 {
1679   HANDLE h;
1680   TOKEN_USER *user;
1681   DWORD token_information_len;
1682   PSID psid;
1683   gchar *sid;
1684   gchar *ret;
1685
1686   ret = NULL;
1687   user = NULL;
1688   h = INVALID_HANDLE_VALUE;
1689
1690   if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
1691     {
1692       g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
1693       goto out;
1694     }
1695
1696   /* Get length of buffer */
1697   token_information_len = 0;
1698   if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
1699     {
1700       if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1701         {
1702           g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1703           goto out;
1704         }
1705     }
1706   user = g_malloc (token_information_len);
1707   if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
1708     {
1709       g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1710       goto out;
1711     }
1712
1713   psid = user->User.Sid;
1714   if (!IsValidSid (psid))
1715     {
1716       g_warning ("Invalid SID");
1717       goto out;
1718     }
1719
1720   if (!ConvertSidToStringSidA (psid, &sid))
1721     {
1722       g_warning ("Invalid SID");
1723       goto out;
1724     }
1725
1726   ret = g_strdup (sid);
1727   LocalFree (sid);
1728
1729 out:
1730   g_free (user);
1731   if (h != INVALID_HANDLE_VALUE)
1732     CloseHandle (h);
1733   return ret;
1734 }
1735 #endif
1736
1737 /* ---------------------------------------------------------------------------------------------------- */
1738
1739 gchar *
1740 _g_dbus_get_machine_id (GError **error)
1741 {
1742   gchar *ret;
1743   /* TODO: use PACKAGE_LOCALSTATEDIR ? */
1744   ret = NULL;
1745   if (!g_file_get_contents ("/var/lib/dbus/machine-id",
1746                             &ret,
1747                             NULL,
1748                             error))
1749     {
1750       g_prefix_error (error, _("Unable to load /var/lib/dbus/machine-id: "));
1751     }
1752   else
1753     {
1754       /* TODO: validate value */
1755       g_strstrip (ret);
1756     }
1757   return ret;
1758 }
1759
1760 /* ---------------------------------------------------------------------------------------------------- */
1761
1762 gchar *
1763 _g_dbus_enum_to_string (GType enum_type, gint value)
1764 {
1765   gchar *ret;
1766   GEnumClass *klass;
1767   GEnumValue *enum_value;
1768
1769   klass = g_type_class_ref (enum_type);
1770   enum_value = g_enum_get_value (klass, value);
1771   if (enum_value != NULL)
1772     ret = g_strdup (enum_value->value_nick);
1773   else
1774     ret = g_strdup_printf ("unknown (value %d)", value);
1775   g_type_class_unref (klass);
1776   return ret;
1777 }
1778
1779 /* ---------------------------------------------------------------------------------------------------- */
1780
1781 static void
1782 write_message_print_transport_debug (gssize bytes_written,
1783                                      MessageToWriteData *data)
1784 {
1785   if (G_LIKELY (!_g_dbus_debug_transport ()))
1786     goto out;
1787
1788   _g_dbus_debug_print_lock ();
1789   g_print ("========================================================================\n"
1790            "GDBus-debug:Transport:\n"
1791            "  >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1792            "       size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
1793            bytes_written,
1794            g_dbus_message_get_serial (data->message),
1795            data->blob_size,
1796            data->total_written,
1797            g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1798   _g_dbus_debug_print_unlock ();
1799  out:
1800   ;
1801 }
1802
1803 /* ---------------------------------------------------------------------------------------------------- */
1804
1805 static void
1806 read_message_print_transport_debug (gssize bytes_read,
1807                                     GDBusWorker *worker)
1808 {
1809   gsize size;
1810   gint32 serial;
1811   gint32 message_length;
1812
1813   if (G_LIKELY (!_g_dbus_debug_transport ()))
1814     goto out;
1815
1816   size = bytes_read + worker->read_buffer_cur_size;
1817   serial = 0;
1818   message_length = 0;
1819   if (size >= 16)
1820     message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
1821   if (size >= 1)
1822     {
1823       switch (worker->read_buffer[0])
1824         {
1825         case 'l':
1826           if (size >= 12)
1827             serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
1828           break;
1829         case 'B':
1830           if (size >= 12)
1831             serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
1832           break;
1833         default:
1834           /* an error will be set elsewhere if this happens */
1835           goto out;
1836         }
1837     }
1838
1839     _g_dbus_debug_print_lock ();
1840   g_print ("========================================================================\n"
1841            "GDBus-debug:Transport:\n"
1842            "  <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1843            "       size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
1844            bytes_read,
1845            serial,
1846            message_length,
1847            worker->read_buffer_cur_size,
1848            g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
1849   _g_dbus_debug_print_unlock ();
1850  out:
1851   ;
1852 }
1853
1854 /* ---------------------------------------------------------------------------------------------------- */
1855
1856 gboolean
1857 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
1858                                      GValue                *return_accu,
1859                                      const GValue          *handler_return,
1860                                      gpointer               dummy)
1861 {
1862   gboolean continue_emission;
1863   gboolean signal_return;
1864
1865   signal_return = g_value_get_boolean (handler_return);
1866   g_value_set_boolean (return_accu, signal_return);
1867   continue_emission = signal_return;
1868
1869   return continue_emission;
1870 }