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