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