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