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