1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
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.
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.
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.
20 * Author: David Zeuthen <davidz@redhat.com>
33 #include "gdbusprivate.h"
34 #include "gdbusmessage.h"
35 #include "gdbuserror.h"
36 #include "gdbusintrospection.h"
37 #include "gasyncresult.h"
38 #include "gsimpleasyncresult.h"
39 #include "ginputstream.h"
40 #include "gmemoryinputstream.h"
41 #include "giostream.h"
42 #include "gsocketcontrolmessage.h"
43 #include "gsocketconnection.h"
44 #include "gsocketoutputstream.h"
47 #include "gunixfdmessage.h"
48 #include "gunixconnection.h"
49 #include "gunixcredentialsmessage.h"
58 /* ---------------------------------------------------------------------------------------------------- */
61 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
66 ret = g_string_new (NULL);
68 for (n = 0; n < len; n += 16)
70 g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
72 for (m = n; m < n + 16; m++)
74 if (m > n && (m%4) == 0)
75 g_string_append_c (ret, ' ');
77 g_string_append_printf (ret, "%02x ", (guchar) data[m]);
79 g_string_append (ret, " ");
82 g_string_append (ret, " ");
84 for (m = n; m < len && m < n + 16; m++)
85 g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
87 g_string_append_c (ret, '\n');
90 return g_string_free (ret, FALSE);
93 /* ---------------------------------------------------------------------------------------------------- */
95 /* Unfortunately ancillary messages are discarded when reading from a
96 * socket using the GSocketInputStream abstraction. So we provide a
97 * very GInputStream-ish API that uses GSocket in this case (very
98 * similar to GSocketInputStream).
104 GCancellable *cancellable;
109 GSocketControlMessage ***messages;
112 GSimpleAsyncResult *simple;
114 gboolean from_mainloop;
115 } ReadWithControlData;
118 read_with_control_data_free (ReadWithControlData *data)
120 g_object_unref (data->socket);
121 if (data->cancellable != NULL)
122 g_object_unref (data->cancellable);
123 g_object_unref (data->simple);
128 _g_socket_read_with_control_messages_ready (GSocket *socket,
129 GIOCondition condition,
132 ReadWithControlData *data = user_data;
138 vector.buffer = data->buffer;
139 vector.size = data->count;
140 result = g_socket_receive_message (data->socket,
151 g_simple_async_result_set_op_res_gssize (data->simple, result);
155 g_assert (error != NULL);
156 g_simple_async_result_take_error (data->simple, error);
159 if (data->from_mainloop)
160 g_simple_async_result_complete (data->simple);
162 g_simple_async_result_complete_in_idle (data->simple);
168 _g_socket_read_with_control_messages (GSocket *socket,
171 GSocketControlMessage ***messages,
174 GCancellable *cancellable,
175 GAsyncReadyCallback callback,
178 ReadWithControlData *data;
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;
185 data->messages = messages;
186 data->num_messages = num_messages;
188 data->simple = g_simple_async_result_new (G_OBJECT (socket),
191 _g_socket_read_with_control_messages);
193 if (!g_socket_condition_check (socket, G_IO_IN))
196 data->from_mainloop = TRUE;
197 source = g_socket_create_source (data->socket,
198 G_IO_IN | G_IO_HUP | G_IO_ERR,
200 g_source_set_callback (source,
201 (GSourceFunc) _g_socket_read_with_control_messages_ready,
203 (GDestroyNotify) read_with_control_data_free);
204 g_source_attach (source, g_main_context_get_thread_default ());
205 g_source_unref (source);
209 _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
210 read_with_control_data_free (data);
215 _g_socket_read_with_control_messages_finish (GSocket *socket,
216 GAsyncResult *result,
219 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
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);
224 if (g_simple_async_result_propagate_error (simple, error))
227 return g_simple_async_result_get_op_res_gssize (simple);
230 /* ---------------------------------------------------------------------------------------------------- */
232 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
234 static GPtrArray *ensured_classes = NULL;
237 ensure_type (GType gtype)
239 g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
243 released_required_types (void)
245 g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
246 g_ptr_array_unref (ensured_classes);
247 ensured_classes = NULL;
251 ensure_required_types (void)
253 g_assert (ensured_classes == NULL);
254 ensured_classes = g_ptr_array_new ();
255 ensure_type (G_TYPE_SIMPLE_ASYNC_RESULT);
256 ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
258 /* ---------------------------------------------------------------------------------------------------- */
260 G_LOCK_DEFINE_STATIC (shared_thread_lock);
266 GMainContext *context;
270 static SharedThreadData *shared_thread_data = NULL;
273 gdbus_shared_thread_func (gpointer data)
275 g_main_context_push_thread_default (shared_thread_data->context);
276 g_main_loop_run (shared_thread_data->loop);
277 g_main_context_pop_thread_default (shared_thread_data->context);
281 typedef void (*GDBusSharedThreadFunc) (gpointer user_data);
285 GDBusSharedThreadFunc func;
291 invoke_caller (gpointer user_data)
293 CallerData *data = user_data;
294 data->func (data->user_data);
299 /* ---------------------------------------------------------------------------------------------------- */
302 _g_dbus_shared_thread_ref (GDBusSharedThreadFunc func,
306 GSource *idle_source;
308 gboolean release_types;
310 G_LOCK (shared_thread_lock);
312 release_types = FALSE;
314 if (shared_thread_data != NULL)
316 shared_thread_data->num_users += 1;
320 shared_thread_data = g_new0 (SharedThreadData, 1);
321 shared_thread_data->num_users = 1;
323 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
324 ensure_required_types ();
325 release_types = TRUE;
328 shared_thread_data->context = g_main_context_new ();
329 shared_thread_data->loop = g_main_loop_new (shared_thread_data->context, FALSE);
330 shared_thread_data->thread = g_thread_create (gdbus_shared_thread_func,
334 g_assert_no_error (error);
338 data = g_new0 (CallerData, 1);
340 data->user_data = user_data;
343 idle_source = g_idle_source_new ();
344 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
345 g_source_set_callback (idle_source,
349 g_source_attach (idle_source, shared_thread_data->context);
350 g_source_unref (idle_source);
352 /* wait for the user code to run.. hmm.. probably use a condition variable instead */
357 released_required_types ();
361 G_UNLOCK (shared_thread_lock);
365 _g_dbus_shared_thread_unref (void)
367 /* TODO: actually destroy the shared thread here */
369 G_LOCK (shared_thread_lock);
370 g_assert (shared_thread_data != NULL);
371 shared_thread_data->num_users -= 1;
372 if (shared_thread_data->num_users == 0)
374 g_main_loop_quit (shared_thread_data->loop);
375 //g_thread_join (shared_thread_data->thread);
376 g_main_loop_unref (shared_thread_data->loop);
377 g_main_context_unref (shared_thread_data->context);
378 g_free (shared_thread_data);
379 shared_thread_data = NULL;
380 G_UNLOCK (shared_thread_lock);
384 G_UNLOCK (shared_thread_lock);
389 /* ---------------------------------------------------------------------------------------------------- */
393 volatile gint ref_count;
397 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
398 * only affects messages received from the other peer (since GDBusServer is the
399 * only user) - we might want it to affect messages sent to the other peer too?
402 GDBusCapabilityFlags capabilities;
403 GQueue *received_messages_while_frozen;
406 GCancellable *cancellable;
407 GDBusWorkerMessageReceivedCallback message_received_callback;
408 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
409 GDBusWorkerDisconnectedCallback disconnected_callback;
414 /* if not NULL, stream is GSocketConnection */
417 /* used for reading */
420 gsize read_buffer_allocated_size;
421 gsize read_buffer_cur_size;
422 gsize read_buffer_bytes_wanted;
423 GUnixFDList *read_fd_list;
424 GSocketControlMessage **read_ancillary_messages;
425 gint read_num_ancillary_messages;
427 /* used for writing */
428 gint num_writes_pending;
431 guint64 write_num_messages_written;
432 GList *write_pending_flushes;
433 gboolean flush_pending;
436 /* ---------------------------------------------------------------------------------------------------- */
442 guint64 number_to_wait_for;
446 struct _MessageToWriteData ;
447 typedef struct _MessageToWriteData MessageToWriteData;
449 static void message_to_write_data_free (MessageToWriteData *data);
451 static void read_message_print_transport_debug (gssize bytes_read,
452 GDBusWorker *worker);
454 static void write_message_print_transport_debug (gssize bytes_written,
455 MessageToWriteData *data);
457 /* ---------------------------------------------------------------------------------------------------- */
460 _g_dbus_worker_ref (GDBusWorker *worker)
462 g_atomic_int_inc (&worker->ref_count);
467 _g_dbus_worker_unref (GDBusWorker *worker)
469 if (g_atomic_int_dec_and_test (&worker->ref_count))
471 g_assert (worker->write_pending_flushes == NULL);
473 _g_dbus_shared_thread_unref ();
475 g_object_unref (worker->stream);
477 g_mutex_free (worker->read_lock);
478 g_object_unref (worker->cancellable);
479 if (worker->read_fd_list != NULL)
480 g_object_unref (worker->read_fd_list);
482 g_queue_foreach (worker->received_messages_while_frozen, (GFunc) g_object_unref, NULL);
483 g_queue_free (worker->received_messages_while_frozen);
485 g_mutex_free (worker->write_lock);
486 g_queue_foreach (worker->write_queue, (GFunc) message_to_write_data_free, NULL);
487 g_queue_free (worker->write_queue);
489 g_free (worker->read_buffer);
496 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
497 gboolean remote_peer_vanished,
500 if (!worker->stopped)
501 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
505 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
506 GDBusMessage *message)
508 if (!worker->stopped)
509 worker->message_received_callback (worker, message, worker->user_data);
512 static GDBusMessage *
513 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
514 GDBusMessage *message)
517 if (!worker->stopped)
518 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
524 /* can only be called from private thread with read-lock held - takes ownership of @message */
526 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
527 GDBusMessage *message)
529 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
532 g_queue_push_tail (worker->received_messages_while_frozen, message);
536 /* not frozen, nor anything in queue */
537 _g_dbus_worker_emit_message_received (worker, message);
538 g_object_unref (message);
542 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
544 unfreeze_in_idle_cb (gpointer user_data)
546 GDBusWorker *worker = user_data;
547 GDBusMessage *message;
549 g_mutex_lock (worker->read_lock);
552 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
554 _g_dbus_worker_emit_message_received (worker, message);
555 g_object_unref (message);
557 worker->frozen = FALSE;
561 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
563 g_mutex_unlock (worker->read_lock);
567 /* can be called from any thread */
569 _g_dbus_worker_unfreeze (GDBusWorker *worker)
571 GSource *idle_source;
572 idle_source = g_idle_source_new ();
573 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
574 g_source_set_callback (idle_source,
576 _g_dbus_worker_ref (worker),
577 (GDestroyNotify) _g_dbus_worker_unref);
578 g_source_attach (idle_source, shared_thread_data->context);
579 g_source_unref (idle_source);
582 /* ---------------------------------------------------------------------------------------------------- */
584 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
586 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
588 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
592 GDBusWorker *worker = user_data;
596 g_mutex_lock (worker->read_lock);
598 /* If already stopped, don't even process the reply */
603 if (worker->socket == NULL)
604 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
608 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
611 if (worker->read_num_ancillary_messages > 0)
614 for (n = 0; n < worker->read_num_ancillary_messages; n++)
616 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
622 else if (G_IS_UNIX_FD_MESSAGE (control_message))
624 GUnixFDMessage *fd_message;
628 fd_message = G_UNIX_FD_MESSAGE (control_message);
629 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
630 if (worker->read_fd_list == NULL)
632 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
637 for (n = 0; n < num_fds; n++)
639 /* TODO: really want a append_steal() */
640 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
646 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
658 "Unexpected ancillary message of type %s received from peer",
659 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
660 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
661 g_error_free (error);
662 g_object_unref (control_message);
664 while (n < worker->read_num_ancillary_messages)
665 g_object_unref (worker->read_ancillary_messages[n++]);
666 g_free (worker->read_ancillary_messages);
670 g_object_unref (control_message);
672 g_free (worker->read_ancillary_messages);
675 if (bytes_read == -1)
677 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
678 g_error_free (error);
683 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
685 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
686 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
687 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
688 G_IO_IN | G_IO_OUT | G_IO_HUP),
693 /* TODO: hmm, hmm... */
699 "Underlying GIOStream returned 0 bytes on an async read");
700 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
701 g_error_free (error);
705 read_message_print_transport_debug (bytes_read, worker);
707 worker->read_buffer_cur_size += bytes_read;
708 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
710 /* OK, got what we asked for! */
711 if (worker->read_buffer_bytes_wanted == 16)
714 /* OK, got the header - determine how many more bytes are needed */
716 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
719 if (message_len == -1)
721 g_warning ("_g_dbus_worker_do_read_cb: error determing bytes needed: %s", error->message);
722 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
723 g_error_free (error);
727 worker->read_buffer_bytes_wanted = message_len;
728 _g_dbus_worker_do_read_unlocked (worker);
732 GDBusMessage *message;
735 /* TODO: use connection->priv->auth to decode the message */
737 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
738 worker->read_buffer_cur_size,
739 worker->capabilities,
744 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
745 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
747 "The payload is as follows:\n"
749 worker->read_buffer_cur_size,
753 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
754 g_error_free (error);
759 if (worker->read_fd_list != NULL)
761 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
762 g_object_unref (worker->read_fd_list);
763 worker->read_fd_list = NULL;
767 if (G_UNLIKELY (_g_dbus_debug_message ()))
770 _g_dbus_debug_print_lock ();
771 g_print ("========================================================================\n"
772 "GDBus-debug:Message:\n"
773 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
774 worker->read_buffer_cur_size);
775 s = g_dbus_message_print (message, 2);
778 if (G_UNLIKELY (_g_dbus_debug_payload ()))
780 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
784 _g_dbus_debug_print_unlock ();
787 /* yay, got a message, go deliver it */
788 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
790 /* start reading another message! */
791 worker->read_buffer_bytes_wanted = 0;
792 worker->read_buffer_cur_size = 0;
793 _g_dbus_worker_do_read_unlocked (worker);
798 /* didn't get all the bytes we requested - so repeat the request... */
799 _g_dbus_worker_do_read_unlocked (worker);
803 g_mutex_unlock (worker->read_lock);
805 /* gives up the reference acquired when calling g_input_stream_read_async() */
806 _g_dbus_worker_unref (worker);
809 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
811 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
813 /* if bytes_wanted is zero, it means start reading a message */
814 if (worker->read_buffer_bytes_wanted == 0)
816 worker->read_buffer_cur_size = 0;
817 worker->read_buffer_bytes_wanted = 16;
820 /* ensure we have a (big enough) buffer */
821 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
823 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
824 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
825 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
828 if (worker->socket == NULL)
829 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
830 worker->read_buffer + worker->read_buffer_cur_size,
831 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
834 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
835 _g_dbus_worker_ref (worker));
838 worker->read_ancillary_messages = NULL;
839 worker->read_num_ancillary_messages = 0;
840 _g_socket_read_with_control_messages (worker->socket,
841 worker->read_buffer + worker->read_buffer_cur_size,
842 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
843 &worker->read_ancillary_messages,
844 &worker->read_num_ancillary_messages,
847 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
848 _g_dbus_worker_ref (worker));
852 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
854 _g_dbus_worker_do_read (GDBusWorker *worker)
856 g_mutex_lock (worker->read_lock);
857 _g_dbus_worker_do_read_unlocked (worker);
858 g_mutex_unlock (worker->read_lock);
861 /* ---------------------------------------------------------------------------------------------------- */
863 struct _MessageToWriteData
866 GDBusMessage *message;
871 GSimpleAsyncResult *simple;
876 message_to_write_data_free (MessageToWriteData *data)
878 _g_dbus_worker_unref (data->worker);
880 g_object_unref (data->message);
885 /* ---------------------------------------------------------------------------------------------------- */
887 static void write_message_continue_writing (MessageToWriteData *data);
889 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
891 write_message_async_cb (GObject *source_object,
895 MessageToWriteData *data = user_data;
896 GSimpleAsyncResult *simple;
897 gssize bytes_written;
900 /* Note: we can't access data->simple after calling g_async_result_complete () because the
901 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
903 simple = data->simple;
906 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
909 if (bytes_written == -1)
911 g_simple_async_result_take_error (simple, error);
912 g_simple_async_result_complete (simple);
913 g_object_unref (simple);
916 g_assert (bytes_written > 0); /* zero is never returned */
918 write_message_print_transport_debug (bytes_written, data);
920 data->total_written += bytes_written;
921 g_assert (data->total_written <= data->blob_size);
922 if (data->total_written == data->blob_size)
924 g_simple_async_result_complete (simple);
925 g_object_unref (simple);
929 write_message_continue_writing (data);
935 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
937 on_socket_ready (GSocket *socket,
938 GIOCondition condition,
941 MessageToWriteData *data = user_data;
942 write_message_continue_writing (data);
943 return FALSE; /* remove source */
946 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
948 write_message_continue_writing (MessageToWriteData *data)
950 GOutputStream *ostream;
951 GSimpleAsyncResult *simple;
953 GUnixFDList *fd_list;
956 /* Note: we can't access data->simple after calling g_async_result_complete () because the
957 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
959 simple = data->simple;
961 ostream = g_io_stream_get_output_stream (data->worker->stream);
963 fd_list = g_dbus_message_get_unix_fd_list (data->message);
966 g_assert (!g_output_stream_has_pending (ostream));
967 g_assert_cmpint (data->total_written, <, data->blob_size);
973 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
975 GOutputVector vector;
976 GSocketControlMessage *control_message;
977 gssize bytes_written;
980 vector.buffer = data->blob;
981 vector.size = data->blob_size;
983 control_message = NULL;
984 if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
986 if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
988 g_simple_async_result_set_error (simple,
991 "Tried sending a file descriptor but remote peer does not support this capability");
992 g_simple_async_result_complete (simple);
993 g_object_unref (simple);
996 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1000 bytes_written = g_socket_send_message (data->worker->socket,
1004 control_message != NULL ? &control_message : NULL,
1005 control_message != NULL ? 1 : 0,
1007 data->worker->cancellable,
1009 if (control_message != NULL)
1010 g_object_unref (control_message);
1012 if (bytes_written == -1)
1014 /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1015 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1018 source = g_socket_create_source (data->worker->socket,
1019 G_IO_OUT | G_IO_HUP | G_IO_ERR,
1020 data->worker->cancellable);
1021 g_source_set_callback (source,
1022 (GSourceFunc) on_socket_ready,
1024 NULL); /* GDestroyNotify */
1025 g_source_attach (source, g_main_context_get_thread_default ());
1026 g_source_unref (source);
1027 g_error_free (error);
1030 g_simple_async_result_take_error (simple, error);
1031 g_simple_async_result_complete (simple);
1032 g_object_unref (simple);
1035 g_assert (bytes_written > 0); /* zero is never returned */
1037 write_message_print_transport_debug (bytes_written, data);
1039 data->total_written += bytes_written;
1040 g_assert (data->total_written <= data->blob_size);
1041 if (data->total_written == data->blob_size)
1043 g_simple_async_result_complete (simple);
1044 g_object_unref (simple);
1048 write_message_continue_writing (data);
1054 if (fd_list != NULL)
1056 g_simple_async_result_set_error (simple,
1059 "Tried sending a file descriptor on unsupported stream of type %s",
1060 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1061 g_simple_async_result_complete (simple);
1062 g_object_unref (simple);
1067 g_output_stream_write_async (ostream,
1068 (const gchar *) data->blob + data->total_written,
1069 data->blob_size - data->total_written,
1071 data->worker->cancellable,
1072 write_message_async_cb,
1079 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1081 write_message_async (GDBusWorker *worker,
1082 MessageToWriteData *data,
1083 GAsyncReadyCallback callback,
1086 data->simple = g_simple_async_result_new (NULL,
1089 write_message_async);
1090 data->total_written = 0;
1091 write_message_continue_writing (data);
1094 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1096 write_message_finish (GAsyncResult *res,
1099 g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1100 if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1105 /* ---------------------------------------------------------------------------------------------------- */
1107 static void maybe_write_next_message (GDBusWorker *worker);
1111 GDBusWorker *worker;
1115 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1117 ostream_flush_cb (GObject *source_object,
1121 FlushAsyncData *data = user_data;
1126 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1132 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1134 _g_dbus_debug_print_lock ();
1135 g_print ("========================================================================\n"
1136 "GDBus-debug:Transport:\n"
1137 " ---- FLUSHED stream of type %s\n",
1138 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1139 _g_dbus_debug_print_unlock ();
1143 g_assert (data->flushers != NULL);
1144 for (l = data->flushers; l != NULL; l = l->next)
1146 FlushData *f = l->data;
1148 f->error = error != NULL ? g_error_copy (error) : NULL;
1150 g_mutex_lock (f->mutex);
1151 g_cond_signal (f->cond);
1152 g_mutex_unlock (f->mutex);
1154 g_list_free (data->flushers);
1157 g_error_free (error);
1159 /* Make sure we tell folks that we don't have additional
1161 g_mutex_lock (data->worker->write_lock);
1162 data->worker->flush_pending = FALSE;
1163 g_mutex_unlock (data->worker->write_lock);
1165 /* OK, cool, finally kick off the next write */
1166 maybe_write_next_message (data->worker);
1168 _g_dbus_worker_unref (data->worker);
1172 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1174 message_written (GDBusWorker *worker,
1175 MessageToWriteData *message_data)
1181 /* first log the fact that we wrote a message */
1182 if (G_UNLIKELY (_g_dbus_debug_message ()))
1185 _g_dbus_debug_print_lock ();
1186 g_print ("========================================================================\n"
1187 "GDBus-debug:Message:\n"
1188 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1189 message_data->blob_size);
1190 s = g_dbus_message_print (message_data->message, 2);
1193 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1195 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1196 g_print ("%s\n", s);
1199 _g_dbus_debug_print_unlock ();
1202 /* then first wake up pending flushes and, if needed, flush the stream */
1204 g_mutex_lock (worker->write_lock);
1205 worker->write_num_messages_written += 1;
1206 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1208 FlushData *f = l->data;
1211 if (f->number_to_wait_for == worker->write_num_messages_written)
1213 flushers = g_list_append (flushers, f);
1214 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1217 if (flushers != NULL)
1219 worker->flush_pending = TRUE;
1221 g_mutex_unlock (worker->write_lock);
1223 if (flushers != NULL)
1225 FlushAsyncData *data;
1226 data = g_new0 (FlushAsyncData, 1);
1227 data->worker = _g_dbus_worker_ref (worker);
1228 data->flushers = flushers;
1229 /* flush the stream before writing the next message */
1230 g_output_stream_flush_async (g_io_stream_get_output_stream (worker->stream),
1232 worker->cancellable,
1238 /* kick off the next write! */
1239 maybe_write_next_message (worker);
1243 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1245 write_message_cb (GObject *source_object,
1249 MessageToWriteData *data = user_data;
1252 g_mutex_lock (data->worker->write_lock);
1253 data->worker->num_writes_pending -= 1;
1254 g_mutex_unlock (data->worker->write_lock);
1257 if (!write_message_finish (res, &error))
1260 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1261 g_error_free (error);
1264 /* this function will also kick of the next write (it might need to
1265 * flush so writing the next message might happen much later
1268 message_written (data->worker, data);
1270 message_to_write_data_free (data);
1273 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1275 maybe_write_next_message (GDBusWorker *worker)
1277 MessageToWriteData *data;
1281 g_mutex_lock (worker->write_lock);
1282 data = g_queue_pop_head (worker->write_queue);
1284 worker->num_writes_pending += 1;
1285 g_mutex_unlock (worker->write_lock);
1287 /* Note that write_lock is only used for protecting the @write_queue
1288 * and @num_writes_pending fields of the GDBusWorker struct ... which we
1289 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1291 * Therefore, it's fine to drop it here when calling back into user
1292 * code and then writing the message out onto the GIOStream since this
1293 * function only runs on the worker thread.
1297 GDBusMessage *old_message;
1299 gsize new_blob_size;
1302 old_message = data->message;
1303 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1304 if (data->message == old_message)
1306 /* filters had no effect - do nothing */
1308 else if (data->message == NULL)
1310 /* filters dropped message */
1311 g_mutex_lock (worker->write_lock);
1312 worker->num_writes_pending -= 1;
1313 g_mutex_unlock (worker->write_lock);
1314 message_to_write_data_free (data);
1319 /* filters altered the message -> reencode */
1321 new_blob = g_dbus_message_to_blob (data->message,
1323 worker->capabilities,
1325 if (new_blob == NULL)
1327 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1328 * the old message instead
1330 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1331 g_dbus_message_get_serial (data->message),
1333 g_error_free (error);
1337 g_free (data->blob);
1338 data->blob = (gchar *) new_blob;
1339 data->blob_size = new_blob_size;
1343 write_message_async (worker,
1350 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1352 write_message_in_idle_cb (gpointer user_data)
1354 GDBusWorker *worker = user_data;
1355 if (worker->num_writes_pending == 0 && !worker->flush_pending)
1356 maybe_write_next_message (worker);
1360 /* ---------------------------------------------------------------------------------------------------- */
1362 /* can be called from any thread - steals blob */
1364 _g_dbus_worker_send_message (GDBusWorker *worker,
1365 GDBusMessage *message,
1369 MessageToWriteData *data;
1371 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1372 g_return_if_fail (blob != NULL);
1373 g_return_if_fail (blob_len > 16);
1375 data = g_new0 (MessageToWriteData, 1);
1376 data->worker = _g_dbus_worker_ref (worker);
1377 data->message = g_object_ref (message);
1378 data->blob = blob; /* steal! */
1379 data->blob_size = blob_len;
1381 g_mutex_lock (worker->write_lock);
1382 g_queue_push_tail (worker->write_queue, data);
1383 if (worker->num_writes_pending == 0)
1385 GSource *idle_source;
1386 idle_source = g_idle_source_new ();
1387 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1388 g_source_set_callback (idle_source,
1389 write_message_in_idle_cb,
1390 _g_dbus_worker_ref (worker),
1391 (GDestroyNotify) _g_dbus_worker_unref);
1392 g_source_attach (idle_source, shared_thread_data->context);
1393 g_source_unref (idle_source);
1395 g_mutex_unlock (worker->write_lock);
1398 /* ---------------------------------------------------------------------------------------------------- */
1401 _g_dbus_worker_thread_begin_func (gpointer user_data)
1403 GDBusWorker *worker = user_data;
1405 worker->thread = g_thread_self ();
1408 _g_dbus_worker_do_read (worker);
1412 _g_dbus_worker_new (GIOStream *stream,
1413 GDBusCapabilityFlags capabilities,
1414 gboolean initially_frozen,
1415 GDBusWorkerMessageReceivedCallback message_received_callback,
1416 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1417 GDBusWorkerDisconnectedCallback disconnected_callback,
1420 GDBusWorker *worker;
1422 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1423 g_return_val_if_fail (message_received_callback != NULL, NULL);
1424 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1425 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1427 worker = g_new0 (GDBusWorker, 1);
1428 worker->ref_count = 1;
1430 worker->read_lock = g_mutex_new ();
1431 worker->message_received_callback = message_received_callback;
1432 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1433 worker->disconnected_callback = disconnected_callback;
1434 worker->user_data = user_data;
1435 worker->stream = g_object_ref (stream);
1436 worker->capabilities = capabilities;
1437 worker->cancellable = g_cancellable_new ();
1438 worker->flush_pending = FALSE;
1440 worker->frozen = initially_frozen;
1441 worker->received_messages_while_frozen = g_queue_new ();
1443 worker->write_lock = g_mutex_new ();
1444 worker->write_queue = g_queue_new ();
1446 if (G_IS_SOCKET_CONNECTION (worker->stream))
1447 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1449 _g_dbus_shared_thread_ref (_g_dbus_worker_thread_begin_func, worker);
1454 /* ---------------------------------------------------------------------------------------------------- */
1456 /* This can be called from any thread - frees worker. Note that
1457 * callbacks might still happen if called from another thread than the
1458 * worker - use your own synchronization primitive in the callbacks.
1461 _g_dbus_worker_stop (GDBusWorker *worker)
1463 worker->stopped = TRUE;
1464 g_cancellable_cancel (worker->cancellable);
1465 _g_dbus_worker_unref (worker);
1468 /* ---------------------------------------------------------------------------------------------------- */
1470 /* can be called from any thread (except the worker thread) - blocks
1471 * calling thread until all queued outgoing messages are written and
1472 * the transport has been flushed
1475 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1476 GCancellable *cancellable,
1485 /* if the queue is empty, there's nothing to wait for */
1486 g_mutex_lock (worker->write_lock);
1487 if (g_queue_get_length (worker->write_queue) > 0)
1489 data = g_new0 (FlushData, 1);
1490 data->mutex = g_mutex_new ();
1491 data->cond = g_cond_new ();
1492 data->number_to_wait_for = worker->write_num_messages_written + g_queue_get_length (worker->write_queue);
1493 g_mutex_lock (data->mutex);
1494 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, data);
1496 g_mutex_unlock (worker->write_lock);
1500 g_cond_wait (data->cond, data->mutex);
1501 g_mutex_unlock (data->mutex);
1503 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1504 g_cond_free (data->cond);
1505 g_mutex_free (data->mutex);
1506 if (data->error != NULL)
1509 g_propagate_error (error, data->error);
1517 /* ---------------------------------------------------------------------------------------------------- */
1519 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1520 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1521 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1522 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1523 #define G_DBUS_DEBUG_CALL (1<<4)
1524 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1525 #define G_DBUS_DEBUG_INCOMING (1<<6)
1526 #define G_DBUS_DEBUG_RETURN (1<<7)
1527 #define G_DBUS_DEBUG_EMISSION (1<<8)
1528 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1530 static gint _gdbus_debug_flags = 0;
1533 _g_dbus_debug_authentication (void)
1535 _g_dbus_initialize ();
1536 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1540 _g_dbus_debug_transport (void)
1542 _g_dbus_initialize ();
1543 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1547 _g_dbus_debug_message (void)
1549 _g_dbus_initialize ();
1550 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1554 _g_dbus_debug_payload (void)
1556 _g_dbus_initialize ();
1557 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1561 _g_dbus_debug_call (void)
1563 _g_dbus_initialize ();
1564 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1568 _g_dbus_debug_signal (void)
1570 _g_dbus_initialize ();
1571 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1575 _g_dbus_debug_incoming (void)
1577 _g_dbus_initialize ();
1578 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1582 _g_dbus_debug_return (void)
1584 _g_dbus_initialize ();
1585 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1589 _g_dbus_debug_emission (void)
1591 _g_dbus_initialize ();
1592 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1596 _g_dbus_debug_address (void)
1598 _g_dbus_initialize ();
1599 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1602 G_LOCK_DEFINE_STATIC (print_lock);
1605 _g_dbus_debug_print_lock (void)
1607 G_LOCK (print_lock);
1611 _g_dbus_debug_print_unlock (void)
1613 G_UNLOCK (print_lock);
1617 * _g_dbus_initialize:
1619 * Does various one-time init things such as
1621 * - registering the G_DBUS_ERROR error domain
1622 * - parses the G_DBUS_DEBUG environment variable
1625 _g_dbus_initialize (void)
1627 static volatile gsize initialized = 0;
1629 if (g_once_init_enter (&initialized))
1631 volatile GQuark g_dbus_error_domain;
1634 g_dbus_error_domain = G_DBUS_ERROR;
1635 (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1637 debug = g_getenv ("G_DBUS_DEBUG");
1640 const GDebugKey keys[] = {
1641 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1642 { "transport", G_DBUS_DEBUG_TRANSPORT },
1643 { "message", G_DBUS_DEBUG_MESSAGE },
1644 { "payload", G_DBUS_DEBUG_PAYLOAD },
1645 { "call", G_DBUS_DEBUG_CALL },
1646 { "signal", G_DBUS_DEBUG_SIGNAL },
1647 { "incoming", G_DBUS_DEBUG_INCOMING },
1648 { "return", G_DBUS_DEBUG_RETURN },
1649 { "emission", G_DBUS_DEBUG_EMISSION },
1650 { "address", G_DBUS_DEBUG_ADDRESS }
1653 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1654 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1655 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1658 g_once_init_leave (&initialized, 1);
1662 /* ---------------------------------------------------------------------------------------------------- */
1665 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1667 const GVariantType *arg_types[256];
1671 for (n = 0; args[n] != NULL; n++)
1673 /* DBus places a hard limit of 255 on signature length.
1674 * therefore number of args must be less than 256.
1678 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1680 if G_UNLIKELY (arg_types[n] == NULL)
1686 return g_variant_type_new_tuple (arg_types, n);
1689 /* ---------------------------------------------------------------------------------------------------- */
1693 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1696 _g_dbus_win32_get_user_sid (void)
1700 DWORD token_information_len;
1707 h = INVALID_HANDLE_VALUE;
1709 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
1711 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
1715 /* Get length of buffer */
1716 token_information_len = 0;
1717 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
1719 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1721 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1725 user = g_malloc (token_information_len);
1726 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
1728 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1732 psid = user->User.Sid;
1733 if (!IsValidSid (psid))
1735 g_warning ("Invalid SID");
1739 if (!ConvertSidToStringSidA (psid, &sid))
1741 g_warning ("Invalid SID");
1745 ret = g_strdup (sid);
1750 if (h != INVALID_HANDLE_VALUE)
1756 /* ---------------------------------------------------------------------------------------------------- */
1759 _g_dbus_get_machine_id (GError **error)
1762 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
1764 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
1769 g_prefix_error (error, _("Unable to load /var/lib/dbus/machine-id: "));
1773 /* TODO: validate value */
1779 /* ---------------------------------------------------------------------------------------------------- */
1782 _g_dbus_enum_to_string (GType enum_type, gint value)
1786 GEnumValue *enum_value;
1788 klass = g_type_class_ref (enum_type);
1789 enum_value = g_enum_get_value (klass, value);
1790 if (enum_value != NULL)
1791 ret = g_strdup (enum_value->value_nick);
1793 ret = g_strdup_printf ("unknown (value %d)", value);
1794 g_type_class_unref (klass);
1798 /* ---------------------------------------------------------------------------------------------------- */
1801 write_message_print_transport_debug (gssize bytes_written,
1802 MessageToWriteData *data)
1804 if (G_LIKELY (!_g_dbus_debug_transport ()))
1807 _g_dbus_debug_print_lock ();
1808 g_print ("========================================================================\n"
1809 "GDBus-debug:Transport:\n"
1810 " >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1811 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
1813 g_dbus_message_get_serial (data->message),
1815 data->total_written,
1816 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1817 _g_dbus_debug_print_unlock ();
1822 /* ---------------------------------------------------------------------------------------------------- */
1825 read_message_print_transport_debug (gssize bytes_read,
1826 GDBusWorker *worker)
1830 gint32 message_length;
1832 if (G_LIKELY (!_g_dbus_debug_transport ()))
1835 size = bytes_read + worker->read_buffer_cur_size;
1839 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
1842 switch (worker->read_buffer[0])
1846 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
1850 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
1853 /* an error will be set elsewhere if this happens */
1858 _g_dbus_debug_print_lock ();
1859 g_print ("========================================================================\n"
1860 "GDBus-debug:Transport:\n"
1861 " <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1862 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
1866 worker->read_buffer_cur_size,
1867 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
1868 _g_dbus_debug_print_unlock ();
1873 /* ---------------------------------------------------------------------------------------------------- */
1876 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
1877 GValue *return_accu,
1878 const GValue *handler_return,
1881 gboolean continue_emission;
1882 gboolean signal_return;
1884 signal_return = g_value_get_boolean (handler_return);
1885 g_value_set_boolean (return_accu, signal_return);
1886 continue_emission = signal_return;
1888 return continue_emission;