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