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_set_from_error (data->simple, error);
157 g_error_free (error);
160 if (data->from_mainloop)
161 g_simple_async_result_complete (data->simple);
163 g_simple_async_result_complete_in_idle (data->simple);
169 _g_socket_read_with_control_messages (GSocket *socket,
172 GSocketControlMessage ***messages,
175 GCancellable *cancellable,
176 GAsyncReadyCallback callback,
179 ReadWithControlData *data;
181 data = g_new0 (ReadWithControlData, 1);
182 data->socket = g_object_ref (socket);
183 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
184 data->buffer = buffer;
186 data->messages = messages;
187 data->num_messages = num_messages;
189 data->simple = g_simple_async_result_new (G_OBJECT (socket),
192 _g_socket_read_with_control_messages);
194 if (!g_socket_condition_check (socket, G_IO_IN))
197 data->from_mainloop = TRUE;
198 source = g_socket_create_source (data->socket,
199 G_IO_IN | G_IO_HUP | G_IO_ERR,
201 g_source_set_callback (source,
202 (GSourceFunc) _g_socket_read_with_control_messages_ready,
204 (GDestroyNotify) read_with_control_data_free);
205 g_source_attach (source, g_main_context_get_thread_default ());
206 g_source_unref (source);
210 _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
211 read_with_control_data_free (data);
216 _g_socket_read_with_control_messages_finish (GSocket *socket,
217 GAsyncResult *result,
220 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
222 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
223 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
225 if (g_simple_async_result_propagate_error (simple, error))
228 return g_simple_async_result_get_op_res_gssize (simple);
231 /* ---------------------------------------------------------------------------------------------------- */
233 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
235 static GPtrArray *ensured_classes = NULL;
238 ensure_type (GType gtype)
240 g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
244 released_required_types (void)
246 g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
247 g_ptr_array_unref (ensured_classes);
248 ensured_classes = NULL;
252 ensure_required_types (void)
254 g_assert (ensured_classes == NULL);
255 ensured_classes = g_ptr_array_new ();
256 ensure_type (G_TYPE_SIMPLE_ASYNC_RESULT);
257 ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
259 /* ---------------------------------------------------------------------------------------------------- */
261 G_LOCK_DEFINE_STATIC (shared_thread_lock);
267 GMainContext *context;
271 static SharedThreadData *shared_thread_data = NULL;
274 gdbus_shared_thread_func (gpointer data)
276 g_main_context_push_thread_default (shared_thread_data->context);
277 g_main_loop_run (shared_thread_data->loop);
278 g_main_context_pop_thread_default (shared_thread_data->context);
282 typedef void (*GDBusSharedThreadFunc) (gpointer user_data);
286 GDBusSharedThreadFunc func;
292 invoke_caller (gpointer user_data)
294 CallerData *data = user_data;
295 data->func (data->user_data);
300 /* ---------------------------------------------------------------------------------------------------- */
303 _g_dbus_shared_thread_ref (GDBusSharedThreadFunc func,
307 GSource *idle_source;
309 gboolean release_types;
311 G_LOCK (shared_thread_lock);
313 release_types = FALSE;
315 if (shared_thread_data != NULL)
317 shared_thread_data->num_users += 1;
321 shared_thread_data = g_new0 (SharedThreadData, 1);
322 shared_thread_data->num_users = 1;
324 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
325 ensure_required_types ();
326 release_types = TRUE;
329 shared_thread_data->context = g_main_context_new ();
330 shared_thread_data->loop = g_main_loop_new (shared_thread_data->context, FALSE);
331 shared_thread_data->thread = g_thread_create (gdbus_shared_thread_func,
335 g_assert_no_error (error);
339 data = g_new0 (CallerData, 1);
341 data->user_data = user_data;
344 idle_source = g_idle_source_new ();
345 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
346 g_source_set_callback (idle_source,
350 g_source_attach (idle_source, shared_thread_data->context);
351 g_source_unref (idle_source);
353 /* wait for the user code to run.. hmm.. probably use a condition variable instead */
358 released_required_types ();
362 G_UNLOCK (shared_thread_lock);
366 _g_dbus_shared_thread_unref (void)
368 /* TODO: actually destroy the shared thread here */
370 G_LOCK (shared_thread_lock);
371 g_assert (shared_thread_data != NULL);
372 shared_thread_data->num_users -= 1;
373 if (shared_thread_data->num_users == 0)
375 g_main_loop_quit (shared_thread_data->loop);
376 //g_thread_join (shared_thread_data->thread);
377 g_main_loop_unref (shared_thread_data->loop);
378 g_main_context_unref (shared_thread_data->context);
379 g_free (shared_thread_data);
380 shared_thread_data = NULL;
381 G_UNLOCK (shared_thread_lock);
385 G_UNLOCK (shared_thread_lock);
390 /* ---------------------------------------------------------------------------------------------------- */
394 volatile gint ref_count;
398 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
399 * only affects messages received from the other peer (since GDBusServer is the
400 * only user) - we might want it to affect messages sent to the other peer too?
403 GQueue *received_messages_while_frozen;
406 GDBusCapabilityFlags capabilities;
407 GCancellable *cancellable;
408 GDBusWorkerMessageReceivedCallback message_received_callback;
409 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
410 GDBusWorkerDisconnectedCallback disconnected_callback;
415 /* if not NULL, stream is GSocketConnection */
418 /* used for reading */
421 gsize read_buffer_allocated_size;
422 gsize read_buffer_cur_size;
423 gsize read_buffer_bytes_wanted;
424 GUnixFDList *read_fd_list;
425 GSocketControlMessage **read_ancillary_messages;
426 gint read_num_ancillary_messages;
428 /* used for writing */
431 gint num_writes_pending;
432 guint64 write_num_messages_written;
433 GList *write_pending_flushes;
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);
879 g_object_unref (data->message);
884 /* ---------------------------------------------------------------------------------------------------- */
886 static void write_message_continue_writing (MessageToWriteData *data);
888 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
890 write_message_async_cb (GObject *source_object,
894 MessageToWriteData *data = user_data;
895 GSimpleAsyncResult *simple;
896 gssize bytes_written;
899 /* Note: we can't access data->simple after calling g_async_result_complete () because the
900 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
902 simple = data->simple;
905 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
908 if (bytes_written == -1)
910 g_simple_async_result_set_from_error (simple, error);
911 g_error_free (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_set_from_error (simple, error);
1031 g_error_free (error);
1032 g_simple_async_result_complete (simple);
1033 g_object_unref (simple);
1036 g_assert (bytes_written > 0); /* zero is never returned */
1038 write_message_print_transport_debug (bytes_written, data);
1040 data->total_written += bytes_written;
1041 g_assert (data->total_written <= data->blob_size);
1042 if (data->total_written == data->blob_size)
1044 g_simple_async_result_complete (simple);
1045 g_object_unref (simple);
1049 write_message_continue_writing (data);
1055 if (fd_list != NULL)
1057 g_simple_async_result_set_error (simple,
1060 "Tried sending a file descriptor on unsupported stream of type %s",
1061 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1062 g_simple_async_result_complete (simple);
1063 g_object_unref (simple);
1068 g_output_stream_write_async (ostream,
1069 (const gchar *) data->blob + data->total_written,
1070 data->blob_size - data->total_written,
1072 data->worker->cancellable,
1073 write_message_async_cb,
1080 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1082 write_message_async (GDBusWorker *worker,
1083 MessageToWriteData *data,
1084 GAsyncReadyCallback callback,
1087 data->simple = g_simple_async_result_new (NULL,
1090 write_message_async);
1091 data->total_written = 0;
1092 write_message_continue_writing (data);
1095 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1097 write_message_finish (GAsyncResult *res,
1100 g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1101 if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1106 /* ---------------------------------------------------------------------------------------------------- */
1108 static void maybe_write_next_message (GDBusWorker *worker);
1112 GDBusWorker *worker;
1116 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1118 ostream_flush_cb (GObject *source_object,
1122 FlushAsyncData *data = user_data;
1127 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1133 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1135 _g_dbus_debug_print_lock ();
1136 g_print ("========================================================================\n"
1137 "GDBus-debug:Transport:\n"
1138 " ---- FLUSHED stream of type %s\n",
1139 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1140 _g_dbus_debug_print_unlock ();
1144 g_assert (data->flushers != NULL);
1145 for (l = data->flushers; l != NULL; l = l->next)
1147 FlushData *f = l->data;
1149 f->error = error != NULL ? g_error_copy (error) : NULL;
1151 g_mutex_lock (f->mutex);
1152 g_cond_signal (f->cond);
1153 g_mutex_unlock (f->mutex);
1155 g_list_free (data->flushers);
1158 g_error_free (error);
1160 /* OK, cool, finally kick off the next write */
1161 maybe_write_next_message (data->worker);
1163 _g_dbus_worker_unref (data->worker);
1167 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1169 message_written (GDBusWorker *worker,
1170 MessageToWriteData *message_data)
1176 /* first log the fact that we wrote a message */
1177 if (G_UNLIKELY (_g_dbus_debug_message ()))
1180 _g_dbus_debug_print_lock ();
1181 g_print ("========================================================================\n"
1182 "GDBus-debug:Message:\n"
1183 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1184 message_data->blob_size);
1185 s = g_dbus_message_print (message_data->message, 2);
1188 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1190 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1191 g_print ("%s\n", s);
1194 _g_dbus_debug_print_unlock ();
1197 /* then first wake up pending flushes and, if needed, flush the stream */
1199 g_mutex_lock (worker->write_lock);
1200 worker->write_num_messages_written += 1;
1201 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1203 FlushData *f = l->data;
1206 if (f->number_to_wait_for == worker->write_num_messages_written)
1208 flushers = g_list_append (flushers, f);
1209 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1212 g_mutex_unlock (worker->write_lock);
1214 if (flushers != NULL)
1216 FlushAsyncData *data;
1217 data = g_new0 (FlushAsyncData, 1);
1218 data->worker = _g_dbus_worker_ref (worker);
1219 data->flushers = flushers;
1220 /* flush the stream before writing the next message */
1221 g_output_stream_flush_async (g_io_stream_get_output_stream (worker->stream),
1223 worker->cancellable,
1229 /* kick off the next write! */
1230 maybe_write_next_message (worker);
1234 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1236 write_message_cb (GObject *source_object,
1240 MessageToWriteData *data = user_data;
1243 g_mutex_lock (data->worker->write_lock);
1244 data->worker->num_writes_pending -= 1;
1245 g_mutex_unlock (data->worker->write_lock);
1248 if (!write_message_finish (res, &error))
1251 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1252 g_error_free (error);
1255 /* this function will also kick of the next write (it might need to
1256 * flush so writing the next message might happen much later
1259 message_written (data->worker, data);
1261 message_to_write_data_free (data);
1264 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1266 maybe_write_next_message (GDBusWorker *worker)
1268 MessageToWriteData *data;
1272 g_mutex_lock (worker->write_lock);
1273 data = g_queue_pop_head (worker->write_queue);
1275 worker->num_writes_pending += 1;
1276 g_mutex_unlock (worker->write_lock);
1278 /* Note that write_lock is only used for protecting the @write_queue
1279 * and @num_writes_pending fields of the GDBusWorker struct ... which we
1280 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1282 * Therefore, it's fine to drop it here when calling back into user
1283 * code and then writing the message out onto the GIOStream since this
1284 * function only runs on the worker thread.
1288 GDBusMessage *old_message;
1290 gsize new_blob_size;
1293 old_message = data->message;
1294 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1295 if (data->message == old_message)
1297 /* filters had no effect - do nothing */
1299 else if (data->message == NULL)
1301 /* filters dropped message */
1302 g_mutex_lock (worker->write_lock);
1303 worker->num_writes_pending -= 1;
1304 g_mutex_unlock (worker->write_lock);
1305 message_to_write_data_free (data);
1310 /* filters altered the message -> reencode */
1312 new_blob = g_dbus_message_to_blob (data->message,
1314 worker->capabilities,
1316 if (new_blob == NULL)
1318 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1319 * the old message instead
1321 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1322 g_dbus_message_get_serial (data->message),
1324 g_error_free (error);
1328 g_free (data->blob);
1329 data->blob = (gchar *) new_blob;
1330 data->blob_size = new_blob_size;
1334 write_message_async (worker,
1341 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
1343 write_message_in_idle_cb (gpointer user_data)
1345 GDBusWorker *worker = user_data;
1346 if (worker->num_writes_pending == 0)
1347 maybe_write_next_message (worker);
1351 /* ---------------------------------------------------------------------------------------------------- */
1353 /* can be called from any thread - steals blob */
1355 _g_dbus_worker_send_message (GDBusWorker *worker,
1356 GDBusMessage *message,
1360 MessageToWriteData *data;
1362 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1363 g_return_if_fail (blob != NULL);
1364 g_return_if_fail (blob_len > 16);
1366 data = g_new0 (MessageToWriteData, 1);
1367 data->worker = _g_dbus_worker_ref (worker);
1368 data->message = g_object_ref (message);
1369 data->blob = blob; /* steal! */
1370 data->blob_size = blob_len;
1372 g_mutex_lock (worker->write_lock);
1373 g_queue_push_tail (worker->write_queue, data);
1374 if (worker->num_writes_pending == 0)
1376 GSource *idle_source;
1377 idle_source = g_idle_source_new ();
1378 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1379 g_source_set_callback (idle_source,
1380 write_message_in_idle_cb,
1381 _g_dbus_worker_ref (worker),
1382 (GDestroyNotify) _g_dbus_worker_unref);
1383 g_source_attach (idle_source, shared_thread_data->context);
1384 g_source_unref (idle_source);
1386 g_mutex_unlock (worker->write_lock);
1389 /* ---------------------------------------------------------------------------------------------------- */
1392 _g_dbus_worker_thread_begin_func (gpointer user_data)
1394 GDBusWorker *worker = user_data;
1396 worker->thread = g_thread_self ();
1399 _g_dbus_worker_do_read (worker);
1403 _g_dbus_worker_new (GIOStream *stream,
1404 GDBusCapabilityFlags capabilities,
1405 gboolean initially_frozen,
1406 GDBusWorkerMessageReceivedCallback message_received_callback,
1407 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1408 GDBusWorkerDisconnectedCallback disconnected_callback,
1411 GDBusWorker *worker;
1413 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1414 g_return_val_if_fail (message_received_callback != NULL, NULL);
1415 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1416 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1418 worker = g_new0 (GDBusWorker, 1);
1419 worker->ref_count = 1;
1421 worker->read_lock = g_mutex_new ();
1422 worker->message_received_callback = message_received_callback;
1423 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1424 worker->disconnected_callback = disconnected_callback;
1425 worker->user_data = user_data;
1426 worker->stream = g_object_ref (stream);
1427 worker->capabilities = capabilities;
1428 worker->cancellable = g_cancellable_new ();
1430 worker->frozen = initially_frozen;
1431 worker->received_messages_while_frozen = g_queue_new ();
1433 worker->write_lock = g_mutex_new ();
1434 worker->write_queue = g_queue_new ();
1436 if (G_IS_SOCKET_CONNECTION (worker->stream))
1437 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1439 _g_dbus_shared_thread_ref (_g_dbus_worker_thread_begin_func, worker);
1444 /* ---------------------------------------------------------------------------------------------------- */
1446 /* This can be called from any thread - frees worker - guarantees no callbacks
1447 * will ever be issued again
1450 _g_dbus_worker_stop (GDBusWorker *worker)
1452 /* If we're called in the worker thread it means we are called from
1453 * a worker callback. This is fine, we just can't lock in that case since
1454 * we're already holding the lock...
1456 if (g_thread_self () != worker->thread)
1457 g_mutex_lock (worker->read_lock);
1458 worker->stopped = TRUE;
1459 if (g_thread_self () != worker->thread)
1460 g_mutex_unlock (worker->read_lock);
1462 g_cancellable_cancel (worker->cancellable);
1463 _g_dbus_worker_unref (worker);
1466 /* ---------------------------------------------------------------------------------------------------- */
1468 /* can be called from any thread (except the worker thread) - blocks
1469 * calling thread until all queued outgoing messages are written and
1470 * the transport has been flushed
1473 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1474 GCancellable *cancellable,
1483 /* if the queue is empty, there's nothing to wait for */
1484 g_mutex_lock (worker->write_lock);
1485 if (g_queue_get_length (worker->write_queue) > 0)
1487 data = g_new0 (FlushData, 1);
1488 data->mutex = g_mutex_new ();
1489 data->cond = g_cond_new ();
1490 data->number_to_wait_for = worker->write_num_messages_written + g_queue_get_length (worker->write_queue);
1491 g_mutex_lock (data->mutex);
1492 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, data);
1494 g_mutex_unlock (worker->write_lock);
1498 g_cond_wait (data->cond, data->mutex);
1499 g_mutex_unlock (data->mutex);
1501 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1502 g_cond_free (data->cond);
1503 g_mutex_free (data->mutex);
1504 if (data->error != NULL)
1507 g_propagate_error (error, data->error);
1515 /* ---------------------------------------------------------------------------------------------------- */
1517 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1518 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1519 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1520 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1521 #define G_DBUS_DEBUG_CALL (1<<4)
1522 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1523 #define G_DBUS_DEBUG_INCOMING (1<<6)
1524 #define G_DBUS_DEBUG_RETURN (1<<7)
1525 #define G_DBUS_DEBUG_EMISSION (1<<8)
1526 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1528 static gint _gdbus_debug_flags = 0;
1531 _g_dbus_debug_authentication (void)
1533 _g_dbus_initialize ();
1534 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1538 _g_dbus_debug_transport (void)
1540 _g_dbus_initialize ();
1541 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1545 _g_dbus_debug_message (void)
1547 _g_dbus_initialize ();
1548 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1552 _g_dbus_debug_payload (void)
1554 _g_dbus_initialize ();
1555 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1559 _g_dbus_debug_call (void)
1561 _g_dbus_initialize ();
1562 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1566 _g_dbus_debug_signal (void)
1568 _g_dbus_initialize ();
1569 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1573 _g_dbus_debug_incoming (void)
1575 _g_dbus_initialize ();
1576 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1580 _g_dbus_debug_return (void)
1582 _g_dbus_initialize ();
1583 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1587 _g_dbus_debug_emission (void)
1589 _g_dbus_initialize ();
1590 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1594 _g_dbus_debug_address (void)
1596 _g_dbus_initialize ();
1597 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1600 G_LOCK_DEFINE_STATIC (print_lock);
1603 _g_dbus_debug_print_lock (void)
1605 G_LOCK (print_lock);
1609 _g_dbus_debug_print_unlock (void)
1611 G_UNLOCK (print_lock);
1615 * _g_dbus_initialize:
1617 * Does various one-time init things such as
1619 * - registering the G_DBUS_ERROR error domain
1620 * - parses the G_DBUS_DEBUG environment variable
1623 _g_dbus_initialize (void)
1625 static volatile gsize initialized = 0;
1627 if (g_once_init_enter (&initialized))
1629 volatile GQuark g_dbus_error_domain;
1632 g_dbus_error_domain = G_DBUS_ERROR;
1634 debug = g_getenv ("G_DBUS_DEBUG");
1637 const GDebugKey keys[] = {
1638 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1639 { "transport", G_DBUS_DEBUG_TRANSPORT },
1640 { "message", G_DBUS_DEBUG_MESSAGE },
1641 { "payload", G_DBUS_DEBUG_PAYLOAD },
1642 { "call", G_DBUS_DEBUG_CALL },
1643 { "signal", G_DBUS_DEBUG_SIGNAL },
1644 { "incoming", G_DBUS_DEBUG_INCOMING },
1645 { "return", G_DBUS_DEBUG_RETURN },
1646 { "emission", G_DBUS_DEBUG_EMISSION },
1647 { "address", G_DBUS_DEBUG_ADDRESS }
1650 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1651 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1652 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1655 g_once_init_leave (&initialized, 1);
1659 /* ---------------------------------------------------------------------------------------------------- */
1662 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1664 const GVariantType *arg_types[256];
1668 for (n = 0; args[n] != NULL; n++)
1670 /* DBus places a hard limit of 255 on signature length.
1671 * therefore number of args must be less than 256.
1675 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1677 if G_UNLIKELY (arg_types[n] == NULL)
1683 return g_variant_type_new_tuple (arg_types, n);
1686 /* ---------------------------------------------------------------------------------------------------- */
1690 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1693 _g_dbus_win32_get_user_sid (void)
1697 DWORD token_information_len;
1704 h = INVALID_HANDLE_VALUE;
1706 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
1708 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
1712 /* Get length of buffer */
1713 token_information_len = 0;
1714 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
1716 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1718 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1722 user = g_malloc (token_information_len);
1723 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
1725 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1729 psid = user->User.Sid;
1730 if (!IsValidSid (psid))
1732 g_warning ("Invalid SID");
1736 if (!ConvertSidToStringSidA (psid, &sid))
1738 g_warning ("Invalid SID");
1742 ret = g_strdup (sid);
1747 if (h != INVALID_HANDLE_VALUE)
1753 /* ---------------------------------------------------------------------------------------------------- */
1756 _g_dbus_get_machine_id (GError **error)
1759 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
1761 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
1766 g_prefix_error (error, _("Unable to load /var/lib/dbus/machine-id: "));
1770 /* TODO: validate value */
1776 /* ---------------------------------------------------------------------------------------------------- */
1779 _g_dbus_enum_to_string (GType enum_type, gint value)
1783 GEnumValue *enum_value;
1785 klass = g_type_class_ref (enum_type);
1786 enum_value = g_enum_get_value (klass, value);
1787 if (enum_value != NULL)
1788 ret = g_strdup (enum_value->value_nick);
1790 ret = g_strdup_printf ("unknown (value %d)", value);
1791 g_type_class_unref (klass);
1795 /* ---------------------------------------------------------------------------------------------------- */
1798 write_message_print_transport_debug (gssize bytes_written,
1799 MessageToWriteData *data)
1801 if (G_LIKELY (!_g_dbus_debug_transport ()))
1804 _g_dbus_debug_print_lock ();
1805 g_print ("========================================================================\n"
1806 "GDBus-debug:Transport:\n"
1807 " >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1808 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
1810 g_dbus_message_get_serial (data->message),
1812 data->total_written,
1813 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1814 _g_dbus_debug_print_unlock ();
1819 /* ---------------------------------------------------------------------------------------------------- */
1822 read_message_print_transport_debug (gssize bytes_read,
1823 GDBusWorker *worker)
1827 gint32 message_length;
1829 if (G_LIKELY (!_g_dbus_debug_transport ()))
1832 size = bytes_read + worker->read_buffer_cur_size;
1836 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
1839 switch (worker->read_buffer[0])
1843 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
1847 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
1850 /* an error will be set elsewhere if this happens */
1855 _g_dbus_debug_print_lock ();
1856 g_print ("========================================================================\n"
1857 "GDBus-debug:Transport:\n"
1858 " <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
1859 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
1863 worker->read_buffer_cur_size,
1864 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
1865 _g_dbus_debug_print_unlock ();