GDBusMessage: Don't reset serial number when copying
[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       GDBusMessage *old_message;
1248       guchar *new_blob;
1249       gsize new_blob_size;
1250       GError *error;
1251
1252       old_message = data->message;
1253       data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1254       if (data->message == old_message)
1255         {
1256           /* filters had no effect - do nothing */
1257         }
1258       else if (data->message == NULL)
1259         {
1260           /* filters dropped message */
1261           g_mutex_lock (worker->write_lock);
1262           worker->num_writes_pending -= 1;
1263           g_mutex_unlock (worker->write_lock);
1264           message_to_write_data_free (data);
1265           goto write_next;
1266         }
1267       else
1268         {
1269           /* filters altered the message -> reencode */
1270           error = NULL;
1271           new_blob = g_dbus_message_to_blob (data->message,
1272                                              &new_blob_size,
1273                                              worker->capabilities,
1274                                              &error);
1275           if (new_blob == NULL)
1276             {
1277               /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1278                * the old message instead
1279                */
1280               g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1281                          g_dbus_message_get_serial (data->message),
1282                          error->message);
1283               g_error_free (error);
1284             }
1285           else
1286             {
1287               g_free (data->blob);
1288               data->blob = (gchar *) new_blob;
1289               data->blob_size = new_blob_size;
1290             }
1291         }
1292
1293       write_message_async (worker,
1294                            data,
1295                            write_message_cb,
1296                            data);
1297     }
1298 }
1299
1300 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1301 static gboolean
1302 write_message_in_idle_cb (gpointer user_data)
1303 {
1304   GDBusWorker *worker = user_data;
1305   if (worker->num_writes_pending == 0)
1306     maybe_write_next_message (worker);
1307   return FALSE;
1308 }
1309
1310 /* ---------------------------------------------------------------------------------------------------- */
1311
1312 /* can be called from any thread - steals blob */
1313 void
1314 _g_dbus_worker_send_message (GDBusWorker    *worker,
1315                              GDBusMessage   *message,
1316                              gchar          *blob,
1317                              gsize           blob_len)
1318 {
1319   MessageToWriteData *data;
1320
1321   g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1322   g_return_if_fail (blob != NULL);
1323   g_return_if_fail (blob_len > 16);
1324
1325   data = g_new0 (MessageToWriteData, 1);
1326   data->worker = _g_dbus_worker_ref (worker);
1327   data->message = g_object_ref (message);
1328   data->blob = blob; /* steal! */
1329   data->blob_size = blob_len;
1330
1331   g_mutex_lock (worker->write_lock);
1332   g_queue_push_tail (worker->write_queue, data);
1333   if (worker->num_writes_pending == 0)
1334     {
1335       GSource *idle_source;
1336       idle_source = g_idle_source_new ();
1337       g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1338       g_source_set_callback (idle_source,
1339                              write_message_in_idle_cb,
1340                              _g_dbus_worker_ref (worker),
1341                              (GDestroyNotify) _g_dbus_worker_unref);
1342       g_source_attach (idle_source, shared_thread_data->context);
1343       g_source_unref (idle_source);
1344     }
1345   g_mutex_unlock (worker->write_lock);
1346 }
1347
1348 /* ---------------------------------------------------------------------------------------------------- */
1349
1350 static void
1351 _g_dbus_worker_thread_begin_func (gpointer user_data)
1352 {
1353   GDBusWorker *worker = user_data;
1354
1355   worker->thread = g_thread_self ();
1356
1357   /* begin reading */
1358   _g_dbus_worker_do_read (worker);
1359 }
1360
1361 GDBusWorker *
1362 _g_dbus_worker_new (GIOStream                              *stream,
1363                     GDBusCapabilityFlags                    capabilities,
1364                     gboolean                                initially_frozen,
1365                     GDBusWorkerMessageReceivedCallback      message_received_callback,
1366                     GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1367                     GDBusWorkerDisconnectedCallback         disconnected_callback,
1368                     gpointer                                user_data)
1369 {
1370   GDBusWorker *worker;
1371
1372   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1373   g_return_val_if_fail (message_received_callback != NULL, NULL);
1374   g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1375   g_return_val_if_fail (disconnected_callback != NULL, NULL);
1376
1377   worker = g_new0 (GDBusWorker, 1);
1378   worker->ref_count = 1;
1379
1380   worker->read_lock = g_mutex_new ();
1381   worker->message_received_callback = message_received_callback;
1382   worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1383   worker->disconnected_callback = disconnected_callback;
1384   worker->user_data = user_data;
1385   worker->stream = g_object_ref (stream);
1386   worker->capabilities = capabilities;
1387   worker->cancellable = g_cancellable_new ();
1388
1389   worker->frozen = initially_frozen;
1390   worker->received_messages_while_frozen = g_queue_new ();
1391
1392   worker->write_lock = g_mutex_new ();
1393   worker->write_queue = g_queue_new ();
1394
1395   if (G_IS_SOCKET_CONNECTION (worker->stream))
1396     worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1397
1398   _g_dbus_shared_thread_ref (_g_dbus_worker_thread_begin_func, worker);
1399
1400   return worker;
1401 }
1402
1403 /* ---------------------------------------------------------------------------------------------------- */
1404
1405 /* This can be called from any thread - frees worker - guarantees no callbacks
1406  * will ever be issued again
1407  */
1408 void
1409 _g_dbus_worker_stop (GDBusWorker *worker)
1410 {
1411   /* If we're called in the worker thread it means we are called from
1412    * a worker callback. This is fine, we just can't lock in that case since
1413    * we're already holding the lock...
1414    */
1415   if (g_thread_self () != worker->thread)
1416     g_mutex_lock (worker->read_lock);
1417   worker->stopped = TRUE;
1418   if (g_thread_self () != worker->thread)
1419     g_mutex_unlock (worker->read_lock);
1420
1421   g_cancellable_cancel (worker->cancellable);
1422   _g_dbus_worker_unref (worker);
1423 }
1424
1425 /* ---------------------------------------------------------------------------------------------------- */
1426
1427 /* can be called from any thread (except the worker thread) - blocks
1428  * calling thread until all queued outgoing messages are written and
1429  * the transport has been flushed
1430  */
1431 gboolean
1432 _g_dbus_worker_flush_sync (GDBusWorker    *worker,
1433                            GCancellable   *cancellable,
1434                            GError        **error)
1435 {
1436   gboolean ret;
1437   FlushData *data;
1438
1439   data = NULL;
1440   ret = TRUE;
1441
1442   /* if the queue is empty, there's nothing to wait for */
1443   g_mutex_lock (worker->write_lock);
1444   if (g_queue_get_length (worker->write_queue) > 0)
1445     {
1446       data = g_new0 (FlushData, 1);
1447       data->mutex = g_mutex_new ();
1448       data->cond = g_cond_new ();
1449       data->number_to_wait_for = worker->write_num_messages_written + g_queue_get_length (worker->write_queue);
1450       g_mutex_lock (data->mutex);
1451       worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, data);
1452     }
1453   g_mutex_unlock (worker->write_lock);
1454
1455   if (data != NULL)
1456     {
1457       g_cond_wait (data->cond, data->mutex);
1458       g_mutex_unlock (data->mutex);
1459
1460       /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1461       g_cond_free (data->cond);
1462       g_mutex_free (data->mutex);
1463       if (data->error != NULL)
1464         {
1465           ret = FALSE;
1466           g_propagate_error (error, data->error);
1467         }
1468       g_free (data);
1469     }
1470
1471   return ret;
1472 }
1473
1474 /* ---------------------------------------------------------------------------------------------------- */
1475
1476 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1477 #define G_DBUS_DEBUG_TRANSPORT      (1<<1)
1478 #define G_DBUS_DEBUG_MESSAGE        (1<<2)
1479 #define G_DBUS_DEBUG_PAYLOAD        (1<<3)
1480 #define G_DBUS_DEBUG_CALL           (1<<4)
1481 #define G_DBUS_DEBUG_SIGNAL         (1<<5)
1482 #define G_DBUS_DEBUG_INCOMING       (1<<6)
1483 #define G_DBUS_DEBUG_RETURN         (1<<7)
1484 #define G_DBUS_DEBUG_EMISSION       (1<<8)
1485 #define G_DBUS_DEBUG_ADDRESS        (1<<9)
1486
1487 static gint _gdbus_debug_flags = 0;
1488
1489 gboolean
1490 _g_dbus_debug_authentication (void)
1491 {
1492   _g_dbus_initialize ();
1493   return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1494 }
1495
1496 gboolean
1497 _g_dbus_debug_transport (void)
1498 {
1499   _g_dbus_initialize ();
1500   return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1501 }
1502
1503 gboolean
1504 _g_dbus_debug_message (void)
1505 {
1506   _g_dbus_initialize ();
1507   return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1508 }
1509
1510 gboolean
1511 _g_dbus_debug_payload (void)
1512 {
1513   _g_dbus_initialize ();
1514   return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1515 }
1516
1517 gboolean
1518 _g_dbus_debug_call (void)
1519 {
1520   _g_dbus_initialize ();
1521   return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1522 }
1523
1524 gboolean
1525 _g_dbus_debug_signal (void)
1526 {
1527   _g_dbus_initialize ();
1528   return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1529 }
1530
1531 gboolean
1532 _g_dbus_debug_incoming (void)
1533 {
1534   _g_dbus_initialize ();
1535   return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1536 }
1537
1538 gboolean
1539 _g_dbus_debug_return (void)
1540 {
1541   _g_dbus_initialize ();
1542   return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1543 }
1544
1545 gboolean
1546 _g_dbus_debug_emission (void)
1547 {
1548   _g_dbus_initialize ();
1549   return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1550 }
1551
1552 gboolean
1553 _g_dbus_debug_address (void)
1554 {
1555   _g_dbus_initialize ();
1556   return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1557 }
1558
1559 G_LOCK_DEFINE_STATIC (print_lock);
1560
1561 void
1562 _g_dbus_debug_print_lock (void)
1563 {
1564   G_LOCK (print_lock);
1565 }
1566
1567 void
1568 _g_dbus_debug_print_unlock (void)
1569 {
1570   G_UNLOCK (print_lock);
1571 }
1572
1573 /*
1574  * _g_dbus_initialize:
1575  *
1576  * Does various one-time init things such as
1577  *
1578  *  - registering the G_DBUS_ERROR error domain
1579  *  - parses the G_DBUS_DEBUG environment variable
1580  */
1581 void
1582 _g_dbus_initialize (void)
1583 {
1584   static volatile gsize initialized = 0;
1585
1586   if (g_once_init_enter (&initialized))
1587     {
1588       volatile GQuark g_dbus_error_domain;
1589       const gchar *debug;
1590
1591       g_dbus_error_domain = G_DBUS_ERROR;
1592
1593       debug = g_getenv ("G_DBUS_DEBUG");
1594       if (debug != NULL)
1595         {
1596           const GDebugKey keys[] = {
1597             { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1598             { "transport",      G_DBUS_DEBUG_TRANSPORT      },
1599             { "message",        G_DBUS_DEBUG_MESSAGE        },
1600             { "payload",        G_DBUS_DEBUG_PAYLOAD        },
1601             { "call",           G_DBUS_DEBUG_CALL           },
1602             { "signal",         G_DBUS_DEBUG_SIGNAL         },
1603             { "incoming",       G_DBUS_DEBUG_INCOMING       },
1604             { "return",         G_DBUS_DEBUG_RETURN         },
1605             { "emission",       G_DBUS_DEBUG_EMISSION       },
1606             { "address",        G_DBUS_DEBUG_ADDRESS        }
1607           };
1608
1609           _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1610           if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1611             _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1612         }
1613
1614       g_once_init_leave (&initialized, 1);
1615     }
1616 }
1617
1618 /* ---------------------------------------------------------------------------------------------------- */
1619
1620 GVariantType *
1621 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1622 {
1623   const GVariantType *arg_types[256];
1624   guint n;
1625
1626   if (args)
1627     for (n = 0; args[n] != NULL; n++)
1628       {
1629         /* DBus places a hard limit of 255 on signature length.
1630          * therefore number of args must be less than 256.
1631          */
1632         g_assert (n < 256);
1633
1634         arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1635
1636         if G_UNLIKELY (arg_types[n] == NULL)
1637           return NULL;
1638       }
1639   else
1640     n = 0;
1641
1642   return g_variant_type_new_tuple (arg_types, n);
1643 }
1644
1645 /* ---------------------------------------------------------------------------------------------------- */
1646
1647 #ifdef G_OS_WIN32
1648
1649 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1650
1651 gchar *
1652 _g_dbus_win32_get_user_sid (void)
1653 {
1654   HANDLE h;
1655   TOKEN_USER *user;
1656   DWORD token_information_len;
1657   PSID psid;
1658   gchar *sid;
1659   gchar *ret;
1660
1661   ret = NULL;
1662   user = NULL;
1663   h = INVALID_HANDLE_VALUE;
1664
1665   if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
1666     {
1667       g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
1668       goto out;
1669     }
1670
1671   /* Get length of buffer */
1672   token_information_len = 0;
1673   if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
1674     {
1675       if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1676         {
1677           g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1678           goto out;
1679         }
1680     }
1681   user = g_malloc (token_information_len);
1682   if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
1683     {
1684       g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1685       goto out;
1686     }
1687
1688   psid = user->User.Sid;
1689   if (!IsValidSid (psid))
1690     {
1691       g_warning ("Invalid SID");
1692       goto out;
1693     }
1694
1695   if (!ConvertSidToStringSidA (psid, &sid))
1696     {
1697       g_warning ("Invalid SID");
1698       goto out;
1699     }
1700
1701   ret = g_strdup (sid);
1702   LocalFree (sid);
1703
1704 out:
1705   g_free (user);
1706   if (h != INVALID_HANDLE_VALUE)
1707     CloseHandle (h);
1708   return ret;
1709 }
1710 #endif
1711
1712 /* ---------------------------------------------------------------------------------------------------- */
1713
1714 gchar *
1715 _g_dbus_get_machine_id (GError **error)
1716 {
1717   gchar *ret;
1718   /* TODO: use PACKAGE_LOCALSTATEDIR ? */
1719   ret = NULL;
1720   if (!g_file_get_contents ("/var/lib/dbus/machine-id",
1721                             &ret,
1722                             NULL,
1723                             error))
1724     {
1725       g_prefix_error (error, _("Unable to load /var/lib/dbus/machine-id: "));
1726     }
1727   else
1728     {
1729       /* TODO: validate value */
1730       g_strstrip (ret);
1731     }
1732   return ret;
1733 }
1734
1735 /* ---------------------------------------------------------------------------------------------------- */
1736
1737 gchar *
1738 _g_dbus_enum_to_string (GType enum_type, gint value)
1739 {
1740   gchar *ret;
1741   GEnumClass *klass;
1742   GEnumValue *enum_value;
1743
1744   klass = g_type_class_ref (enum_type);
1745   enum_value = g_enum_get_value (klass, value);
1746   if (enum_value != NULL)
1747     ret = g_strdup (enum_value->value_nick);
1748   else
1749     ret = g_strdup_printf ("unknown (value %d)", value);
1750   g_type_class_unref (klass);
1751   return ret;
1752 }
1753
1754 /* ---------------------------------------------------------------------------------------------------- */
1755
1756 static void
1757 write_message_print_transport_debug (gssize bytes_written,
1758                                      MessageToWriteData *data)
1759 {
1760   if (G_LIKELY (!_g_dbus_debug_transport ()))
1761     goto out;
1762
1763   _g_dbus_debug_print_lock ();
1764   g_print ("========================================================================\n"
1765            "GDBus-debug:Transport:\n"
1766            "  >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1767            "       size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
1768            bytes_written,
1769            g_dbus_message_get_serial (data->message),
1770            data->blob_size,
1771            data->total_written,
1772            g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1773   _g_dbus_debug_print_unlock ();
1774  out:
1775   ;
1776 }
1777
1778 /* ---------------------------------------------------------------------------------------------------- */
1779
1780 static void
1781 read_message_print_transport_debug (gssize bytes_read,
1782                                     GDBusWorker *worker)
1783 {
1784   gsize size;
1785   gint32 serial;
1786   gint32 message_length;
1787
1788   if (G_LIKELY (!_g_dbus_debug_transport ()))
1789     goto out;
1790
1791   size = bytes_read + worker->read_buffer_cur_size;
1792   serial = 0;
1793   message_length = 0;
1794   if (size >= 16)
1795     message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
1796   if (size >= 1)
1797     {
1798       switch (worker->read_buffer[0])
1799         {
1800         case 'l':
1801           if (size >= 12)
1802             serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
1803           break;
1804         case 'B':
1805           if (size >= 12)
1806             serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
1807           break;
1808         default:
1809           /* an error will be set elsewhere if this happens */
1810           goto out;
1811         }
1812     }
1813
1814     _g_dbus_debug_print_lock ();
1815   g_print ("========================================================================\n"
1816            "GDBus-debug:Transport:\n"
1817            "  <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1818            "       size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
1819            bytes_read,
1820            serial,
1821            message_length,
1822            worker->read_buffer_cur_size,
1823            g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
1824   _g_dbus_debug_print_unlock ();
1825  out:
1826   ;
1827 }