5208ad993a547a19a4a8fbf957c5f807e994e8a6
[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 "giostream.h"
41 #include "gsocketcontrolmessage.h"
42 #include "gsocketconnection.h"
43
44 #ifdef G_OS_UNIX
45 #include "gunixfdmessage.h"
46 #include "gunixconnection.h"
47 #include "gunixcredentialsmessage.h"
48 #endif
49
50 #ifdef G_OS_WIN32
51 #include <windows.h>
52 #endif
53
54 #include "glibintl.h"
55 #include "gioalias.h"
56
57 /* ---------------------------------------------------------------------------------------------------- */
58
59 gchar *
60 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
61 {
62  guint n, m;
63  GString *ret;
64
65  ret = g_string_new (NULL);
66
67  for (n = 0; n < len; n += 16)
68    {
69      g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
70
71      for (m = n; m < n + 16; m++)
72        {
73          if (m > n && (m%4) == 0)
74            g_string_append_c (ret, ' ');
75          if (m < len)
76            g_string_append_printf (ret, "%02x ", (guchar) data[m]);
77          else
78            g_string_append (ret, "   ");
79        }
80
81      g_string_append (ret, "   ");
82
83      for (m = n; m < len && m < n + 16; m++)
84        g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
85
86      g_string_append_c (ret, '\n');
87    }
88
89  return g_string_free (ret, FALSE);
90 }
91
92 /* ---------------------------------------------------------------------------------------------------- */
93
94 /* Unfortunately ancillary messages are discarded when reading from a
95  * socket using the GSocketInputStream abstraction. So we provide a
96  * very GInputStream-ish API that uses GSocket in this case (very
97  * similar to GSocketInputStream).
98  */
99
100 typedef struct
101 {
102   GSocket *socket;
103   GCancellable *cancellable;
104
105   void *buffer;
106   gsize count;
107
108   GSocketControlMessage ***messages;
109   gint *num_messages;
110
111   GSimpleAsyncResult *simple;
112
113   gboolean from_mainloop;
114 } ReadWithControlData;
115
116 static void
117 read_with_control_data_free (ReadWithControlData *data)
118 {
119   g_object_unref (data->socket);
120   if (data->cancellable != NULL)
121     g_object_unref (data->cancellable);
122   g_free (data);
123 }
124
125 static gboolean
126 _g_socket_read_with_control_messages_ready (GSocket      *socket,
127                                             GIOCondition  condition,
128                                             gpointer      user_data)
129 {
130   ReadWithControlData *data = user_data;
131   GError *error;
132   gssize result;
133   GInputVector vector;
134
135   error = NULL;
136   vector.buffer = data->buffer;
137   vector.size = data->count;
138   result = g_socket_receive_message (data->socket,
139                                      NULL, /* address */
140                                      &vector,
141                                      1,
142                                      data->messages,
143                                      data->num_messages,
144                                      NULL,
145                                      data->cancellable,
146                                      &error);
147   if (result >= 0)
148     {
149       g_simple_async_result_set_op_res_gssize (data->simple, result);
150     }
151   else
152     {
153       g_assert (error != NULL);
154       g_simple_async_result_set_from_error (data->simple, error);
155       g_error_free (error);
156     }
157
158   if (data->from_mainloop)
159     g_simple_async_result_complete (data->simple);
160   else
161     g_simple_async_result_complete_in_idle (data->simple);
162
163   return FALSE;
164 }
165
166 static void
167 _g_socket_read_with_control_messages (GSocket                 *socket,
168                                       void                    *buffer,
169                                       gsize                    count,
170                                       GSocketControlMessage ***messages,
171                                       gint                    *num_messages,
172                                       gint                     io_priority,
173                                       GCancellable            *cancellable,
174                                       GAsyncReadyCallback      callback,
175                                       gpointer                 user_data)
176 {
177   ReadWithControlData *data;
178
179   data = g_new0 (ReadWithControlData, 1);
180   data->socket = g_object_ref (socket);
181   data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
182   data->buffer = buffer;
183   data->count = count;
184   data->messages = messages;
185   data->num_messages = num_messages;
186
187   data->simple = g_simple_async_result_new (G_OBJECT (socket),
188                                             callback,
189                                             user_data,
190                                             _g_socket_read_with_control_messages);
191
192   if (!g_socket_condition_check (socket, G_IO_IN))
193     {
194       GSource *source;
195       data->from_mainloop = TRUE;
196       source = g_socket_create_source (data->socket,
197                                        G_IO_IN | G_IO_HUP | G_IO_ERR,
198                                        cancellable);
199       g_source_set_callback (source,
200                              (GSourceFunc) _g_socket_read_with_control_messages_ready,
201                              data,
202                              (GDestroyNotify) read_with_control_data_free);
203       g_source_attach (source, g_main_context_get_thread_default ());
204       g_source_unref (source);
205     }
206   else
207     {
208       _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
209       read_with_control_data_free (data);
210     }
211 }
212
213 static gssize
214 _g_socket_read_with_control_messages_finish (GSocket       *socket,
215                                              GAsyncResult  *result,
216                                              GError       **error)
217 {
218   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
219
220   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
221   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
222
223   if (g_simple_async_result_propagate_error (simple, error))
224       return -1;
225   else
226     return g_simple_async_result_get_op_res_gssize (simple);
227 }
228
229 /* ---------------------------------------------------------------------------------------------------- */
230
231 G_LOCK_DEFINE_STATIC (shared_thread_lock);
232
233 typedef struct
234 {
235   gint num_users;
236   GThread *thread;
237   GMainContext *context;
238   GMainLoop *loop;
239 } SharedThreadData;
240
241 static SharedThreadData *shared_thread_data = NULL;
242
243 static gpointer
244 shared_thread_func (gpointer data)
245 {
246   g_main_context_push_thread_default (shared_thread_data->context);
247   g_main_loop_run (shared_thread_data->loop);
248   g_main_context_pop_thread_default (shared_thread_data->context);
249   return NULL;
250 }
251
252 typedef void (*GDBusSharedThreadFunc) (gpointer user_data);
253
254 typedef struct
255 {
256   GDBusSharedThreadFunc func;
257   gpointer              user_data;
258   gboolean              done;
259 } CallerData;
260
261 static gboolean
262 invoke_caller (gpointer user_data)
263 {
264   CallerData *data = user_data;
265   data->func (data->user_data);
266   data->done = TRUE;
267   return FALSE;
268 }
269
270 static void
271 _g_dbus_shared_thread_ref (GDBusSharedThreadFunc func,
272                            gpointer              user_data)
273 {
274   GError *error;
275   GSource *idle_source;
276   CallerData *data;
277
278   G_LOCK (shared_thread_lock);
279
280   if (shared_thread_data != NULL)
281     {
282       shared_thread_data->num_users += 1;
283       goto have_thread;
284     }
285
286   shared_thread_data = g_new0 (SharedThreadData, 1);
287   shared_thread_data->num_users = 1;
288
289   error = NULL;
290   shared_thread_data->context = g_main_context_new ();
291   shared_thread_data->loop = g_main_loop_new (shared_thread_data->context, FALSE);
292   shared_thread_data->thread = g_thread_create (shared_thread_func,
293                                                 NULL,
294                                                 TRUE,
295                                                 &error);
296   g_assert_no_error (error);
297
298  have_thread:
299
300   data = g_new0 (CallerData, 1);
301   data->func = func;
302   data->user_data = user_data;
303   data->done = FALSE;
304
305   idle_source = g_idle_source_new ();
306   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
307   g_source_set_callback (idle_source,
308                          invoke_caller,
309                          data,
310                          NULL);
311   g_source_attach (idle_source, shared_thread_data->context);
312   g_source_unref (idle_source);
313
314   /* wait for the user code to run.. hmm.. probably use a condition variable instead */
315   while (!data->done)
316     g_thread_yield ();
317
318   g_free (data);
319
320   G_UNLOCK (shared_thread_lock);
321 }
322
323 static void
324 _g_dbus_shared_thread_unref (void)
325 {
326   /* TODO: actually destroy the shared thread here */
327 #if 0
328   G_LOCK (shared_thread_lock);
329   g_assert (shared_thread_data != NULL);
330   shared_thread_data->num_users -= 1;
331   if (shared_thread_data->num_users == 0)
332     {
333       g_main_loop_quit (shared_thread_data->loop);
334       //g_thread_join (shared_thread_data->thread);
335       g_main_loop_unref (shared_thread_data->loop);
336       g_main_context_unref (shared_thread_data->context);
337       g_free (shared_thread_data);
338       shared_thread_data = NULL;
339       G_UNLOCK (shared_thread_lock);
340     }
341   else
342     {
343       G_UNLOCK (shared_thread_lock);
344     }
345 #endif
346 }
347
348 /* ---------------------------------------------------------------------------------------------------- */
349
350 struct GDBusWorker
351 {
352   volatile gint                       ref_count;
353
354   gboolean                            stopped;
355
356   /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
357    * only affects messages received from the other peer (since GDBusServer is the
358    * only user) - we might want it to affect messages sent to the other peer too?
359    */
360   gboolean                            frozen;
361   GQueue                             *received_messages_while_frozen;
362
363   GIOStream                          *stream;
364   GDBusCapabilityFlags                capabilities;
365   GCancellable                       *cancellable;
366   GDBusWorkerMessageReceivedCallback  message_received_callback;
367   GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
368   GDBusWorkerDisconnectedCallback     disconnected_callback;
369   gpointer                            user_data;
370
371   GThread                            *thread;
372
373   /* if not NULL, stream is GSocketConnection */
374   GSocket *socket;
375
376   /* used for reading */
377   GMutex                             *read_lock;
378   gchar                              *read_buffer;
379   gsize                               read_buffer_allocated_size;
380   gsize                               read_buffer_cur_size;
381   gsize                               read_buffer_bytes_wanted;
382   GUnixFDList                        *read_fd_list;
383   GSocketControlMessage             **read_ancillary_messages;
384   gint                                read_num_ancillary_messages;
385
386   /* used for writing */
387   GMutex                             *write_lock;
388   GQueue                             *write_queue;
389   gboolean                            write_is_pending;
390 };
391
392 struct _MessageToWriteData ;
393 typedef struct _MessageToWriteData MessageToWriteData;
394
395 static void message_to_write_data_free (MessageToWriteData *data);
396
397 static GDBusWorker *
398 _g_dbus_worker_ref (GDBusWorker *worker)
399 {
400   g_atomic_int_inc (&worker->ref_count);
401   return worker;
402 }
403
404 static void
405 _g_dbus_worker_unref (GDBusWorker *worker)
406 {
407   if (g_atomic_int_dec_and_test (&worker->ref_count))
408     {
409       _g_dbus_shared_thread_unref ();
410
411       g_object_unref (worker->stream);
412
413       g_mutex_free (worker->read_lock);
414       g_object_unref (worker->cancellable);
415       if (worker->read_fd_list != NULL)
416         g_object_unref (worker->read_fd_list);
417
418       g_queue_foreach (worker->received_messages_while_frozen, (GFunc) g_object_unref, NULL);
419       g_queue_free (worker->received_messages_while_frozen);
420
421       g_mutex_free (worker->write_lock);
422       g_queue_foreach (worker->write_queue, (GFunc) message_to_write_data_free, NULL);
423       g_queue_free (worker->write_queue);
424
425       g_free (worker);
426     }
427 }
428
429 static void
430 _g_dbus_worker_emit_disconnected (GDBusWorker  *worker,
431                                   gboolean      remote_peer_vanished,
432                                   GError       *error)
433 {
434   if (!worker->stopped)
435     worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
436 }
437
438 static void
439 _g_dbus_worker_emit_message_received (GDBusWorker  *worker,
440                                       GDBusMessage *message)
441 {
442   if (!worker->stopped)
443     worker->message_received_callback (worker, message, worker->user_data);
444 }
445
446 static gboolean
447 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker  *worker,
448                                               GDBusMessage *message)
449 {
450   gboolean ret;
451   ret = FALSE;
452   if (!worker->stopped)
453     ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
454   return ret;
455 }
456
457 /* can only be called from private thread with read-lock held - takes ownership of @message */
458 static void
459 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker  *worker,
460                                                   GDBusMessage *message)
461 {
462   if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
463     {
464       /* queue up */
465       g_queue_push_tail (worker->received_messages_while_frozen, message);
466     }
467   else
468     {
469       /* not frozen, nor anything in queue */
470       _g_dbus_worker_emit_message_received (worker, message);
471       g_object_unref (message);
472     }
473 }
474
475 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
476 static gboolean
477 unfreeze_in_idle_cb (gpointer user_data)
478 {
479   GDBusWorker *worker = user_data;
480   GDBusMessage *message;
481
482   g_mutex_lock (worker->read_lock);
483   if (worker->frozen)
484     {
485       while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
486         {
487           _g_dbus_worker_emit_message_received (worker, message);
488           g_object_unref (message);
489         }
490       worker->frozen = FALSE;
491     }
492   else
493     {
494       g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
495     }
496   g_mutex_unlock (worker->read_lock);
497   return FALSE;
498 }
499
500 /* can be called from any thread */
501 void
502 _g_dbus_worker_unfreeze (GDBusWorker *worker)
503 {
504   GSource *idle_source;
505   idle_source = g_idle_source_new ();
506   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
507   g_source_set_callback (idle_source,
508                          unfreeze_in_idle_cb,
509                          _g_dbus_worker_ref (worker),
510                          (GDestroyNotify) _g_dbus_worker_unref);
511   g_source_attach (idle_source, shared_thread_data->context);
512   g_source_unref (idle_source);
513 }
514
515 /* ---------------------------------------------------------------------------------------------------- */
516
517 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
518
519 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
520 static void
521 _g_dbus_worker_do_read_cb (GInputStream  *input_stream,
522                            GAsyncResult  *res,
523                            gpointer       user_data)
524 {
525   GDBusWorker *worker = user_data;
526   GError *error;
527   gssize bytes_read;
528
529   g_mutex_lock (worker->read_lock);
530
531   /* If already stopped, don't even process the reply */
532   if (worker->stopped)
533     goto out;
534
535   error = NULL;
536   if (worker->socket == NULL)
537     bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
538                                              res,
539                                              &error);
540   else
541     bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
542                                                               res,
543                                                               &error);
544   if (worker->read_num_ancillary_messages > 0)
545     {
546       gint n;
547       for (n = 0; n < worker->read_num_ancillary_messages; n++)
548         {
549           GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
550
551           if (FALSE)
552             {
553             }
554 #ifdef G_OS_UNIX
555           else if (G_IS_UNIX_FD_MESSAGE (control_message))
556             {
557               GUnixFDMessage *fd_message;
558               gint *fds;
559               gint num_fds;
560
561               fd_message = G_UNIX_FD_MESSAGE (control_message);
562               fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
563               if (worker->read_fd_list == NULL)
564                 {
565                   worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
566                 }
567               else
568                 {
569                   gint n;
570                   for (n = 0; n < num_fds; n++)
571                     {
572                       /* TODO: really want a append_steal() */
573                       g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
574                       close (fds[n]);
575                     }
576                 }
577               g_free (fds);
578             }
579           else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
580             {
581               /* do nothing */
582             }
583 #endif
584           else
585             {
586               if (error == NULL)
587                 {
588                   g_set_error (&error,
589                                G_IO_ERROR,
590                                G_IO_ERROR_FAILED,
591                                "Unexpected ancillary message of type %s received from peer",
592                                g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
593                   _g_dbus_worker_emit_disconnected (worker, TRUE, error);
594                   g_error_free (error);
595                   g_object_unref (control_message);
596                   n++;
597                   while (n < worker->read_num_ancillary_messages)
598                     g_object_unref (worker->read_ancillary_messages[n++]);
599                   g_free (worker->read_ancillary_messages);
600                   goto out;
601                 }
602             }
603           g_object_unref (control_message);
604         }
605       g_free (worker->read_ancillary_messages);
606     }
607
608   if (bytes_read == -1)
609     {
610       _g_dbus_worker_emit_disconnected (worker, TRUE, error);
611       g_error_free (error);
612       goto out;
613     }
614
615 #if 0
616   g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
617            (gint) bytes_read,
618            g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
619            g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
620            g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
621                                      G_IO_IN | G_IO_OUT | G_IO_HUP),
622            worker->stream,
623            worker);
624 #endif
625
626   /* TODO: hmm, hmm... */
627   if (bytes_read == 0)
628     {
629       g_set_error (&error,
630                    G_IO_ERROR,
631                    G_IO_ERROR_FAILED,
632                    "Underlying GIOStream returned 0 bytes on an async read");
633       _g_dbus_worker_emit_disconnected (worker, TRUE, error);
634       g_error_free (error);
635       goto out;
636     }
637
638   worker->read_buffer_cur_size += bytes_read;
639   if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
640     {
641       /* OK, got what we asked for! */
642       if (worker->read_buffer_bytes_wanted == 16)
643         {
644           gssize message_len;
645           /* OK, got the header - determine how many more bytes are needed */
646           error = NULL;
647           message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
648                                                      16,
649                                                      &error);
650           if (message_len == -1)
651             {
652               g_warning ("_g_dbus_worker_do_read_cb: error determing bytes needed: %s", error->message);
653               _g_dbus_worker_emit_disconnected (worker, FALSE, error);
654               g_error_free (error);
655               goto out;
656             }
657
658           worker->read_buffer_bytes_wanted = message_len;
659           _g_dbus_worker_do_read_unlocked (worker);
660         }
661       else
662         {
663           GDBusMessage *message;
664           error = NULL;
665
666           /* TODO: use connection->priv->auth to decode the message */
667
668           message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
669                                                   worker->read_buffer_cur_size,
670                                                   worker->capabilities,
671                                                   &error);
672           if (message == NULL)
673             {
674               gchar *s;
675               s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
676               g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
677                          "The error is: %s\n"
678                          "The payload is as follows:\n"
679                          "%s\n",
680                          worker->read_buffer_cur_size,
681                          error->message,
682                          s);
683               g_free (s);
684               _g_dbus_worker_emit_disconnected (worker, FALSE, error);
685               g_error_free (error);
686               goto out;
687             }
688
689 #ifdef G_OS_UNIX
690           if (worker->read_fd_list != NULL)
691             {
692               g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
693               worker->read_fd_list = NULL;
694             }
695 #endif
696
697           if (G_UNLIKELY (_g_dbus_debug_message ()))
698             {
699               gchar *s;
700               g_print ("========================================================================\n"
701                        "GDBus-debug:Message:\n"
702                        "  <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
703                        worker->read_buffer_cur_size);
704               s = g_dbus_message_print (message, 2);
705               g_print ("%s", s);
706               g_free (s);
707               s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
708               g_print ("%s\n", s);
709               g_free (s);
710             }
711
712           /* yay, got a message, go deliver it */
713           _g_dbus_worker_queue_or_deliver_received_message (worker, message);
714
715           /* start reading another message! */
716           worker->read_buffer_bytes_wanted = 0;
717           worker->read_buffer_cur_size = 0;
718           _g_dbus_worker_do_read_unlocked (worker);
719         }
720     }
721   else
722     {
723       /* didn't get all the bytes we requested - so repeat the request... */
724       _g_dbus_worker_do_read_unlocked (worker);
725     }
726
727  out:
728   g_mutex_unlock (worker->read_lock);
729
730   /* gives up the reference acquired when calling g_input_stream_read_async() */
731   _g_dbus_worker_unref (worker);
732 }
733
734 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
735 static void
736 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
737 {
738   /* if bytes_wanted is zero, it means start reading a message */
739   if (worker->read_buffer_bytes_wanted == 0)
740     {
741       worker->read_buffer_cur_size = 0;
742       worker->read_buffer_bytes_wanted = 16;
743     }
744
745   /* ensure we have a (big enough) buffer */
746   if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
747     {
748       /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
749       worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
750       worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
751     }
752
753   if (worker->socket == NULL)
754     g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
755                                worker->read_buffer + worker->read_buffer_cur_size,
756                                worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
757                                G_PRIORITY_DEFAULT,
758                                worker->cancellable,
759                                (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
760                                _g_dbus_worker_ref (worker));
761   else
762     {
763       worker->read_ancillary_messages = NULL;
764       worker->read_num_ancillary_messages = 0;
765       _g_socket_read_with_control_messages (worker->socket,
766                                             worker->read_buffer + worker->read_buffer_cur_size,
767                                             worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
768                                             &worker->read_ancillary_messages,
769                                             &worker->read_num_ancillary_messages,
770                                             G_PRIORITY_DEFAULT,
771                                             worker->cancellable,
772                                             (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
773                                             _g_dbus_worker_ref (worker));
774     }
775 }
776
777 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
778 static void
779 _g_dbus_worker_do_read (GDBusWorker *worker)
780 {
781   g_mutex_lock (worker->read_lock);
782   _g_dbus_worker_do_read_unlocked (worker);
783   g_mutex_unlock (worker->read_lock);
784 }
785
786 /* ---------------------------------------------------------------------------------------------------- */
787
788 struct _MessageToWriteData
789 {
790   GDBusMessage *message;
791   gchar        *blob;
792   gsize         blob_size;
793 };
794
795 static void
796 message_to_write_data_free (MessageToWriteData *data)
797 {
798   g_object_unref (data->message);
799   g_free (data->blob);
800   g_free (data);
801 }
802
803 /* ---------------------------------------------------------------------------------------------------- */
804
805 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
806 static gboolean
807 write_message (GDBusWorker         *worker,
808                MessageToWriteData  *data,
809                GError             **error)
810 {
811   gboolean ret;
812
813   g_return_val_if_fail (data->blob_size > 16, FALSE);
814
815   ret = FALSE;
816
817   /* First, the initial 16 bytes - special case UNIX sockets here
818    * since it may involve writing an ancillary message with file
819    * descriptors
820    */
821 #ifdef G_OS_UNIX
822   {
823     GOutputVector vector;
824     GSocketControlMessage *message;
825     GUnixFDList *fd_list;
826     gssize bytes_written;
827
828     fd_list = g_dbus_message_get_unix_fd_list (data->message);
829
830     message = NULL;
831     if (fd_list != NULL)
832       {
833         if (!G_IS_UNIX_CONNECTION (worker->stream))
834           {
835             g_set_error (error,
836                          G_IO_ERROR,
837                          G_IO_ERROR_INVALID_ARGUMENT,
838                          "Tried sending a file descriptor on unsupported stream of type %s",
839                          g_type_name (G_TYPE_FROM_INSTANCE (worker->stream)));
840             goto out;
841           }
842         else if (!(worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
843           {
844             g_set_error_literal (error,
845                                  G_IO_ERROR,
846                                  G_IO_ERROR_INVALID_ARGUMENT,
847                                  "Tried sending a file descriptor but remote peer does not support this capability");
848             goto out;
849           }
850         message = g_unix_fd_message_new_with_fd_list (fd_list);
851       }
852
853     vector.buffer = data->blob;
854     vector.size = 16;
855
856     bytes_written = g_socket_send_message (worker->socket,
857                                            NULL, /* address */
858                                            &vector,
859                                            1,
860                                            message != NULL ? &message : NULL,
861                                            message != NULL ? 1 : 0,
862                                            G_SOCKET_MSG_NONE,
863                                            worker->cancellable,
864                                            error);
865     if (bytes_written == -1)
866       {
867         g_prefix_error (error, _("Error writing first 16 bytes of message to socket: "));
868         if (message != NULL)
869           g_object_unref (message);
870         goto out;
871       }
872     if (message != NULL)
873       g_object_unref (message);
874
875     if (bytes_written < 16)
876       {
877         /* TODO: I think this needs to be handled ... are we guaranteed that the ancillary
878          * messages are sent?
879          */
880         g_assert_not_reached ();
881       }
882   }
883 #else
884   /* write the first 16 bytes (guaranteed to return an error if everything can't be written) */
885   if (!g_output_stream_write_all (g_io_stream_get_output_stream (worker->stream),
886                                   (const gchar *) data->blob,
887                                   16,
888                                   NULL, /* bytes_written */
889                                   worker->cancellable, /* cancellable */
890                                   error))
891     goto out;
892 #endif
893
894   /* Then write the rest of the message (guaranteed to return an error if everything can't be written) */
895   if (!g_output_stream_write_all (g_io_stream_get_output_stream (worker->stream),
896                                   (const gchar *) data->blob + 16,
897                                   data->blob_size - 16,
898                                   NULL, /* bytes_written */
899                                   worker->cancellable, /* cancellable */
900                                   error))
901     goto out;
902
903   ret = TRUE;
904
905   if (G_UNLIKELY (_g_dbus_debug_message ()))
906     {
907       gchar *s;
908       g_print ("========================================================================\n"
909                "GDBus-debug:Message:\n"
910                "  >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
911                data->blob_size);
912       s = g_dbus_message_print (data->message, 2);
913       g_print ("%s", s);
914       g_free (s);
915       s = _g_dbus_hexdump (data->blob, data->blob_size, 2);
916       g_print ("%s\n", s);
917       g_free (s);
918     }
919
920  out:
921   return ret;
922 }
923
924 /* ---------------------------------------------------------------------------------------------------- */
925
926 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
927 static gboolean
928 write_message_in_idle_cb (gpointer user_data)
929 {
930   GDBusWorker *worker = user_data;
931   gboolean more_writes_are_pending;
932   MessageToWriteData *data;
933   gboolean message_was_dropped;
934   GError *error;
935
936   g_mutex_lock (worker->write_lock);
937   data = g_queue_pop_head (worker->write_queue);
938   g_assert (data != NULL);
939   more_writes_are_pending = (g_queue_get_length (worker->write_queue) > 0);
940   worker->write_is_pending = more_writes_are_pending;
941   g_mutex_unlock (worker->write_lock);
942
943   /* Note that write_lock is only used for protecting the @write_queue
944    * and @write_is_pending fields of the GDBusWorker struct ... which we
945    * need to modify from arbitrary threads in _g_dbus_worker_send_message().
946    *
947    * Therefore, it's fine to drop it here when calling back into user
948    * code and then writing the message out onto the GIOStream since this
949    * function only runs on the worker thread.
950    */
951   message_was_dropped = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
952   if (G_LIKELY (!message_was_dropped))
953     {
954       error = NULL;
955       if (!write_message (worker,
956                           data,
957                           &error))
958         {
959           /* TODO: handle */
960           _g_dbus_worker_emit_disconnected (worker, TRUE, error);
961           g_error_free (error);
962         }
963     }
964   message_to_write_data_free (data);
965
966   return more_writes_are_pending;
967 }
968
969 /* ---------------------------------------------------------------------------------------------------- */
970
971 /* can be called from any thread - steals blob */
972 void
973 _g_dbus_worker_send_message (GDBusWorker    *worker,
974                              GDBusMessage   *message,
975                              gchar          *blob,
976                              gsize           blob_len)
977 {
978   MessageToWriteData *data;
979
980   g_return_if_fail (G_IS_DBUS_MESSAGE (message));
981   g_return_if_fail (blob != NULL);
982   g_return_if_fail (blob_len > 16);
983
984   data = g_new0 (MessageToWriteData, 1);
985   data->message = g_object_ref (message);
986   data->blob = blob; /* steal! */
987   data->blob_size = blob_len;
988
989   g_mutex_lock (worker->write_lock);
990   g_queue_push_tail (worker->write_queue, data);
991   if (!worker->write_is_pending)
992     {
993       GSource *idle_source;
994
995       worker->write_is_pending = TRUE;
996
997       idle_source = g_idle_source_new ();
998       g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
999       g_source_set_callback (idle_source,
1000                              write_message_in_idle_cb,
1001                              _g_dbus_worker_ref (worker),
1002                              (GDestroyNotify) _g_dbus_worker_unref);
1003       g_source_attach (idle_source, shared_thread_data->context);
1004       g_source_unref (idle_source);
1005     }
1006   g_mutex_unlock (worker->write_lock);
1007 }
1008
1009 /* ---------------------------------------------------------------------------------------------------- */
1010
1011 static void
1012 _g_dbus_worker_thread_begin_func (gpointer user_data)
1013 {
1014   GDBusWorker *worker = user_data;
1015
1016   worker->thread = g_thread_self ();
1017
1018   /* begin reading */
1019   _g_dbus_worker_do_read (worker);
1020 }
1021
1022 GDBusWorker *
1023 _g_dbus_worker_new (GIOStream                              *stream,
1024                     GDBusCapabilityFlags                    capabilities,
1025                     gboolean                                initially_frozen,
1026                     GDBusWorkerMessageReceivedCallback      message_received_callback,
1027                     GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1028                     GDBusWorkerDisconnectedCallback         disconnected_callback,
1029                     gpointer                                user_data)
1030 {
1031   GDBusWorker *worker;
1032
1033   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1034   g_return_val_if_fail (message_received_callback != NULL, NULL);
1035   g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1036   g_return_val_if_fail (disconnected_callback != NULL, NULL);
1037
1038   worker = g_new0 (GDBusWorker, 1);
1039   worker->ref_count = 1;
1040
1041   worker->read_lock = g_mutex_new ();
1042   worker->message_received_callback = message_received_callback;
1043   worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1044   worker->disconnected_callback = disconnected_callback;
1045   worker->user_data = user_data;
1046   worker->stream = g_object_ref (stream);
1047   worker->capabilities = capabilities;
1048   worker->cancellable = g_cancellable_new ();
1049
1050   worker->frozen = initially_frozen;
1051   worker->received_messages_while_frozen = g_queue_new ();
1052
1053   worker->write_lock = g_mutex_new ();
1054   worker->write_queue = g_queue_new ();
1055
1056   if (G_IS_SOCKET_CONNECTION (worker->stream))
1057     worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1058
1059   _g_dbus_shared_thread_ref (_g_dbus_worker_thread_begin_func, worker);
1060
1061   return worker;
1062 }
1063
1064 /* This can be called from any thread - frees worker - guarantees no callbacks
1065  * will ever be issued again
1066  */
1067 void
1068 _g_dbus_worker_stop (GDBusWorker *worker)
1069 {
1070   /* If we're called in the worker thread it means we are called from
1071    * a worker callback. This is fine, we just can't lock in that case since
1072    * we're already holding the lock...
1073    */
1074   if (g_thread_self () != worker->thread)
1075     g_mutex_lock (worker->read_lock);
1076   worker->stopped = TRUE;
1077   if (g_thread_self () != worker->thread)
1078     g_mutex_unlock (worker->read_lock);
1079
1080   g_cancellable_cancel (worker->cancellable);
1081   _g_dbus_worker_unref (worker);
1082 }
1083
1084 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1085 #define G_DBUS_DEBUG_MESSAGE        (1<<1)
1086 #define G_DBUS_DEBUG_ALL            0xffffffff
1087 static gint _gdbus_debug_flags = 0;
1088
1089 gboolean
1090 _g_dbus_debug_authentication (void)
1091 {
1092   _g_dbus_initialize ();
1093   return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1094 }
1095
1096 gboolean
1097 _g_dbus_debug_message (void)
1098 {
1099   _g_dbus_initialize ();
1100   return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1101 }
1102
1103 /*
1104  * _g_dbus_initialize:
1105  *
1106  * Does various one-time init things such as
1107  *
1108  *  - registering the G_DBUS_ERROR error domain
1109  *  - parses the G_DBUS_DEBUG environment variable
1110  */
1111 void
1112 _g_dbus_initialize (void)
1113 {
1114   static volatile gsize initialized = 0;
1115
1116   if (g_once_init_enter (&initialized))
1117     {
1118       volatile GQuark g_dbus_error_domain;
1119       const gchar *debug;
1120
1121       g_dbus_error_domain = G_DBUS_ERROR;
1122
1123       debug = g_getenv ("G_DBUS_DEBUG");
1124       if (debug != NULL)
1125         {
1126           gchar **tokens;
1127           guint n;
1128           tokens = g_strsplit (debug, ",", 0);
1129           for (n = 0; tokens[n] != NULL; n++)
1130             {
1131               if (g_strcmp0 (tokens[n], "authentication") == 0)
1132                 _gdbus_debug_flags |= G_DBUS_DEBUG_AUTHENTICATION;
1133               else if (g_strcmp0 (tokens[n], "message") == 0)
1134                 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1135               else if (g_strcmp0 (tokens[n], "all") == 0)
1136                 _gdbus_debug_flags |= G_DBUS_DEBUG_ALL;
1137             }
1138           g_strfreev (tokens);
1139         }
1140
1141       g_once_init_leave (&initialized, 1);
1142     }
1143 }
1144
1145 /* ---------------------------------------------------------------------------------------------------- */
1146
1147 GVariantType *
1148 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1149 {
1150   const GVariantType *arg_types[256];
1151   guint n;
1152
1153   if (args)
1154     for (n = 0; args[n] != NULL; n++)
1155       {
1156         /* DBus places a hard limit of 255 on signature length.
1157          * therefore number of args must be less than 256.
1158          */
1159         g_assert (n < 256);
1160
1161         arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1162
1163         if G_UNLIKELY (arg_types[n] == NULL)
1164           return NULL;
1165       }
1166   else
1167     n = 0;
1168
1169   return g_variant_type_new_tuple (arg_types, n);
1170 }
1171
1172 /* ---------------------------------------------------------------------------------------------------- */
1173
1174 #ifdef G_OS_WIN32
1175
1176 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1177
1178 gchar *
1179 _g_dbus_win32_get_user_sid (void)
1180 {
1181   HANDLE h;
1182   TOKEN_USER *user;
1183   DWORD token_information_len;
1184   PSID psid;
1185   gchar *sid;
1186   gchar *ret;
1187
1188   ret = NULL;
1189   user = NULL;
1190   h = INVALID_HANDLE_VALUE;
1191
1192   if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
1193     {
1194       g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
1195       goto out;
1196     }
1197
1198   /* Get length of buffer */
1199   token_information_len = 0;
1200   if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
1201     {
1202       if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1203         {
1204           g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1205           goto out;
1206         }
1207     }
1208   user = g_malloc (token_information_len);
1209   if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
1210     {
1211       g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1212       goto out;
1213     }
1214
1215   psid = user->User.Sid;
1216   if (!IsValidSid (psid))
1217     {
1218       g_warning ("Invalid SID");
1219       goto out;
1220     }
1221
1222   if (!ConvertSidToStringSidA (psid, &sid))
1223     {
1224       g_warning ("Invalid SID");
1225       goto out;
1226     }
1227
1228   ret = g_strdup (sid);
1229   LocalFree (sid);
1230
1231 out:
1232   g_free (user);
1233   if (h != INVALID_HANDLE_VALUE)
1234     CloseHandle (h);
1235   return ret;
1236 }
1237 #endif
1238
1239 /* ---------------------------------------------------------------------------------------------------- */
1240
1241 #define __G_DBUS_PRIVATE_C__
1242 #include "gioaliasdef.c"