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 static gboolean _g_dbus_worker_do_initial_read (gpointer data);
60 /* ---------------------------------------------------------------------------------------------------- */
63 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
68 ret = g_string_new (NULL);
70 for (n = 0; n < len; n += 16)
72 g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
74 for (m = n; m < n + 16; m++)
76 if (m > n && (m%4) == 0)
77 g_string_append_c (ret, ' ');
79 g_string_append_printf (ret, "%02x ", (guchar) data[m]);
81 g_string_append (ret, " ");
84 g_string_append (ret, " ");
86 for (m = n; m < len && m < n + 16; m++)
87 g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
89 g_string_append_c (ret, '\n');
92 return g_string_free (ret, FALSE);
95 /* ---------------------------------------------------------------------------------------------------- */
97 /* Unfortunately ancillary messages are discarded when reading from a
98 * socket using the GSocketInputStream abstraction. So we provide a
99 * very GInputStream-ish API that uses GSocket in this case (very
100 * similar to GSocketInputStream).
106 GCancellable *cancellable;
111 GSocketControlMessage ***messages;
114 GSimpleAsyncResult *simple;
116 gboolean from_mainloop;
117 } ReadWithControlData;
120 read_with_control_data_free (ReadWithControlData *data)
122 g_object_unref (data->socket);
123 if (data->cancellable != NULL)
124 g_object_unref (data->cancellable);
125 g_object_unref (data->simple);
130 _g_socket_read_with_control_messages_ready (GSocket *socket,
131 GIOCondition condition,
134 ReadWithControlData *data = user_data;
140 vector.buffer = data->buffer;
141 vector.size = data->count;
142 result = g_socket_receive_message (data->socket,
153 g_simple_async_result_set_op_res_gssize (data->simple, result);
157 g_assert (error != NULL);
158 g_simple_async_result_take_error (data->simple, error);
161 if (data->from_mainloop)
162 g_simple_async_result_complete (data->simple);
164 g_simple_async_result_complete_in_idle (data->simple);
170 _g_socket_read_with_control_messages (GSocket *socket,
173 GSocketControlMessage ***messages,
176 GCancellable *cancellable,
177 GAsyncReadyCallback callback,
180 ReadWithControlData *data;
182 data = g_new0 (ReadWithControlData, 1);
183 data->socket = g_object_ref (socket);
184 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
185 data->buffer = buffer;
187 data->messages = messages;
188 data->num_messages = num_messages;
190 data->simple = g_simple_async_result_new (G_OBJECT (socket),
193 _g_socket_read_with_control_messages);
195 if (!g_socket_condition_check (socket, G_IO_IN))
198 data->from_mainloop = TRUE;
199 source = g_socket_create_source (data->socket,
200 G_IO_IN | G_IO_HUP | G_IO_ERR,
202 g_source_set_callback (source,
203 (GSourceFunc) _g_socket_read_with_control_messages_ready,
205 (GDestroyNotify) read_with_control_data_free);
206 g_source_attach (source, g_main_context_get_thread_default ());
207 g_source_unref (source);
211 _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
212 read_with_control_data_free (data);
217 _g_socket_read_with_control_messages_finish (GSocket *socket,
218 GAsyncResult *result,
221 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
223 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
224 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
226 if (g_simple_async_result_propagate_error (simple, error))
229 return g_simple_async_result_get_op_res_gssize (simple);
232 /* ---------------------------------------------------------------------------------------------------- */
234 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
236 static GPtrArray *ensured_classes = NULL;
239 ensure_type (GType gtype)
241 g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
245 release_required_types (void)
247 g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
248 g_ptr_array_unref (ensured_classes);
249 ensured_classes = NULL;
253 ensure_required_types (void)
255 g_assert (ensured_classes == NULL);
256 ensured_classes = g_ptr_array_new ();
257 ensure_type (G_TYPE_SIMPLE_ASYNC_RESULT);
258 ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
260 /* ---------------------------------------------------------------------------------------------------- */
264 volatile gint refcount;
266 GMainContext *context;
271 gdbus_shared_thread_func (gpointer user_data)
273 SharedThreadData *data = user_data;
275 g_main_context_push_thread_default (data->context);
276 g_main_loop_run (data->loop);
277 g_main_context_pop_thread_default (data->context);
279 release_required_types ();
284 /* ---------------------------------------------------------------------------------------------------- */
286 static SharedThreadData *
287 _g_dbus_shared_thread_ref (void)
289 static gsize shared_thread_data = 0;
290 GError *error = NULL;
291 SharedThreadData *ret;
293 if (g_once_init_enter (&shared_thread_data))
295 SharedThreadData *data;
297 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
298 ensure_required_types ();
300 data = g_new0 (SharedThreadData, 1);
303 data->context = g_main_context_new ();
304 data->loop = g_main_loop_new (data->context, FALSE);
305 data->thread = g_thread_create (gdbus_shared_thread_func,
309 g_assert_no_error (error);
310 /* We can cast between gsize and gpointer safely */
311 g_once_init_leave (&shared_thread_data, (gsize) data);
314 ret = (SharedThreadData*) shared_thread_data;
315 g_atomic_int_inc (&ret->refcount);
320 _g_dbus_shared_thread_unref (SharedThreadData *data)
322 /* TODO: actually destroy the shared thread here */
324 g_assert (data != NULL);
325 if (g_atomic_int_dec_and_test (&data->refcount))
327 g_main_loop_quit (data->loop);
328 //g_thread_join (data->thread);
329 g_main_loop_unref (data->loop);
330 g_main_context_unref (data->context);
335 /* ---------------------------------------------------------------------------------------------------- */
339 volatile gint ref_count;
341 SharedThreadData *shared_thread_data;
345 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
346 * only affects messages received from the other peer (since GDBusServer is the
347 * only user) - we might want it to affect messages sent to the other peer too?
350 GDBusCapabilityFlags capabilities;
351 GQueue *received_messages_while_frozen;
354 GCancellable *cancellable;
355 GDBusWorkerMessageReceivedCallback message_received_callback;
356 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
357 GDBusWorkerDisconnectedCallback disconnected_callback;
360 /* if not NULL, stream is GSocketConnection */
363 /* used for reading */
366 gsize read_buffer_allocated_size;
367 gsize read_buffer_cur_size;
368 gsize read_buffer_bytes_wanted;
369 GUnixFDList *read_fd_list;
370 GSocketControlMessage **read_ancillary_messages;
371 gint read_num_ancillary_messages;
373 /* TRUE if an async write or flush is pending.
374 * Only the worker thread may change its value, and only with the write_lock.
375 * Other threads may read its value when holding the write_lock.
376 * The worker thread may read its value at any time.
378 gboolean output_pending;
379 /* used for writing */
382 guint64 write_num_messages_written;
383 GList *write_pending_flushes;
386 /* ---------------------------------------------------------------------------------------------------- */
392 guint64 number_to_wait_for;
396 struct _MessageToWriteData ;
397 typedef struct _MessageToWriteData MessageToWriteData;
399 static void message_to_write_data_free (MessageToWriteData *data);
401 static void read_message_print_transport_debug (gssize bytes_read,
402 GDBusWorker *worker);
404 static void write_message_print_transport_debug (gssize bytes_written,
405 MessageToWriteData *data);
407 /* ---------------------------------------------------------------------------------------------------- */
410 _g_dbus_worker_ref (GDBusWorker *worker)
412 g_atomic_int_inc (&worker->ref_count);
417 _g_dbus_worker_unref (GDBusWorker *worker)
419 if (g_atomic_int_dec_and_test (&worker->ref_count))
421 g_assert (worker->write_pending_flushes == NULL);
423 _g_dbus_shared_thread_unref (worker->shared_thread_data);
425 g_object_unref (worker->stream);
427 g_mutex_free (worker->read_lock);
428 g_object_unref (worker->cancellable);
429 if (worker->read_fd_list != NULL)
430 g_object_unref (worker->read_fd_list);
432 g_queue_foreach (worker->received_messages_while_frozen, (GFunc) g_object_unref, NULL);
433 g_queue_free (worker->received_messages_while_frozen);
435 g_mutex_free (worker->write_lock);
436 g_queue_foreach (worker->write_queue, (GFunc) message_to_write_data_free, NULL);
437 g_queue_free (worker->write_queue);
439 g_free (worker->read_buffer);
446 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
447 gboolean remote_peer_vanished,
450 if (!worker->stopped)
451 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
455 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
456 GDBusMessage *message)
458 if (!worker->stopped)
459 worker->message_received_callback (worker, message, worker->user_data);
462 static GDBusMessage *
463 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
464 GDBusMessage *message)
467 if (!worker->stopped)
468 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
474 /* can only be called from private thread with read-lock held - takes ownership of @message */
476 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
477 GDBusMessage *message)
479 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
482 g_queue_push_tail (worker->received_messages_while_frozen, message);
486 /* not frozen, nor anything in queue */
487 _g_dbus_worker_emit_message_received (worker, message);
488 g_object_unref (message);
492 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
494 unfreeze_in_idle_cb (gpointer user_data)
496 GDBusWorker *worker = user_data;
497 GDBusMessage *message;
499 g_mutex_lock (worker->read_lock);
502 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
504 _g_dbus_worker_emit_message_received (worker, message);
505 g_object_unref (message);
507 worker->frozen = FALSE;
511 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
513 g_mutex_unlock (worker->read_lock);
517 /* can be called from any thread */
519 _g_dbus_worker_unfreeze (GDBusWorker *worker)
521 GSource *idle_source;
522 idle_source = g_idle_source_new ();
523 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
524 g_source_set_callback (idle_source,
526 _g_dbus_worker_ref (worker),
527 (GDestroyNotify) _g_dbus_worker_unref);
528 g_source_attach (idle_source, worker->shared_thread_data->context);
529 g_source_unref (idle_source);
532 /* ---------------------------------------------------------------------------------------------------- */
534 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
536 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
538 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
542 GDBusWorker *worker = user_data;
546 g_mutex_lock (worker->read_lock);
548 /* If already stopped, don't even process the reply */
553 if (worker->socket == NULL)
554 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
558 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
561 if (worker->read_num_ancillary_messages > 0)
564 for (n = 0; n < worker->read_num_ancillary_messages; n++)
566 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
572 else if (G_IS_UNIX_FD_MESSAGE (control_message))
574 GUnixFDMessage *fd_message;
578 fd_message = G_UNIX_FD_MESSAGE (control_message);
579 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
580 if (worker->read_fd_list == NULL)
582 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
587 for (n = 0; n < num_fds; n++)
589 /* TODO: really want a append_steal() */
590 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
596 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
608 "Unexpected ancillary message of type %s received from peer",
609 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
610 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
611 g_error_free (error);
612 g_object_unref (control_message);
614 while (n < worker->read_num_ancillary_messages)
615 g_object_unref (worker->read_ancillary_messages[n++]);
616 g_free (worker->read_ancillary_messages);
620 g_object_unref (control_message);
622 g_free (worker->read_ancillary_messages);
625 if (bytes_read == -1)
627 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
628 g_error_free (error);
633 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
635 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
636 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
637 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
638 G_IO_IN | G_IO_OUT | G_IO_HUP),
643 /* TODO: hmm, hmm... */
649 "Underlying GIOStream returned 0 bytes on an async read");
650 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
651 g_error_free (error);
655 read_message_print_transport_debug (bytes_read, worker);
657 worker->read_buffer_cur_size += bytes_read;
658 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
660 /* OK, got what we asked for! */
661 if (worker->read_buffer_bytes_wanted == 16)
664 /* OK, got the header - determine how many more bytes are needed */
666 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
669 if (message_len == -1)
671 g_warning ("_g_dbus_worker_do_read_cb: error determing bytes needed: %s", error->message);
672 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
673 g_error_free (error);
677 worker->read_buffer_bytes_wanted = message_len;
678 _g_dbus_worker_do_read_unlocked (worker);
682 GDBusMessage *message;
685 /* TODO: use connection->priv->auth to decode the message */
687 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
688 worker->read_buffer_cur_size,
689 worker->capabilities,
694 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
695 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
697 "The payload is as follows:\n"
699 worker->read_buffer_cur_size,
703 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
704 g_error_free (error);
709 if (worker->read_fd_list != NULL)
711 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
712 g_object_unref (worker->read_fd_list);
713 worker->read_fd_list = NULL;
717 if (G_UNLIKELY (_g_dbus_debug_message ()))
720 _g_dbus_debug_print_lock ();
721 g_print ("========================================================================\n"
722 "GDBus-debug:Message:\n"
723 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
724 worker->read_buffer_cur_size);
725 s = g_dbus_message_print (message, 2);
728 if (G_UNLIKELY (_g_dbus_debug_payload ()))
730 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
734 _g_dbus_debug_print_unlock ();
737 /* yay, got a message, go deliver it */
738 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
740 /* start reading another message! */
741 worker->read_buffer_bytes_wanted = 0;
742 worker->read_buffer_cur_size = 0;
743 _g_dbus_worker_do_read_unlocked (worker);
748 /* didn't get all the bytes we requested - so repeat the request... */
749 _g_dbus_worker_do_read_unlocked (worker);
753 g_mutex_unlock (worker->read_lock);
755 /* gives up the reference acquired when calling g_input_stream_read_async() */
756 _g_dbus_worker_unref (worker);
759 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
761 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
763 /* if bytes_wanted is zero, it means start reading a message */
764 if (worker->read_buffer_bytes_wanted == 0)
766 worker->read_buffer_cur_size = 0;
767 worker->read_buffer_bytes_wanted = 16;
770 /* ensure we have a (big enough) buffer */
771 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
773 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
774 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
775 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
778 if (worker->socket == NULL)
779 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
780 worker->read_buffer + worker->read_buffer_cur_size,
781 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
784 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
785 _g_dbus_worker_ref (worker));
788 worker->read_ancillary_messages = NULL;
789 worker->read_num_ancillary_messages = 0;
790 _g_socket_read_with_control_messages (worker->socket,
791 worker->read_buffer + worker->read_buffer_cur_size,
792 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
793 &worker->read_ancillary_messages,
794 &worker->read_num_ancillary_messages,
797 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
798 _g_dbus_worker_ref (worker));
802 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
804 _g_dbus_worker_do_initial_read (gpointer data)
806 GDBusWorker *worker = data;
807 g_mutex_lock (worker->read_lock);
808 _g_dbus_worker_do_read_unlocked (worker);
809 g_mutex_unlock (worker->read_lock);
813 /* ---------------------------------------------------------------------------------------------------- */
815 struct _MessageToWriteData
818 GDBusMessage *message;
823 GSimpleAsyncResult *simple;
828 message_to_write_data_free (MessageToWriteData *data)
830 _g_dbus_worker_unref (data->worker);
832 g_object_unref (data->message);
837 /* ---------------------------------------------------------------------------------------------------- */
839 static void write_message_continue_writing (MessageToWriteData *data);
841 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
843 write_message_async_cb (GObject *source_object,
847 MessageToWriteData *data = user_data;
848 GSimpleAsyncResult *simple;
849 gssize bytes_written;
852 /* Note: we can't access data->simple after calling g_async_result_complete () because the
853 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
855 simple = data->simple;
858 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
861 if (bytes_written == -1)
863 g_simple_async_result_take_error (simple, error);
864 g_simple_async_result_complete (simple);
865 g_object_unref (simple);
868 g_assert (bytes_written > 0); /* zero is never returned */
870 write_message_print_transport_debug (bytes_written, data);
872 data->total_written += bytes_written;
873 g_assert (data->total_written <= data->blob_size);
874 if (data->total_written == data->blob_size)
876 g_simple_async_result_complete (simple);
877 g_object_unref (simple);
881 write_message_continue_writing (data);
887 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
889 on_socket_ready (GSocket *socket,
890 GIOCondition condition,
893 MessageToWriteData *data = user_data;
894 write_message_continue_writing (data);
895 return FALSE; /* remove source */
898 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
900 write_message_continue_writing (MessageToWriteData *data)
902 GOutputStream *ostream;
903 GSimpleAsyncResult *simple;
905 GUnixFDList *fd_list;
908 /* Note: we can't access data->simple after calling g_async_result_complete () because the
909 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
911 simple = data->simple;
913 ostream = g_io_stream_get_output_stream (data->worker->stream);
915 fd_list = g_dbus_message_get_unix_fd_list (data->message);
918 g_assert (!g_output_stream_has_pending (ostream));
919 g_assert_cmpint (data->total_written, <, data->blob_size);
925 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
927 GOutputVector vector;
928 GSocketControlMessage *control_message;
929 gssize bytes_written;
932 vector.buffer = data->blob;
933 vector.size = data->blob_size;
935 control_message = NULL;
936 if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
938 if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
940 g_simple_async_result_set_error (simple,
943 "Tried sending a file descriptor but remote peer does not support this capability");
944 g_simple_async_result_complete (simple);
945 g_object_unref (simple);
948 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
952 bytes_written = g_socket_send_message (data->worker->socket,
956 control_message != NULL ? &control_message : NULL,
957 control_message != NULL ? 1 : 0,
959 data->worker->cancellable,
961 if (control_message != NULL)
962 g_object_unref (control_message);
964 if (bytes_written == -1)
966 /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
967 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
970 source = g_socket_create_source (data->worker->socket,
971 G_IO_OUT | G_IO_HUP | G_IO_ERR,
972 data->worker->cancellable);
973 g_source_set_callback (source,
974 (GSourceFunc) on_socket_ready,
976 NULL); /* GDestroyNotify */
977 g_source_attach (source, g_main_context_get_thread_default ());
978 g_source_unref (source);
979 g_error_free (error);
982 g_simple_async_result_take_error (simple, error);
983 g_simple_async_result_complete (simple);
984 g_object_unref (simple);
987 g_assert (bytes_written > 0); /* zero is never returned */
989 write_message_print_transport_debug (bytes_written, data);
991 data->total_written += bytes_written;
992 g_assert (data->total_written <= data->blob_size);
993 if (data->total_written == data->blob_size)
995 g_simple_async_result_complete (simple);
996 g_object_unref (simple);
1000 write_message_continue_writing (data);
1006 if (fd_list != NULL)
1008 g_simple_async_result_set_error (simple,
1011 "Tried sending a file descriptor on unsupported stream of type %s",
1012 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1013 g_simple_async_result_complete (simple);
1014 g_object_unref (simple);
1019 g_output_stream_write_async (ostream,
1020 (const gchar *) data->blob + data->total_written,
1021 data->blob_size - data->total_written,
1023 data->worker->cancellable,
1024 write_message_async_cb,
1031 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1033 write_message_async (GDBusWorker *worker,
1034 MessageToWriteData *data,
1035 GAsyncReadyCallback callback,
1038 data->simple = g_simple_async_result_new (NULL,
1041 write_message_async);
1042 data->total_written = 0;
1043 write_message_continue_writing (data);
1046 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1048 write_message_finish (GAsyncResult *res,
1051 g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1052 if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1057 /* ---------------------------------------------------------------------------------------------------- */
1059 static void maybe_write_next_message (GDBusWorker *worker);
1063 GDBusWorker *worker;
1067 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1069 ostream_flush_cb (GObject *source_object,
1073 FlushAsyncData *data = user_data;
1078 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1084 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1086 _g_dbus_debug_print_lock ();
1087 g_print ("========================================================================\n"
1088 "GDBus-debug:Transport:\n"
1089 " ---- FLUSHED stream of type %s\n",
1090 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1091 _g_dbus_debug_print_unlock ();
1095 g_assert (data->flushers != NULL);
1096 for (l = data->flushers; l != NULL; l = l->next)
1098 FlushData *f = l->data;
1100 f->error = error != NULL ? g_error_copy (error) : NULL;
1102 g_mutex_lock (f->mutex);
1103 g_cond_signal (f->cond);
1104 g_mutex_unlock (f->mutex);
1106 g_list_free (data->flushers);
1109 g_error_free (error);
1111 /* Make sure we tell folks that we don't have additional
1113 g_mutex_lock (data->worker->write_lock);
1114 g_assert (data->worker->output_pending);
1115 data->worker->output_pending = FALSE;
1116 g_mutex_unlock (data->worker->write_lock);
1118 /* OK, cool, finally kick off the next write */
1119 maybe_write_next_message (data->worker);
1121 _g_dbus_worker_unref (data->worker);
1125 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1127 message_written (GDBusWorker *worker,
1128 MessageToWriteData *message_data)
1134 /* first log the fact that we wrote a message */
1135 if (G_UNLIKELY (_g_dbus_debug_message ()))
1138 _g_dbus_debug_print_lock ();
1139 g_print ("========================================================================\n"
1140 "GDBus-debug:Message:\n"
1141 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1142 message_data->blob_size);
1143 s = g_dbus_message_print (message_data->message, 2);
1146 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1148 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1149 g_print ("%s\n", s);
1152 _g_dbus_debug_print_unlock ();
1155 /* then first wake up pending flushes and, if needed, flush the stream */
1157 g_mutex_lock (worker->write_lock);
1158 worker->write_num_messages_written += 1;
1159 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1161 FlushData *f = l->data;
1164 if (f->number_to_wait_for == worker->write_num_messages_written)
1166 flushers = g_list_append (flushers, f);
1167 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1170 if (flushers != NULL)
1172 g_assert (!worker->output_pending);
1173 worker->output_pending = TRUE;
1175 g_mutex_unlock (worker->write_lock);
1177 if (flushers != NULL)
1179 FlushAsyncData *data;
1180 data = g_new0 (FlushAsyncData, 1);
1181 data->worker = _g_dbus_worker_ref (worker);
1182 data->flushers = flushers;
1183 /* flush the stream before writing the next message */
1184 g_output_stream_flush_async (g_io_stream_get_output_stream (worker->stream),
1186 worker->cancellable,
1192 /* kick off the next write! */
1193 maybe_write_next_message (worker);
1197 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1199 write_message_cb (GObject *source_object,
1203 MessageToWriteData *data = user_data;
1206 g_mutex_lock (data->worker->write_lock);
1207 g_assert (data->worker->output_pending);
1208 data->worker->output_pending = FALSE;
1209 g_mutex_unlock (data->worker->write_lock);
1212 if (!write_message_finish (res, &error))
1215 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1216 g_error_free (error);
1219 /* this function will also kick of the next write (it might need to
1220 * flush so writing the next message might happen much later
1223 message_written (data->worker, data);
1225 message_to_write_data_free (data);
1228 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1230 maybe_write_next_message (GDBusWorker *worker)
1232 MessageToWriteData *data;
1235 /* we mustn't try to write two things at once */
1236 g_assert (!worker->output_pending);
1238 g_mutex_lock (worker->write_lock);
1239 data = g_queue_pop_head (worker->write_queue);
1241 worker->output_pending = TRUE;
1242 g_mutex_unlock (worker->write_lock);
1244 /* Note that write_lock is only used for protecting the @write_queue
1245 * and @output_pending fields of the GDBusWorker struct ... which we
1246 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1248 * Therefore, it's fine to drop it here when calling back into user
1249 * code and then writing the message out onto the GIOStream since this
1250 * function only runs on the worker thread.
1254 GDBusMessage *old_message;
1256 gsize new_blob_size;
1259 old_message = data->message;
1260 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1261 if (data->message == old_message)
1263 /* filters had no effect - do nothing */
1265 else if (data->message == NULL)
1267 /* filters dropped message */
1268 g_mutex_lock (worker->write_lock);
1269 worker->output_pending = FALSE;
1270 g_mutex_unlock (worker->write_lock);
1271 message_to_write_data_free (data);
1276 /* filters altered the message -> reencode */
1278 new_blob = g_dbus_message_to_blob (data->message,
1280 worker->capabilities,
1282 if (new_blob == NULL)
1284 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1285 * the old message instead
1287 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1288 g_dbus_message_get_serial (data->message),
1290 g_error_free (error);
1294 g_free (data->blob);
1295 data->blob = (gchar *) new_blob;
1296 data->blob_size = new_blob_size;
1300 write_message_async (worker,
1307 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1309 write_message_in_idle_cb (gpointer user_data)
1311 GDBusWorker *worker = user_data;
1313 /* Because this is the worker thread, we can read this struct member
1314 * without holding the lock: no other thread ever modifies it.
1316 if (!worker->output_pending)
1317 maybe_write_next_message (worker);
1322 /* ---------------------------------------------------------------------------------------------------- */
1324 /* can be called from any thread - steals blob */
1326 _g_dbus_worker_send_message (GDBusWorker *worker,
1327 GDBusMessage *message,
1331 MessageToWriteData *data;
1333 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1334 g_return_if_fail (blob != NULL);
1335 g_return_if_fail (blob_len > 16);
1337 data = g_new0 (MessageToWriteData, 1);
1338 data->worker = _g_dbus_worker_ref (worker);
1339 data->message = g_object_ref (message);
1340 data->blob = blob; /* steal! */
1341 data->blob_size = blob_len;
1343 g_mutex_lock (worker->write_lock);
1344 g_queue_push_tail (worker->write_queue, data);
1345 if (!worker->output_pending)
1347 GSource *idle_source;
1348 idle_source = g_idle_source_new ();
1349 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1350 g_source_set_callback (idle_source,
1351 write_message_in_idle_cb,
1352 _g_dbus_worker_ref (worker),
1353 (GDestroyNotify) _g_dbus_worker_unref);
1354 g_source_attach (idle_source, worker->shared_thread_data->context);
1355 g_source_unref (idle_source);
1357 g_mutex_unlock (worker->write_lock);
1360 /* ---------------------------------------------------------------------------------------------------- */
1363 _g_dbus_worker_new (GIOStream *stream,
1364 GDBusCapabilityFlags capabilities,
1365 gboolean initially_frozen,
1366 GDBusWorkerMessageReceivedCallback message_received_callback,
1367 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1368 GDBusWorkerDisconnectedCallback disconnected_callback,
1371 GDBusWorker *worker;
1372 GSource *idle_source;
1374 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1375 g_return_val_if_fail (message_received_callback != NULL, NULL);
1376 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1377 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1379 worker = g_new0 (GDBusWorker, 1);
1380 worker->ref_count = 1;
1382 worker->read_lock = g_mutex_new ();
1383 worker->message_received_callback = message_received_callback;
1384 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1385 worker->disconnected_callback = disconnected_callback;
1386 worker->user_data = user_data;
1387 worker->stream = g_object_ref (stream);
1388 worker->capabilities = capabilities;
1389 worker->cancellable = g_cancellable_new ();
1390 worker->output_pending = FALSE;
1392 worker->frozen = initially_frozen;
1393 worker->received_messages_while_frozen = g_queue_new ();
1395 worker->write_lock = g_mutex_new ();
1396 worker->write_queue = g_queue_new ();
1398 if (G_IS_SOCKET_CONNECTION (worker->stream))
1399 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1401 worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1404 idle_source = g_idle_source_new ();
1405 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1406 g_source_set_callback (idle_source,
1407 _g_dbus_worker_do_initial_read,
1410 g_source_attach (idle_source, worker->shared_thread_data->context);
1411 g_source_unref (idle_source);
1416 /* ---------------------------------------------------------------------------------------------------- */
1418 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
1420 unref_in_idle_cb (gpointer user_data)
1422 GDBusWorker *worker = user_data;
1423 _g_dbus_worker_unref (worker);
1427 /* This can be called from any thread - frees worker. Note that
1428 * callbacks might still happen if called from another thread than the
1429 * worker - use your own synchronization primitive in the callbacks.
1432 _g_dbus_worker_stop (GDBusWorker *worker)
1434 GSource *idle_source;
1436 worker->stopped = TRUE;
1437 g_cancellable_cancel (worker->cancellable);
1439 idle_source = g_idle_source_new ();
1440 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1441 g_source_set_callback (idle_source,
1443 _g_dbus_worker_ref (worker),
1444 (GDestroyNotify) _g_dbus_worker_unref);
1445 g_source_attach (idle_source, worker->shared_thread_data->context);
1446 g_source_unref (idle_source);
1449 /* ---------------------------------------------------------------------------------------------------- */
1451 /* can be called from any thread (except the worker thread) - blocks
1452 * calling thread until all queued outgoing messages are written and
1453 * the transport has been flushed
1456 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1457 GCancellable *cancellable,
1466 /* if the queue is empty, there's nothing to wait for */
1467 g_mutex_lock (worker->write_lock);
1468 if (g_queue_get_length (worker->write_queue) > 0)
1470 data = g_new0 (FlushData, 1);
1471 data->mutex = g_mutex_new ();
1472 data->cond = g_cond_new ();
1473 data->number_to_wait_for = worker->write_num_messages_written + g_queue_get_length (worker->write_queue);
1474 g_mutex_lock (data->mutex);
1475 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, data);
1477 g_mutex_unlock (worker->write_lock);
1481 g_cond_wait (data->cond, data->mutex);
1482 g_mutex_unlock (data->mutex);
1484 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1485 g_cond_free (data->cond);
1486 g_mutex_free (data->mutex);
1487 if (data->error != NULL)
1490 g_propagate_error (error, data->error);
1498 /* ---------------------------------------------------------------------------------------------------- */
1500 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1501 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1502 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1503 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1504 #define G_DBUS_DEBUG_CALL (1<<4)
1505 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1506 #define G_DBUS_DEBUG_INCOMING (1<<6)
1507 #define G_DBUS_DEBUG_RETURN (1<<7)
1508 #define G_DBUS_DEBUG_EMISSION (1<<8)
1509 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1511 static gint _gdbus_debug_flags = 0;
1514 _g_dbus_debug_authentication (void)
1516 _g_dbus_initialize ();
1517 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1521 _g_dbus_debug_transport (void)
1523 _g_dbus_initialize ();
1524 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1528 _g_dbus_debug_message (void)
1530 _g_dbus_initialize ();
1531 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1535 _g_dbus_debug_payload (void)
1537 _g_dbus_initialize ();
1538 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1542 _g_dbus_debug_call (void)
1544 _g_dbus_initialize ();
1545 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1549 _g_dbus_debug_signal (void)
1551 _g_dbus_initialize ();
1552 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1556 _g_dbus_debug_incoming (void)
1558 _g_dbus_initialize ();
1559 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1563 _g_dbus_debug_return (void)
1565 _g_dbus_initialize ();
1566 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1570 _g_dbus_debug_emission (void)
1572 _g_dbus_initialize ();
1573 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1577 _g_dbus_debug_address (void)
1579 _g_dbus_initialize ();
1580 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1583 G_LOCK_DEFINE_STATIC (print_lock);
1586 _g_dbus_debug_print_lock (void)
1588 G_LOCK (print_lock);
1592 _g_dbus_debug_print_unlock (void)
1594 G_UNLOCK (print_lock);
1598 * _g_dbus_initialize:
1600 * Does various one-time init things such as
1602 * - registering the G_DBUS_ERROR error domain
1603 * - parses the G_DBUS_DEBUG environment variable
1606 _g_dbus_initialize (void)
1608 static volatile gsize initialized = 0;
1610 if (g_once_init_enter (&initialized))
1612 volatile GQuark g_dbus_error_domain;
1615 g_dbus_error_domain = G_DBUS_ERROR;
1616 (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1618 debug = g_getenv ("G_DBUS_DEBUG");
1621 const GDebugKey keys[] = {
1622 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1623 { "transport", G_DBUS_DEBUG_TRANSPORT },
1624 { "message", G_DBUS_DEBUG_MESSAGE },
1625 { "payload", G_DBUS_DEBUG_PAYLOAD },
1626 { "call", G_DBUS_DEBUG_CALL },
1627 { "signal", G_DBUS_DEBUG_SIGNAL },
1628 { "incoming", G_DBUS_DEBUG_INCOMING },
1629 { "return", G_DBUS_DEBUG_RETURN },
1630 { "emission", G_DBUS_DEBUG_EMISSION },
1631 { "address", G_DBUS_DEBUG_ADDRESS }
1634 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1635 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1636 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1639 g_once_init_leave (&initialized, 1);
1643 /* ---------------------------------------------------------------------------------------------------- */
1646 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1648 const GVariantType *arg_types[256];
1652 for (n = 0; args[n] != NULL; n++)
1654 /* DBus places a hard limit of 255 on signature length.
1655 * therefore number of args must be less than 256.
1659 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1661 if G_UNLIKELY (arg_types[n] == NULL)
1667 return g_variant_type_new_tuple (arg_types, n);
1670 /* ---------------------------------------------------------------------------------------------------- */
1674 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1677 _g_dbus_win32_get_user_sid (void)
1681 DWORD token_information_len;
1688 h = INVALID_HANDLE_VALUE;
1690 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
1692 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
1696 /* Get length of buffer */
1697 token_information_len = 0;
1698 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
1700 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1702 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1706 user = g_malloc (token_information_len);
1707 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
1709 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1713 psid = user->User.Sid;
1714 if (!IsValidSid (psid))
1716 g_warning ("Invalid SID");
1720 if (!ConvertSidToStringSidA (psid, &sid))
1722 g_warning ("Invalid SID");
1726 ret = g_strdup (sid);
1731 if (h != INVALID_HANDLE_VALUE)
1737 /* ---------------------------------------------------------------------------------------------------- */
1740 _g_dbus_get_machine_id (GError **error)
1743 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
1745 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
1750 g_prefix_error (error, _("Unable to load /var/lib/dbus/machine-id: "));
1754 /* TODO: validate value */
1760 /* ---------------------------------------------------------------------------------------------------- */
1763 _g_dbus_enum_to_string (GType enum_type, gint value)
1767 GEnumValue *enum_value;
1769 klass = g_type_class_ref (enum_type);
1770 enum_value = g_enum_get_value (klass, value);
1771 if (enum_value != NULL)
1772 ret = g_strdup (enum_value->value_nick);
1774 ret = g_strdup_printf ("unknown (value %d)", value);
1775 g_type_class_unref (klass);
1779 /* ---------------------------------------------------------------------------------------------------- */
1782 write_message_print_transport_debug (gssize bytes_written,
1783 MessageToWriteData *data)
1785 if (G_LIKELY (!_g_dbus_debug_transport ()))
1788 _g_dbus_debug_print_lock ();
1789 g_print ("========================================================================\n"
1790 "GDBus-debug:Transport:\n"
1791 " >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1792 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
1794 g_dbus_message_get_serial (data->message),
1796 data->total_written,
1797 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1798 _g_dbus_debug_print_unlock ();
1803 /* ---------------------------------------------------------------------------------------------------- */
1806 read_message_print_transport_debug (gssize bytes_read,
1807 GDBusWorker *worker)
1811 gint32 message_length;
1813 if (G_LIKELY (!_g_dbus_debug_transport ()))
1816 size = bytes_read + worker->read_buffer_cur_size;
1820 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
1823 switch (worker->read_buffer[0])
1827 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
1831 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
1834 /* an error will be set elsewhere if this happens */
1839 _g_dbus_debug_print_lock ();
1840 g_print ("========================================================================\n"
1841 "GDBus-debug:Transport:\n"
1842 " <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1843 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
1847 worker->read_buffer_cur_size,
1848 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
1849 _g_dbus_debug_print_unlock ();
1854 /* ---------------------------------------------------------------------------------------------------- */
1857 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
1858 GValue *return_accu,
1859 const GValue *handler_return,
1862 gboolean continue_emission;
1863 gboolean signal_return;
1865 signal_return = g_value_get_boolean (handler_return);
1866 g_value_set_boolean (return_accu, signal_return);
1867 continue_emission = signal_return;
1869 return continue_emission;