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