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 /* used for writing */
374 gint num_writes_pending;
377 guint64 write_num_messages_written;
378 GList *write_pending_flushes;
379 gboolean flush_pending;
382 /* ---------------------------------------------------------------------------------------------------- */
388 guint64 number_to_wait_for;
392 struct _MessageToWriteData ;
393 typedef struct _MessageToWriteData MessageToWriteData;
395 static void message_to_write_data_free (MessageToWriteData *data);
397 static void read_message_print_transport_debug (gssize bytes_read,
398 GDBusWorker *worker);
400 static void write_message_print_transport_debug (gssize bytes_written,
401 MessageToWriteData *data);
403 /* ---------------------------------------------------------------------------------------------------- */
406 _g_dbus_worker_ref (GDBusWorker *worker)
408 g_atomic_int_inc (&worker->ref_count);
413 _g_dbus_worker_unref (GDBusWorker *worker)
415 if (g_atomic_int_dec_and_test (&worker->ref_count))
417 g_assert (worker->write_pending_flushes == NULL);
419 _g_dbus_shared_thread_unref (worker->shared_thread_data);
421 g_object_unref (worker->stream);
423 g_mutex_free (worker->read_lock);
424 g_object_unref (worker->cancellable);
425 if (worker->read_fd_list != NULL)
426 g_object_unref (worker->read_fd_list);
428 g_queue_foreach (worker->received_messages_while_frozen, (GFunc) g_object_unref, NULL);
429 g_queue_free (worker->received_messages_while_frozen);
431 g_mutex_free (worker->write_lock);
432 g_queue_foreach (worker->write_queue, (GFunc) message_to_write_data_free, NULL);
433 g_queue_free (worker->write_queue);
435 g_free (worker->read_buffer);
442 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
443 gboolean remote_peer_vanished,
446 if (!worker->stopped)
447 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
451 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
452 GDBusMessage *message)
454 if (!worker->stopped)
455 worker->message_received_callback (worker, message, worker->user_data);
458 static GDBusMessage *
459 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
460 GDBusMessage *message)
463 if (!worker->stopped)
464 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
470 /* can only be called from private thread with read-lock held - takes ownership of @message */
472 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
473 GDBusMessage *message)
475 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
478 g_queue_push_tail (worker->received_messages_while_frozen, message);
482 /* not frozen, nor anything in queue */
483 _g_dbus_worker_emit_message_received (worker, message);
484 g_object_unref (message);
488 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
490 unfreeze_in_idle_cb (gpointer user_data)
492 GDBusWorker *worker = user_data;
493 GDBusMessage *message;
495 g_mutex_lock (worker->read_lock);
498 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
500 _g_dbus_worker_emit_message_received (worker, message);
501 g_object_unref (message);
503 worker->frozen = FALSE;
507 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
509 g_mutex_unlock (worker->read_lock);
513 /* can be called from any thread */
515 _g_dbus_worker_unfreeze (GDBusWorker *worker)
517 GSource *idle_source;
518 idle_source = g_idle_source_new ();
519 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
520 g_source_set_callback (idle_source,
522 _g_dbus_worker_ref (worker),
523 (GDestroyNotify) _g_dbus_worker_unref);
524 g_source_attach (idle_source, worker->shared_thread_data->context);
525 g_source_unref (idle_source);
528 /* ---------------------------------------------------------------------------------------------------- */
530 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
532 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
534 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
538 GDBusWorker *worker = user_data;
542 g_mutex_lock (worker->read_lock);
544 /* If already stopped, don't even process the reply */
549 if (worker->socket == NULL)
550 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
554 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
557 if (worker->read_num_ancillary_messages > 0)
560 for (n = 0; n < worker->read_num_ancillary_messages; n++)
562 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
568 else if (G_IS_UNIX_FD_MESSAGE (control_message))
570 GUnixFDMessage *fd_message;
574 fd_message = G_UNIX_FD_MESSAGE (control_message);
575 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
576 if (worker->read_fd_list == NULL)
578 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
583 for (n = 0; n < num_fds; n++)
585 /* TODO: really want a append_steal() */
586 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
592 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
604 "Unexpected ancillary message of type %s received from peer",
605 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
606 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
607 g_error_free (error);
608 g_object_unref (control_message);
610 while (n < worker->read_num_ancillary_messages)
611 g_object_unref (worker->read_ancillary_messages[n++]);
612 g_free (worker->read_ancillary_messages);
616 g_object_unref (control_message);
618 g_free (worker->read_ancillary_messages);
621 if (bytes_read == -1)
623 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
624 g_error_free (error);
629 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
631 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
632 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
633 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
634 G_IO_IN | G_IO_OUT | G_IO_HUP),
639 /* TODO: hmm, hmm... */
645 "Underlying GIOStream returned 0 bytes on an async read");
646 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
647 g_error_free (error);
651 read_message_print_transport_debug (bytes_read, worker);
653 worker->read_buffer_cur_size += bytes_read;
654 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
656 /* OK, got what we asked for! */
657 if (worker->read_buffer_bytes_wanted == 16)
660 /* OK, got the header - determine how many more bytes are needed */
662 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
665 if (message_len == -1)
667 g_warning ("_g_dbus_worker_do_read_cb: error determing bytes needed: %s", error->message);
668 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
669 g_error_free (error);
673 worker->read_buffer_bytes_wanted = message_len;
674 _g_dbus_worker_do_read_unlocked (worker);
678 GDBusMessage *message;
681 /* TODO: use connection->priv->auth to decode the message */
683 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
684 worker->read_buffer_cur_size,
685 worker->capabilities,
690 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
691 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
693 "The payload is as follows:\n"
695 worker->read_buffer_cur_size,
699 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
700 g_error_free (error);
705 if (worker->read_fd_list != NULL)
707 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
708 g_object_unref (worker->read_fd_list);
709 worker->read_fd_list = NULL;
713 if (G_UNLIKELY (_g_dbus_debug_message ()))
716 _g_dbus_debug_print_lock ();
717 g_print ("========================================================================\n"
718 "GDBus-debug:Message:\n"
719 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
720 worker->read_buffer_cur_size);
721 s = g_dbus_message_print (message, 2);
724 if (G_UNLIKELY (_g_dbus_debug_payload ()))
726 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
730 _g_dbus_debug_print_unlock ();
733 /* yay, got a message, go deliver it */
734 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
736 /* start reading another message! */
737 worker->read_buffer_bytes_wanted = 0;
738 worker->read_buffer_cur_size = 0;
739 _g_dbus_worker_do_read_unlocked (worker);
744 /* didn't get all the bytes we requested - so repeat the request... */
745 _g_dbus_worker_do_read_unlocked (worker);
749 g_mutex_unlock (worker->read_lock);
751 /* gives up the reference acquired when calling g_input_stream_read_async() */
752 _g_dbus_worker_unref (worker);
755 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
757 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
759 /* if bytes_wanted is zero, it means start reading a message */
760 if (worker->read_buffer_bytes_wanted == 0)
762 worker->read_buffer_cur_size = 0;
763 worker->read_buffer_bytes_wanted = 16;
766 /* ensure we have a (big enough) buffer */
767 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
769 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
770 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
771 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
774 if (worker->socket == NULL)
775 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
776 worker->read_buffer + worker->read_buffer_cur_size,
777 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
780 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
781 _g_dbus_worker_ref (worker));
784 worker->read_ancillary_messages = NULL;
785 worker->read_num_ancillary_messages = 0;
786 _g_socket_read_with_control_messages (worker->socket,
787 worker->read_buffer + worker->read_buffer_cur_size,
788 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
789 &worker->read_ancillary_messages,
790 &worker->read_num_ancillary_messages,
793 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
794 _g_dbus_worker_ref (worker));
798 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
800 _g_dbus_worker_do_initial_read (gpointer data)
802 GDBusWorker *worker = data;
803 g_mutex_lock (worker->read_lock);
804 _g_dbus_worker_do_read_unlocked (worker);
805 g_mutex_unlock (worker->read_lock);
809 /* ---------------------------------------------------------------------------------------------------- */
811 struct _MessageToWriteData
814 GDBusMessage *message;
819 GSimpleAsyncResult *simple;
824 message_to_write_data_free (MessageToWriteData *data)
826 _g_dbus_worker_unref (data->worker);
828 g_object_unref (data->message);
833 /* ---------------------------------------------------------------------------------------------------- */
835 static void write_message_continue_writing (MessageToWriteData *data);
837 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
839 write_message_async_cb (GObject *source_object,
843 MessageToWriteData *data = user_data;
844 GSimpleAsyncResult *simple;
845 gssize bytes_written;
848 /* Note: we can't access data->simple after calling g_async_result_complete () because the
849 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
851 simple = data->simple;
854 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
857 if (bytes_written == -1)
859 g_simple_async_result_take_error (simple, error);
860 g_simple_async_result_complete (simple);
861 g_object_unref (simple);
864 g_assert (bytes_written > 0); /* zero is never returned */
866 write_message_print_transport_debug (bytes_written, data);
868 data->total_written += bytes_written;
869 g_assert (data->total_written <= data->blob_size);
870 if (data->total_written == data->blob_size)
872 g_simple_async_result_complete (simple);
873 g_object_unref (simple);
877 write_message_continue_writing (data);
883 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
885 on_socket_ready (GSocket *socket,
886 GIOCondition condition,
889 MessageToWriteData *data = user_data;
890 write_message_continue_writing (data);
891 return FALSE; /* remove source */
894 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
896 write_message_continue_writing (MessageToWriteData *data)
898 GOutputStream *ostream;
899 GSimpleAsyncResult *simple;
901 GUnixFDList *fd_list;
904 /* Note: we can't access data->simple after calling g_async_result_complete () because the
905 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
907 simple = data->simple;
909 ostream = g_io_stream_get_output_stream (data->worker->stream);
911 fd_list = g_dbus_message_get_unix_fd_list (data->message);
914 g_assert (!g_output_stream_has_pending (ostream));
915 g_assert_cmpint (data->total_written, <, data->blob_size);
921 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
923 GOutputVector vector;
924 GSocketControlMessage *control_message;
925 gssize bytes_written;
928 vector.buffer = data->blob;
929 vector.size = data->blob_size;
931 control_message = NULL;
932 if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
934 if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
936 g_simple_async_result_set_error (simple,
939 "Tried sending a file descriptor but remote peer does not support this capability");
940 g_simple_async_result_complete (simple);
941 g_object_unref (simple);
944 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
948 bytes_written = g_socket_send_message (data->worker->socket,
952 control_message != NULL ? &control_message : NULL,
953 control_message != NULL ? 1 : 0,
955 data->worker->cancellable,
957 if (control_message != NULL)
958 g_object_unref (control_message);
960 if (bytes_written == -1)
962 /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
963 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
966 source = g_socket_create_source (data->worker->socket,
967 G_IO_OUT | G_IO_HUP | G_IO_ERR,
968 data->worker->cancellable);
969 g_source_set_callback (source,
970 (GSourceFunc) on_socket_ready,
972 NULL); /* GDestroyNotify */
973 g_source_attach (source, g_main_context_get_thread_default ());
974 g_source_unref (source);
975 g_error_free (error);
978 g_simple_async_result_take_error (simple, error);
979 g_simple_async_result_complete (simple);
980 g_object_unref (simple);
983 g_assert (bytes_written > 0); /* zero is never returned */
985 write_message_print_transport_debug (bytes_written, data);
987 data->total_written += bytes_written;
988 g_assert (data->total_written <= data->blob_size);
989 if (data->total_written == data->blob_size)
991 g_simple_async_result_complete (simple);
992 g_object_unref (simple);
996 write_message_continue_writing (data);
1002 if (fd_list != NULL)
1004 g_simple_async_result_set_error (simple,
1007 "Tried sending a file descriptor on unsupported stream of type %s",
1008 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1009 g_simple_async_result_complete (simple);
1010 g_object_unref (simple);
1015 g_output_stream_write_async (ostream,
1016 (const gchar *) data->blob + data->total_written,
1017 data->blob_size - data->total_written,
1019 data->worker->cancellable,
1020 write_message_async_cb,
1027 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1029 write_message_async (GDBusWorker *worker,
1030 MessageToWriteData *data,
1031 GAsyncReadyCallback callback,
1034 data->simple = g_simple_async_result_new (NULL,
1037 write_message_async);
1038 data->total_written = 0;
1039 write_message_continue_writing (data);
1042 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1044 write_message_finish (GAsyncResult *res,
1047 g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1048 if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1053 /* ---------------------------------------------------------------------------------------------------- */
1055 static void maybe_write_next_message (GDBusWorker *worker);
1059 GDBusWorker *worker;
1063 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1065 ostream_flush_cb (GObject *source_object,
1069 FlushAsyncData *data = user_data;
1074 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1080 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1082 _g_dbus_debug_print_lock ();
1083 g_print ("========================================================================\n"
1084 "GDBus-debug:Transport:\n"
1085 " ---- FLUSHED stream of type %s\n",
1086 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1087 _g_dbus_debug_print_unlock ();
1091 g_assert (data->flushers != NULL);
1092 for (l = data->flushers; l != NULL; l = l->next)
1094 FlushData *f = l->data;
1096 f->error = error != NULL ? g_error_copy (error) : NULL;
1098 g_mutex_lock (f->mutex);
1099 g_cond_signal (f->cond);
1100 g_mutex_unlock (f->mutex);
1102 g_list_free (data->flushers);
1105 g_error_free (error);
1107 /* Make sure we tell folks that we don't have additional
1109 g_mutex_lock (data->worker->write_lock);
1110 data->worker->flush_pending = FALSE;
1111 g_mutex_unlock (data->worker->write_lock);
1113 /* OK, cool, finally kick off the next write */
1114 maybe_write_next_message (data->worker);
1116 _g_dbus_worker_unref (data->worker);
1120 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1122 message_written (GDBusWorker *worker,
1123 MessageToWriteData *message_data)
1129 /* first log the fact that we wrote a message */
1130 if (G_UNLIKELY (_g_dbus_debug_message ()))
1133 _g_dbus_debug_print_lock ();
1134 g_print ("========================================================================\n"
1135 "GDBus-debug:Message:\n"
1136 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1137 message_data->blob_size);
1138 s = g_dbus_message_print (message_data->message, 2);
1141 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1143 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1144 g_print ("%s\n", s);
1147 _g_dbus_debug_print_unlock ();
1150 /* then first wake up pending flushes and, if needed, flush the stream */
1152 g_mutex_lock (worker->write_lock);
1153 worker->write_num_messages_written += 1;
1154 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1156 FlushData *f = l->data;
1159 if (f->number_to_wait_for == worker->write_num_messages_written)
1161 flushers = g_list_append (flushers, f);
1162 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1165 if (flushers != NULL)
1167 worker->flush_pending = TRUE;
1169 g_mutex_unlock (worker->write_lock);
1171 if (flushers != NULL)
1173 FlushAsyncData *data;
1174 data = g_new0 (FlushAsyncData, 1);
1175 data->worker = _g_dbus_worker_ref (worker);
1176 data->flushers = flushers;
1177 /* flush the stream before writing the next message */
1178 g_output_stream_flush_async (g_io_stream_get_output_stream (worker->stream),
1180 worker->cancellable,
1186 /* kick off the next write! */
1187 maybe_write_next_message (worker);
1191 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1193 write_message_cb (GObject *source_object,
1197 MessageToWriteData *data = user_data;
1200 g_mutex_lock (data->worker->write_lock);
1201 data->worker->num_writes_pending -= 1;
1202 g_mutex_unlock (data->worker->write_lock);
1205 if (!write_message_finish (res, &error))
1208 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1209 g_error_free (error);
1212 /* this function will also kick of the next write (it might need to
1213 * flush so writing the next message might happen much later
1216 message_written (data->worker, data);
1218 message_to_write_data_free (data);
1221 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1223 maybe_write_next_message (GDBusWorker *worker)
1225 MessageToWriteData *data;
1229 g_mutex_lock (worker->write_lock);
1230 data = g_queue_pop_head (worker->write_queue);
1232 worker->num_writes_pending += 1;
1233 g_mutex_unlock (worker->write_lock);
1235 /* Note that write_lock is only used for protecting the @write_queue
1236 * and @num_writes_pending fields of the GDBusWorker struct ... which we
1237 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1239 * Therefore, it's fine to drop it here when calling back into user
1240 * code and then writing the message out onto the GIOStream since this
1241 * function only runs on the worker thread.
1245 GDBusMessage *old_message;
1247 gsize new_blob_size;
1250 old_message = data->message;
1251 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1252 if (data->message == old_message)
1254 /* filters had no effect - do nothing */
1256 else if (data->message == NULL)
1258 /* filters dropped message */
1259 g_mutex_lock (worker->write_lock);
1260 worker->num_writes_pending -= 1;
1261 g_mutex_unlock (worker->write_lock);
1262 message_to_write_data_free (data);
1267 /* filters altered the message -> reencode */
1269 new_blob = g_dbus_message_to_blob (data->message,
1271 worker->capabilities,
1273 if (new_blob == NULL)
1275 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1276 * the old message instead
1278 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1279 g_dbus_message_get_serial (data->message),
1281 g_error_free (error);
1285 g_free (data->blob);
1286 data->blob = (gchar *) new_blob;
1287 data->blob_size = new_blob_size;
1291 write_message_async (worker,
1298 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1300 write_message_in_idle_cb (gpointer user_data)
1302 GDBusWorker *worker = user_data;
1303 if (worker->num_writes_pending == 0 && !worker->flush_pending)
1304 maybe_write_next_message (worker);
1308 /* ---------------------------------------------------------------------------------------------------- */
1310 /* can be called from any thread - steals blob */
1312 _g_dbus_worker_send_message (GDBusWorker *worker,
1313 GDBusMessage *message,
1317 MessageToWriteData *data;
1319 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1320 g_return_if_fail (blob != NULL);
1321 g_return_if_fail (blob_len > 16);
1323 data = g_new0 (MessageToWriteData, 1);
1324 data->worker = _g_dbus_worker_ref (worker);
1325 data->message = g_object_ref (message);
1326 data->blob = blob; /* steal! */
1327 data->blob_size = blob_len;
1329 g_mutex_lock (worker->write_lock);
1330 g_queue_push_tail (worker->write_queue, data);
1331 if (worker->num_writes_pending == 0)
1333 GSource *idle_source;
1334 idle_source = g_idle_source_new ();
1335 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1336 g_source_set_callback (idle_source,
1337 write_message_in_idle_cb,
1338 _g_dbus_worker_ref (worker),
1339 (GDestroyNotify) _g_dbus_worker_unref);
1340 g_source_attach (idle_source, worker->shared_thread_data->context);
1341 g_source_unref (idle_source);
1343 g_mutex_unlock (worker->write_lock);
1346 /* ---------------------------------------------------------------------------------------------------- */
1349 _g_dbus_worker_new (GIOStream *stream,
1350 GDBusCapabilityFlags capabilities,
1351 gboolean initially_frozen,
1352 GDBusWorkerMessageReceivedCallback message_received_callback,
1353 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1354 GDBusWorkerDisconnectedCallback disconnected_callback,
1357 GDBusWorker *worker;
1358 GSource *idle_source;
1360 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1361 g_return_val_if_fail (message_received_callback != NULL, NULL);
1362 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1363 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1365 worker = g_new0 (GDBusWorker, 1);
1366 worker->ref_count = 1;
1368 worker->read_lock = g_mutex_new ();
1369 worker->message_received_callback = message_received_callback;
1370 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1371 worker->disconnected_callback = disconnected_callback;
1372 worker->user_data = user_data;
1373 worker->stream = g_object_ref (stream);
1374 worker->capabilities = capabilities;
1375 worker->cancellable = g_cancellable_new ();
1376 worker->flush_pending = FALSE;
1378 worker->frozen = initially_frozen;
1379 worker->received_messages_while_frozen = g_queue_new ();
1381 worker->write_lock = g_mutex_new ();
1382 worker->write_queue = g_queue_new ();
1384 if (G_IS_SOCKET_CONNECTION (worker->stream))
1385 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1387 worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1390 idle_source = g_idle_source_new ();
1391 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1392 g_source_set_callback (idle_source,
1393 _g_dbus_worker_do_initial_read,
1396 g_source_attach (idle_source, worker->shared_thread_data->context);
1397 g_source_unref (idle_source);
1402 /* ---------------------------------------------------------------------------------------------------- */
1404 /* This can be called from any thread - frees worker. Note that
1405 * callbacks might still happen if called from another thread than the
1406 * worker - use your own synchronization primitive in the callbacks.
1409 _g_dbus_worker_stop (GDBusWorker *worker)
1411 worker->stopped = TRUE;
1412 g_cancellable_cancel (worker->cancellable);
1413 _g_dbus_worker_unref (worker);
1416 /* ---------------------------------------------------------------------------------------------------- */
1418 /* can be called from any thread (except the worker thread) - blocks
1419 * calling thread until all queued outgoing messages are written and
1420 * the transport has been flushed
1423 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1424 GCancellable *cancellable,
1433 /* if the queue is empty, there's nothing to wait for */
1434 g_mutex_lock (worker->write_lock);
1435 if (g_queue_get_length (worker->write_queue) > 0)
1437 data = g_new0 (FlushData, 1);
1438 data->mutex = g_mutex_new ();
1439 data->cond = g_cond_new ();
1440 data->number_to_wait_for = worker->write_num_messages_written + g_queue_get_length (worker->write_queue);
1441 g_mutex_lock (data->mutex);
1442 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, data);
1444 g_mutex_unlock (worker->write_lock);
1448 g_cond_wait (data->cond, data->mutex);
1449 g_mutex_unlock (data->mutex);
1451 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1452 g_cond_free (data->cond);
1453 g_mutex_free (data->mutex);
1454 if (data->error != NULL)
1457 g_propagate_error (error, data->error);
1465 /* ---------------------------------------------------------------------------------------------------- */
1467 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1468 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1469 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1470 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1471 #define G_DBUS_DEBUG_CALL (1<<4)
1472 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1473 #define G_DBUS_DEBUG_INCOMING (1<<6)
1474 #define G_DBUS_DEBUG_RETURN (1<<7)
1475 #define G_DBUS_DEBUG_EMISSION (1<<8)
1476 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1478 static gint _gdbus_debug_flags = 0;
1481 _g_dbus_debug_authentication (void)
1483 _g_dbus_initialize ();
1484 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1488 _g_dbus_debug_transport (void)
1490 _g_dbus_initialize ();
1491 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1495 _g_dbus_debug_message (void)
1497 _g_dbus_initialize ();
1498 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1502 _g_dbus_debug_payload (void)
1504 _g_dbus_initialize ();
1505 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1509 _g_dbus_debug_call (void)
1511 _g_dbus_initialize ();
1512 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1516 _g_dbus_debug_signal (void)
1518 _g_dbus_initialize ();
1519 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1523 _g_dbus_debug_incoming (void)
1525 _g_dbus_initialize ();
1526 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1530 _g_dbus_debug_return (void)
1532 _g_dbus_initialize ();
1533 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1537 _g_dbus_debug_emission (void)
1539 _g_dbus_initialize ();
1540 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1544 _g_dbus_debug_address (void)
1546 _g_dbus_initialize ();
1547 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1550 G_LOCK_DEFINE_STATIC (print_lock);
1553 _g_dbus_debug_print_lock (void)
1555 G_LOCK (print_lock);
1559 _g_dbus_debug_print_unlock (void)
1561 G_UNLOCK (print_lock);
1565 * _g_dbus_initialize:
1567 * Does various one-time init things such as
1569 * - registering the G_DBUS_ERROR error domain
1570 * - parses the G_DBUS_DEBUG environment variable
1573 _g_dbus_initialize (void)
1575 static volatile gsize initialized = 0;
1577 if (g_once_init_enter (&initialized))
1579 volatile GQuark g_dbus_error_domain;
1582 g_dbus_error_domain = G_DBUS_ERROR;
1583 (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1585 debug = g_getenv ("G_DBUS_DEBUG");
1588 const GDebugKey keys[] = {
1589 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1590 { "transport", G_DBUS_DEBUG_TRANSPORT },
1591 { "message", G_DBUS_DEBUG_MESSAGE },
1592 { "payload", G_DBUS_DEBUG_PAYLOAD },
1593 { "call", G_DBUS_DEBUG_CALL },
1594 { "signal", G_DBUS_DEBUG_SIGNAL },
1595 { "incoming", G_DBUS_DEBUG_INCOMING },
1596 { "return", G_DBUS_DEBUG_RETURN },
1597 { "emission", G_DBUS_DEBUG_EMISSION },
1598 { "address", G_DBUS_DEBUG_ADDRESS }
1601 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1602 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1603 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1606 g_once_init_leave (&initialized, 1);
1610 /* ---------------------------------------------------------------------------------------------------- */
1613 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1615 const GVariantType *arg_types[256];
1619 for (n = 0; args[n] != NULL; n++)
1621 /* DBus places a hard limit of 255 on signature length.
1622 * therefore number of args must be less than 256.
1626 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1628 if G_UNLIKELY (arg_types[n] == NULL)
1634 return g_variant_type_new_tuple (arg_types, n);
1637 /* ---------------------------------------------------------------------------------------------------- */
1641 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1644 _g_dbus_win32_get_user_sid (void)
1648 DWORD token_information_len;
1655 h = INVALID_HANDLE_VALUE;
1657 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
1659 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
1663 /* Get length of buffer */
1664 token_information_len = 0;
1665 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
1667 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1669 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1673 user = g_malloc (token_information_len);
1674 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
1676 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1680 psid = user->User.Sid;
1681 if (!IsValidSid (psid))
1683 g_warning ("Invalid SID");
1687 if (!ConvertSidToStringSidA (psid, &sid))
1689 g_warning ("Invalid SID");
1693 ret = g_strdup (sid);
1698 if (h != INVALID_HANDLE_VALUE)
1704 /* ---------------------------------------------------------------------------------------------------- */
1707 _g_dbus_get_machine_id (GError **error)
1710 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
1712 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
1717 g_prefix_error (error, _("Unable to load /var/lib/dbus/machine-id: "));
1721 /* TODO: validate value */
1727 /* ---------------------------------------------------------------------------------------------------- */
1730 _g_dbus_enum_to_string (GType enum_type, gint value)
1734 GEnumValue *enum_value;
1736 klass = g_type_class_ref (enum_type);
1737 enum_value = g_enum_get_value (klass, value);
1738 if (enum_value != NULL)
1739 ret = g_strdup (enum_value->value_nick);
1741 ret = g_strdup_printf ("unknown (value %d)", value);
1742 g_type_class_unref (klass);
1746 /* ---------------------------------------------------------------------------------------------------- */
1749 write_message_print_transport_debug (gssize bytes_written,
1750 MessageToWriteData *data)
1752 if (G_LIKELY (!_g_dbus_debug_transport ()))
1755 _g_dbus_debug_print_lock ();
1756 g_print ("========================================================================\n"
1757 "GDBus-debug:Transport:\n"
1758 " >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1759 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
1761 g_dbus_message_get_serial (data->message),
1763 data->total_written,
1764 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1765 _g_dbus_debug_print_unlock ();
1770 /* ---------------------------------------------------------------------------------------------------- */
1773 read_message_print_transport_debug (gssize bytes_read,
1774 GDBusWorker *worker)
1778 gint32 message_length;
1780 if (G_LIKELY (!_g_dbus_debug_transport ()))
1783 size = bytes_read + worker->read_buffer_cur_size;
1787 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
1790 switch (worker->read_buffer[0])
1794 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
1798 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
1801 /* an error will be set elsewhere if this happens */
1806 _g_dbus_debug_print_lock ();
1807 g_print ("========================================================================\n"
1808 "GDBus-debug:Transport:\n"
1809 " <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1810 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
1814 worker->read_buffer_cur_size,
1815 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
1816 _g_dbus_debug_print_unlock ();
1821 /* ---------------------------------------------------------------------------------------------------- */
1824 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
1825 GValue *return_accu,
1826 const GValue *handler_return,
1829 gboolean continue_emission;
1830 gboolean signal_return;
1832 signal_return = g_value_get_boolean (handler_return);
1833 g_value_set_boolean (return_accu, signal_return);
1834 continue_emission = signal_return;
1836 return continue_emission;