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