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