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>
30 #include "gdbusprivate.h"
31 #include "gdbusmessage.h"
32 #include "gdbuserror.h"
33 #include "gdbusintrospection.h"
34 #include "gasyncresult.h"
35 #include "gsimpleasyncresult.h"
36 #include "ginputstream.h"
37 #include "gmemoryinputstream.h"
38 #include "giostream.h"
39 #include "glib/gstdio.h"
40 #include "gsocketcontrolmessage.h"
41 #include "gsocketconnection.h"
42 #include "gsocketoutputstream.h"
45 #include "gunixfdmessage.h"
46 #include "gunixconnection.h"
47 #include "gunixcredentialsmessage.h"
56 static gboolean _g_dbus_worker_do_initial_read (gpointer data);
58 /* ---------------------------------------------------------------------------------------------------- */
61 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
66 ret = g_string_new (NULL);
68 for (n = 0; n < len; n += 16)
70 g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
72 for (m = n; m < n + 16; m++)
74 if (m > n && (m%4) == 0)
75 g_string_append_c (ret, ' ');
77 g_string_append_printf (ret, "%02x ", (guchar) data[m]);
79 g_string_append (ret, " ");
82 g_string_append (ret, " ");
84 for (m = n; m < len && m < n + 16; m++)
85 g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
87 g_string_append_c (ret, '\n');
90 return g_string_free (ret, FALSE);
93 /* ---------------------------------------------------------------------------------------------------- */
95 /* Unfortunately ancillary messages are discarded when reading from a
96 * socket using the GSocketInputStream abstraction. So we provide a
97 * very GInputStream-ish API that uses GSocket in this case (very
98 * similar to GSocketInputStream).
104 GCancellable *cancellable;
109 GSocketControlMessage ***messages;
112 GSimpleAsyncResult *simple;
114 gboolean from_mainloop;
115 } ReadWithControlData;
118 read_with_control_data_free (ReadWithControlData *data)
120 g_object_unref (data->socket);
121 if (data->cancellable != NULL)
122 g_object_unref (data->cancellable);
123 g_object_unref (data->simple);
128 _g_socket_read_with_control_messages_ready (GSocket *socket,
129 GIOCondition condition,
132 ReadWithControlData *data = user_data;
138 vector.buffer = data->buffer;
139 vector.size = data->count;
140 result = g_socket_receive_message (data->socket,
151 g_simple_async_result_set_op_res_gssize (data->simple, result);
155 g_assert (error != NULL);
156 g_simple_async_result_take_error (data->simple, error);
159 if (data->from_mainloop)
160 g_simple_async_result_complete (data->simple);
162 g_simple_async_result_complete_in_idle (data->simple);
168 _g_socket_read_with_control_messages (GSocket *socket,
171 GSocketControlMessage ***messages,
174 GCancellable *cancellable,
175 GAsyncReadyCallback callback,
178 ReadWithControlData *data;
180 data = g_new0 (ReadWithControlData, 1);
181 data->socket = g_object_ref (socket);
182 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
183 data->buffer = buffer;
185 data->messages = messages;
186 data->num_messages = num_messages;
188 data->simple = g_simple_async_result_new (G_OBJECT (socket),
191 _g_socket_read_with_control_messages);
192 g_simple_async_result_set_check_cancellable (data->simple, cancellable);
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 release_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 /* ---------------------------------------------------------------------------------------------------- */
263 volatile gint refcount;
265 GMainContext *context;
270 gdbus_shared_thread_func (gpointer user_data)
272 SharedThreadData *data = user_data;
274 g_main_context_push_thread_default (data->context);
275 g_main_loop_run (data->loop);
276 g_main_context_pop_thread_default (data->context);
278 release_required_types ();
283 /* ---------------------------------------------------------------------------------------------------- */
285 static SharedThreadData *
286 _g_dbus_shared_thread_ref (void)
288 static gsize shared_thread_data = 0;
289 SharedThreadData *ret;
291 if (g_once_init_enter (&shared_thread_data))
293 SharedThreadData *data;
295 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
296 ensure_required_types ();
298 data = g_new0 (SharedThreadData, 1);
301 data->context = g_main_context_new ();
302 data->loop = g_main_loop_new (data->context, FALSE);
303 data->thread = g_thread_new ("gdbus",
304 gdbus_shared_thread_func,
306 /* We can cast between gsize and gpointer safely */
307 g_once_init_leave (&shared_thread_data, (gsize) data);
310 ret = (SharedThreadData*) shared_thread_data;
311 g_atomic_int_inc (&ret->refcount);
316 _g_dbus_shared_thread_unref (SharedThreadData *data)
318 /* TODO: actually destroy the shared thread here */
320 g_assert (data != NULL);
321 if (g_atomic_int_dec_and_test (&data->refcount))
323 g_main_loop_quit (data->loop);
324 //g_thread_join (data->thread);
325 g_main_loop_unref (data->loop);
326 g_main_context_unref (data->context);
331 /* ---------------------------------------------------------------------------------------------------- */
342 volatile gint ref_count;
344 SharedThreadData *shared_thread_data;
346 /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
347 volatile gint stopped;
349 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
350 * only affects messages received from the other peer (since GDBusServer is the
351 * only user) - we might want it to affect messages sent to the other peer too?
354 GDBusCapabilityFlags capabilities;
355 GQueue *received_messages_while_frozen;
358 GCancellable *cancellable;
359 GDBusWorkerMessageReceivedCallback message_received_callback;
360 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
361 GDBusWorkerDisconnectedCallback disconnected_callback;
364 /* if not NULL, stream is GSocketConnection */
367 /* used for reading */
370 gsize read_buffer_allocated_size;
371 gsize read_buffer_cur_size;
372 gsize read_buffer_bytes_wanted;
373 GUnixFDList *read_fd_list;
374 GSocketControlMessage **read_ancillary_messages;
375 gint read_num_ancillary_messages;
377 /* Whether an async write, flush or close, or none of those, is pending.
378 * Only the worker thread may change its value, and only with the write_lock.
379 * Other threads may read its value when holding the write_lock.
380 * The worker thread may read its value at any time.
382 OutputPending output_pending;
383 /* used for writing */
385 /* queue of MessageToWriteData, protected by write_lock */
387 /* protected by write_lock */
388 guint64 write_num_messages_written;
389 /* number of messages we'd written out last time we flushed;
390 * protected by write_lock
392 guint64 write_num_messages_flushed;
393 /* list of FlushData, protected by write_lock */
394 GList *write_pending_flushes;
395 /* list of CloseData, protected by write_lock */
396 GList *pending_close_attempts;
397 /* no lock - only used from the worker thread */
398 gboolean close_expected;
401 static void _g_dbus_worker_unref (GDBusWorker *worker);
403 /* ---------------------------------------------------------------------------------------------------- */
409 guint64 number_to_wait_for;
413 struct _MessageToWriteData ;
414 typedef struct _MessageToWriteData MessageToWriteData;
416 static void message_to_write_data_free (MessageToWriteData *data);
418 static void read_message_print_transport_debug (gssize bytes_read,
419 GDBusWorker *worker);
421 static void write_message_print_transport_debug (gssize bytes_written,
422 MessageToWriteData *data);
426 GCancellable *cancellable;
427 GSimpleAsyncResult *result;
430 static void close_data_free (CloseData *close_data)
432 if (close_data->cancellable != NULL)
433 g_object_unref (close_data->cancellable);
435 if (close_data->result != NULL)
436 g_object_unref (close_data->result);
438 _g_dbus_worker_unref (close_data->worker);
439 g_slice_free (CloseData, close_data);
442 /* ---------------------------------------------------------------------------------------------------- */
445 _g_dbus_worker_ref (GDBusWorker *worker)
447 g_atomic_int_inc (&worker->ref_count);
452 _g_dbus_worker_unref (GDBusWorker *worker)
454 if (g_atomic_int_dec_and_test (&worker->ref_count))
456 g_assert (worker->write_pending_flushes == NULL);
458 _g_dbus_shared_thread_unref (worker->shared_thread_data);
460 g_object_unref (worker->stream);
462 g_mutex_clear (&worker->read_lock);
463 g_object_unref (worker->cancellable);
464 if (worker->read_fd_list != NULL)
465 g_object_unref (worker->read_fd_list);
467 g_queue_free_full (worker->received_messages_while_frozen, (GDestroyNotify) g_object_unref);
468 g_mutex_clear (&worker->write_lock);
469 g_queue_free_full (worker->write_queue, (GDestroyNotify) message_to_write_data_free);
470 g_free (worker->read_buffer);
477 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
478 gboolean remote_peer_vanished,
481 if (!g_atomic_int_get (&worker->stopped))
482 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
486 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
487 GDBusMessage *message)
489 if (!g_atomic_int_get (&worker->stopped))
490 worker->message_received_callback (worker, message, worker->user_data);
493 static GDBusMessage *
494 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
495 GDBusMessage *message)
498 if (!g_atomic_int_get (&worker->stopped))
499 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
505 /* can only be called from private thread with read-lock held - takes ownership of @message */
507 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
508 GDBusMessage *message)
510 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
513 g_queue_push_tail (worker->received_messages_while_frozen, message);
517 /* not frozen, nor anything in queue */
518 _g_dbus_worker_emit_message_received (worker, message);
519 g_object_unref (message);
523 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
525 unfreeze_in_idle_cb (gpointer user_data)
527 GDBusWorker *worker = user_data;
528 GDBusMessage *message;
530 g_mutex_lock (&worker->read_lock);
533 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
535 _g_dbus_worker_emit_message_received (worker, message);
536 g_object_unref (message);
538 worker->frozen = FALSE;
542 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
544 g_mutex_unlock (&worker->read_lock);
548 /* can be called from any thread */
550 _g_dbus_worker_unfreeze (GDBusWorker *worker)
552 GSource *idle_source;
553 idle_source = g_idle_source_new ();
554 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
555 g_source_set_callback (idle_source,
557 _g_dbus_worker_ref (worker),
558 (GDestroyNotify) _g_dbus_worker_unref);
559 g_source_attach (idle_source, worker->shared_thread_data->context);
560 g_source_unref (idle_source);
563 /* ---------------------------------------------------------------------------------------------------- */
565 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
567 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
569 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
573 GDBusWorker *worker = user_data;
577 g_mutex_lock (&worker->read_lock);
579 /* If already stopped, don't even process the reply */
580 if (g_atomic_int_get (&worker->stopped))
584 if (worker->socket == NULL)
585 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
589 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
592 if (worker->read_num_ancillary_messages > 0)
595 for (n = 0; n < worker->read_num_ancillary_messages; n++)
597 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
603 else if (G_IS_UNIX_FD_MESSAGE (control_message))
605 GUnixFDMessage *fd_message;
609 fd_message = G_UNIX_FD_MESSAGE (control_message);
610 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
611 if (worker->read_fd_list == NULL)
613 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
618 for (n = 0; n < num_fds; n++)
620 /* TODO: really want a append_steal() */
621 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
622 (void) g_close (fds[n], NULL);
627 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
639 "Unexpected ancillary message of type %s received from peer",
640 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
641 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
642 g_error_free (error);
643 g_object_unref (control_message);
645 while (n < worker->read_num_ancillary_messages)
646 g_object_unref (worker->read_ancillary_messages[n++]);
647 g_free (worker->read_ancillary_messages);
651 g_object_unref (control_message);
653 g_free (worker->read_ancillary_messages);
656 if (bytes_read == -1)
658 if (G_UNLIKELY (_g_dbus_debug_transport ()))
660 _g_dbus_debug_print_lock ();
661 g_print ("========================================================================\n"
662 "GDBus-debug:Transport:\n"
663 " ---- READ ERROR on stream of type %s:\n"
665 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))),
666 g_quark_to_string (error->domain), error->code,
668 _g_dbus_debug_print_unlock ();
671 /* Every async read that uses this callback uses worker->cancellable
672 * as its GCancellable. worker->cancellable gets cancelled if and only
673 * if the GDBusConnection tells us to close (either via
674 * _g_dbus_worker_stop, which is called on last-unref, or directly),
675 * so a cancelled read must mean our connection was closed locally.
677 * If we're closing, other errors are possible - notably,
678 * G_IO_ERROR_CLOSED can be seen if we close the stream with an async
679 * read in-flight. It seems sensible to treat all read errors during
680 * closing as an expected thing that doesn't trip exit-on-close.
682 * Because close_expected can't be set until we get into the worker
683 * thread, but the cancellable is signalled sooner (from another
684 * thread), we do still need to check the error.
686 if (worker->close_expected ||
687 g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
688 _g_dbus_worker_emit_disconnected (worker, FALSE, NULL);
690 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
692 g_error_free (error);
697 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
699 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
700 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
701 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
702 G_IO_IN | G_IO_OUT | G_IO_HUP),
707 /* TODO: hmm, hmm... */
713 "Underlying GIOStream returned 0 bytes on an async read");
714 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
715 g_error_free (error);
719 read_message_print_transport_debug (bytes_read, worker);
721 worker->read_buffer_cur_size += bytes_read;
722 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
724 /* OK, got what we asked for! */
725 if (worker->read_buffer_bytes_wanted == 16)
728 /* OK, got the header - determine how many more bytes are needed */
730 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
733 if (message_len == -1)
735 g_warning ("_g_dbus_worker_do_read_cb: error determining bytes needed: %s", error->message);
736 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
737 g_error_free (error);
741 worker->read_buffer_bytes_wanted = message_len;
742 _g_dbus_worker_do_read_unlocked (worker);
746 GDBusMessage *message;
749 /* TODO: use connection->priv->auth to decode the message */
751 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
752 worker->read_buffer_cur_size,
753 worker->capabilities,
758 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
759 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
761 "The payload is as follows:\n"
763 worker->read_buffer_cur_size,
767 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
768 g_error_free (error);
773 if (worker->read_fd_list != NULL)
775 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
776 g_object_unref (worker->read_fd_list);
777 worker->read_fd_list = NULL;
781 if (G_UNLIKELY (_g_dbus_debug_message ()))
784 _g_dbus_debug_print_lock ();
785 g_print ("========================================================================\n"
786 "GDBus-debug:Message:\n"
787 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
788 worker->read_buffer_cur_size);
789 s = g_dbus_message_print (message, 2);
792 if (G_UNLIKELY (_g_dbus_debug_payload ()))
794 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
798 _g_dbus_debug_print_unlock ();
801 /* yay, got a message, go deliver it */
802 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
804 /* start reading another message! */
805 worker->read_buffer_bytes_wanted = 0;
806 worker->read_buffer_cur_size = 0;
807 _g_dbus_worker_do_read_unlocked (worker);
812 /* didn't get all the bytes we requested - so repeat the request... */
813 _g_dbus_worker_do_read_unlocked (worker);
817 g_mutex_unlock (&worker->read_lock);
819 /* gives up the reference acquired when calling g_input_stream_read_async() */
820 _g_dbus_worker_unref (worker);
823 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
825 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
827 /* Note that we do need to keep trying to read even if close_expected is
828 * true, because only failing a read causes us to signal 'closed'.
831 /* if bytes_wanted is zero, it means start reading a message */
832 if (worker->read_buffer_bytes_wanted == 0)
834 worker->read_buffer_cur_size = 0;
835 worker->read_buffer_bytes_wanted = 16;
838 /* ensure we have a (big enough) buffer */
839 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
841 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
842 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
843 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
846 if (worker->socket == NULL)
847 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
848 worker->read_buffer + worker->read_buffer_cur_size,
849 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
852 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
853 _g_dbus_worker_ref (worker));
856 worker->read_ancillary_messages = NULL;
857 worker->read_num_ancillary_messages = 0;
858 _g_socket_read_with_control_messages (worker->socket,
859 worker->read_buffer + worker->read_buffer_cur_size,
860 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
861 &worker->read_ancillary_messages,
862 &worker->read_num_ancillary_messages,
865 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
866 _g_dbus_worker_ref (worker));
870 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
872 _g_dbus_worker_do_initial_read (gpointer data)
874 GDBusWorker *worker = data;
875 g_mutex_lock (&worker->read_lock);
876 _g_dbus_worker_do_read_unlocked (worker);
877 g_mutex_unlock (&worker->read_lock);
881 /* ---------------------------------------------------------------------------------------------------- */
883 struct _MessageToWriteData
886 GDBusMessage *message;
891 GSimpleAsyncResult *simple;
896 message_to_write_data_free (MessageToWriteData *data)
898 _g_dbus_worker_unref (data->worker);
900 g_object_unref (data->message);
905 /* ---------------------------------------------------------------------------------------------------- */
907 static void write_message_continue_writing (MessageToWriteData *data);
909 /* called in private thread shared by all GDBusConnection instances
911 * write-lock is not held on entry
912 * output_pending is PENDING_WRITE on entry
915 write_message_async_cb (GObject *source_object,
919 MessageToWriteData *data = user_data;
920 GSimpleAsyncResult *simple;
921 gssize bytes_written;
924 /* Note: we can't access data->simple after calling g_async_result_complete () because the
925 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
927 simple = data->simple;
930 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
933 if (bytes_written == -1)
935 g_simple_async_result_take_error (simple, error);
936 g_simple_async_result_complete (simple);
937 g_object_unref (simple);
940 g_assert (bytes_written > 0); /* zero is never returned */
942 write_message_print_transport_debug (bytes_written, data);
944 data->total_written += bytes_written;
945 g_assert (data->total_written <= data->blob_size);
946 if (data->total_written == data->blob_size)
948 g_simple_async_result_complete (simple);
949 g_object_unref (simple);
953 write_message_continue_writing (data);
959 /* called in private thread shared by all GDBusConnection instances
961 * write-lock is not held on entry
962 * output_pending is PENDING_WRITE on entry
966 on_socket_ready (GSocket *socket,
967 GIOCondition condition,
970 MessageToWriteData *data = user_data;
971 write_message_continue_writing (data);
972 return FALSE; /* remove source */
976 /* called in private thread shared by all GDBusConnection instances
978 * write-lock is not held on entry
979 * output_pending is PENDING_WRITE on entry
982 write_message_continue_writing (MessageToWriteData *data)
984 GOutputStream *ostream;
986 GSimpleAsyncResult *simple;
987 GUnixFDList *fd_list;
991 /* Note: we can't access data->simple after calling g_async_result_complete () because the
992 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
994 simple = data->simple;
997 ostream = g_io_stream_get_output_stream (data->worker->stream);
999 fd_list = g_dbus_message_get_unix_fd_list (data->message);
1002 g_assert (!g_output_stream_has_pending (ostream));
1003 g_assert_cmpint (data->total_written, <, data->blob_size);
1009 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
1011 GOutputVector vector;
1012 GSocketControlMessage *control_message;
1013 gssize bytes_written;
1016 vector.buffer = data->blob;
1017 vector.size = data->blob_size;
1019 control_message = NULL;
1020 if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
1022 if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
1024 g_simple_async_result_set_error (simple,
1027 "Tried sending a file descriptor but remote peer does not support this capability");
1028 g_simple_async_result_complete (simple);
1029 g_object_unref (simple);
1032 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1036 bytes_written = g_socket_send_message (data->worker->socket,
1040 control_message != NULL ? &control_message : NULL,
1041 control_message != NULL ? 1 : 0,
1043 data->worker->cancellable,
1045 if (control_message != NULL)
1046 g_object_unref (control_message);
1048 if (bytes_written == -1)
1050 /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1051 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1054 source = g_socket_create_source (data->worker->socket,
1055 G_IO_OUT | G_IO_HUP | G_IO_ERR,
1056 data->worker->cancellable);
1057 g_source_set_callback (source,
1058 (GSourceFunc) on_socket_ready,
1060 NULL); /* GDestroyNotify */
1061 g_source_attach (source, g_main_context_get_thread_default ());
1062 g_source_unref (source);
1063 g_error_free (error);
1066 g_simple_async_result_take_error (simple, error);
1067 g_simple_async_result_complete (simple);
1068 g_object_unref (simple);
1071 g_assert (bytes_written > 0); /* zero is never returned */
1073 write_message_print_transport_debug (bytes_written, data);
1075 data->total_written += bytes_written;
1076 g_assert (data->total_written <= data->blob_size);
1077 if (data->total_written == data->blob_size)
1079 g_simple_async_result_complete (simple);
1080 g_object_unref (simple);
1084 write_message_continue_writing (data);
1090 if (fd_list != NULL)
1092 g_simple_async_result_set_error (simple,
1095 "Tried sending a file descriptor on unsupported stream of type %s",
1096 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1097 g_simple_async_result_complete (simple);
1098 g_object_unref (simple);
1103 g_output_stream_write_async (ostream,
1104 (const gchar *) data->blob + data->total_written,
1105 data->blob_size - data->total_written,
1107 data->worker->cancellable,
1108 write_message_async_cb,
1117 /* called in private thread shared by all GDBusConnection instances
1119 * write-lock is not held on entry
1120 * output_pending is PENDING_WRITE on entry
1123 write_message_async (GDBusWorker *worker,
1124 MessageToWriteData *data,
1125 GAsyncReadyCallback callback,
1128 data->simple = g_simple_async_result_new (NULL,
1131 write_message_async);
1132 data->total_written = 0;
1133 write_message_continue_writing (data);
1136 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1138 write_message_finish (GAsyncResult *res,
1141 g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1142 if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1147 /* ---------------------------------------------------------------------------------------------------- */
1149 static void continue_writing (GDBusWorker *worker);
1153 GDBusWorker *worker;
1158 flush_data_list_complete (const GList *flushers,
1159 const GError *error)
1163 for (l = flushers; l != NULL; l = l->next)
1165 FlushData *f = l->data;
1167 f->error = error != NULL ? g_error_copy (error) : NULL;
1169 g_mutex_lock (&f->mutex);
1170 g_cond_signal (&f->cond);
1171 g_mutex_unlock (&f->mutex);
1175 /* called in private thread shared by all GDBusConnection instances
1177 * write-lock is not held on entry
1178 * output_pending is PENDING_FLUSH on entry
1181 ostream_flush_cb (GObject *source_object,
1185 FlushAsyncData *data = user_data;
1189 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1195 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1197 _g_dbus_debug_print_lock ();
1198 g_print ("========================================================================\n"
1199 "GDBus-debug:Transport:\n"
1200 " ---- FLUSHED stream of type %s\n",
1201 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1202 _g_dbus_debug_print_unlock ();
1206 g_assert (data->flushers != NULL);
1207 flush_data_list_complete (data->flushers, error);
1208 g_list_free (data->flushers);
1211 g_error_free (error);
1213 /* Make sure we tell folks that we don't have additional
1215 g_mutex_lock (&data->worker->write_lock);
1216 data->worker->write_num_messages_flushed = data->worker->write_num_messages_written;
1217 g_assert (data->worker->output_pending == PENDING_FLUSH);
1218 data->worker->output_pending = PENDING_NONE;
1219 g_mutex_unlock (&data->worker->write_lock);
1221 /* OK, cool, finally kick off the next write */
1222 continue_writing (data->worker);
1224 _g_dbus_worker_unref (data->worker);
1228 /* called in private thread shared by all GDBusConnection instances
1230 * write-lock is not held on entry
1231 * output_pending is PENDING_FLUSH on entry
1234 start_flush (FlushAsyncData *data)
1236 g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1238 data->worker->cancellable,
1243 /* called in private thread shared by all GDBusConnection instances
1245 * write-lock is held on entry
1246 * output_pending is PENDING_NONE on entry
1249 message_written_unlocked (GDBusWorker *worker,
1250 MessageToWriteData *message_data)
1252 if (G_UNLIKELY (_g_dbus_debug_message ()))
1255 _g_dbus_debug_print_lock ();
1256 g_print ("========================================================================\n"
1257 "GDBus-debug:Message:\n"
1258 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1259 message_data->blob_size);
1260 s = g_dbus_message_print (message_data->message, 2);
1263 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1265 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1266 g_print ("%s\n", s);
1269 _g_dbus_debug_print_unlock ();
1272 worker->write_num_messages_written += 1;
1275 /* called in private thread shared by all GDBusConnection instances
1277 * write-lock is held on entry
1278 * output_pending is PENDING_NONE on entry
1280 * Returns: non-%NULL, setting @output_pending, if we need to flush now
1282 static FlushAsyncData *
1283 prepare_flush_unlocked (GDBusWorker *worker)
1290 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1292 FlushData *f = l->data;
1295 if (f->number_to_wait_for == worker->write_num_messages_written)
1297 flushers = g_list_append (flushers, f);
1298 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1301 if (flushers != NULL)
1303 g_assert (worker->output_pending == PENDING_NONE);
1304 worker->output_pending = PENDING_FLUSH;
1307 if (flushers != NULL)
1309 FlushAsyncData *data;
1311 data = g_new0 (FlushAsyncData, 1);
1312 data->worker = _g_dbus_worker_ref (worker);
1313 data->flushers = flushers;
1320 /* called in private thread shared by all GDBusConnection instances
1322 * write-lock is not held on entry
1323 * output_pending is PENDING_WRITE on entry
1326 write_message_cb (GObject *source_object,
1330 MessageToWriteData *data = user_data;
1333 g_mutex_lock (&data->worker->write_lock);
1334 g_assert (data->worker->output_pending == PENDING_WRITE);
1335 data->worker->output_pending = PENDING_NONE;
1338 if (!write_message_finish (res, &error))
1340 g_mutex_unlock (&data->worker->write_lock);
1343 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1344 g_error_free (error);
1346 g_mutex_lock (&data->worker->write_lock);
1349 message_written_unlocked (data->worker, data);
1351 g_mutex_unlock (&data->worker->write_lock);
1353 continue_writing (data->worker);
1355 message_to_write_data_free (data);
1358 /* called in private thread shared by all GDBusConnection instances
1360 * write-lock is not held on entry
1361 * output_pending is PENDING_CLOSE on entry
1364 iostream_close_cb (GObject *source_object,
1368 GDBusWorker *worker = user_data;
1369 GError *error = NULL;
1370 GList *pending_close_attempts, *pending_flush_attempts;
1373 g_io_stream_close_finish (worker->stream, res, &error);
1375 g_mutex_lock (&worker->write_lock);
1377 pending_close_attempts = worker->pending_close_attempts;
1378 worker->pending_close_attempts = NULL;
1380 pending_flush_attempts = worker->write_pending_flushes;
1381 worker->write_pending_flushes = NULL;
1383 send_queue = worker->write_queue;
1384 worker->write_queue = g_queue_new ();
1386 g_assert (worker->output_pending == PENDING_CLOSE);
1387 worker->output_pending = PENDING_NONE;
1389 g_mutex_unlock (&worker->write_lock);
1391 while (pending_close_attempts != NULL)
1393 CloseData *close_data = pending_close_attempts->data;
1395 pending_close_attempts = g_list_delete_link (pending_close_attempts,
1396 pending_close_attempts);
1398 if (close_data->result != NULL)
1401 g_simple_async_result_set_from_error (close_data->result, error);
1403 /* this must be in an idle because the result is likely to be
1404 * intended for another thread
1406 g_simple_async_result_complete_in_idle (close_data->result);
1409 close_data_free (close_data);
1412 g_clear_error (&error);
1414 /* all messages queued for sending are discarded */
1415 g_queue_free_full (send_queue, (GDestroyNotify) message_to_write_data_free);
1416 /* all queued flushes fail */
1417 error = g_error_new (G_IO_ERROR, G_IO_ERROR_CANCELLED,
1418 _("Operation was cancelled"));
1419 flush_data_list_complete (pending_flush_attempts, error);
1420 g_list_free (pending_flush_attempts);
1421 g_clear_error (&error);
1423 _g_dbus_worker_unref (worker);
1426 /* called in private thread shared by all GDBusConnection instances
1428 * write-lock is not held on entry
1429 * output_pending must be PENDING_NONE on entry
1432 continue_writing (GDBusWorker *worker)
1434 MessageToWriteData *data;
1435 FlushAsyncData *flush_async_data;
1438 /* we mustn't try to write two things at once */
1439 g_assert (worker->output_pending == PENDING_NONE);
1441 g_mutex_lock (&worker->write_lock);
1444 flush_async_data = NULL;
1446 /* if we want to close the connection, that takes precedence */
1447 if (worker->pending_close_attempts != NULL)
1449 worker->close_expected = TRUE;
1450 worker->output_pending = PENDING_CLOSE;
1452 g_io_stream_close_async (worker->stream, G_PRIORITY_DEFAULT,
1453 NULL, iostream_close_cb,
1454 _g_dbus_worker_ref (worker));
1458 flush_async_data = prepare_flush_unlocked (worker);
1460 if (flush_async_data == NULL)
1462 data = g_queue_pop_head (worker->write_queue);
1465 worker->output_pending = PENDING_WRITE;
1469 g_mutex_unlock (&worker->write_lock);
1471 /* Note that write_lock is only used for protecting the @write_queue
1472 * and @output_pending fields of the GDBusWorker struct ... which we
1473 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1475 * Therefore, it's fine to drop it here when calling back into user
1476 * code and then writing the message out onto the GIOStream since this
1477 * function only runs on the worker thread.
1480 if (flush_async_data != NULL)
1482 start_flush (flush_async_data);
1483 g_assert (data == NULL);
1485 else if (data != NULL)
1487 GDBusMessage *old_message;
1489 gsize new_blob_size;
1492 old_message = data->message;
1493 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1494 if (data->message == old_message)
1496 /* filters had no effect - do nothing */
1498 else if (data->message == NULL)
1500 /* filters dropped message */
1501 g_mutex_lock (&worker->write_lock);
1502 worker->output_pending = PENDING_NONE;
1503 g_mutex_unlock (&worker->write_lock);
1504 message_to_write_data_free (data);
1509 /* filters altered the message -> reencode */
1511 new_blob = g_dbus_message_to_blob (data->message,
1513 worker->capabilities,
1515 if (new_blob == NULL)
1517 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1518 * the old message instead
1520 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1521 g_dbus_message_get_serial (data->message),
1523 g_error_free (error);
1527 g_free (data->blob);
1528 data->blob = (gchar *) new_blob;
1529 data->blob_size = new_blob_size;
1533 write_message_async (worker,
1540 /* called in private thread shared by all GDBusConnection instances
1542 * write-lock is not held on entry
1543 * output_pending may be anything
1546 continue_writing_in_idle_cb (gpointer user_data)
1548 GDBusWorker *worker = user_data;
1550 /* Because this is the worker thread, we can read this struct member
1551 * without holding the lock: no other thread ever modifies it.
1553 if (worker->output_pending == PENDING_NONE)
1554 continue_writing (worker);
1560 * @write_data: (transfer full) (allow-none):
1561 * @flush_data: (transfer full) (allow-none):
1562 * @close_data: (transfer full) (allow-none):
1564 * Can be called from any thread
1566 * write_lock is held on entry
1567 * output_pending may be anything
1570 schedule_writing_unlocked (GDBusWorker *worker,
1571 MessageToWriteData *write_data,
1572 FlushData *flush_data,
1573 CloseData *close_data)
1575 if (write_data != NULL)
1576 g_queue_push_tail (worker->write_queue, write_data);
1578 if (flush_data != NULL)
1579 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, flush_data);
1581 if (close_data != NULL)
1582 worker->pending_close_attempts = g_list_prepend (worker->pending_close_attempts,
1585 /* If we had output pending, the next bit of output will happen
1586 * automatically when it finishes, so we only need to do this
1587 * if nothing was pending.
1589 * The idle callback will re-check that output_pending is still
1590 * PENDING_NONE, to guard against output starting before the idle.
1592 if (worker->output_pending == PENDING_NONE)
1594 GSource *idle_source;
1595 idle_source = g_idle_source_new ();
1596 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1597 g_source_set_callback (idle_source,
1598 continue_writing_in_idle_cb,
1599 _g_dbus_worker_ref (worker),
1600 (GDestroyNotify) _g_dbus_worker_unref);
1601 g_source_attach (idle_source, worker->shared_thread_data->context);
1602 g_source_unref (idle_source);
1606 /* ---------------------------------------------------------------------------------------------------- */
1608 /* can be called from any thread - steals blob
1610 * write_lock is not held on entry
1611 * output_pending may be anything
1614 _g_dbus_worker_send_message (GDBusWorker *worker,
1615 GDBusMessage *message,
1619 MessageToWriteData *data;
1621 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1622 g_return_if_fail (blob != NULL);
1623 g_return_if_fail (blob_len > 16);
1625 data = g_new0 (MessageToWriteData, 1);
1626 data->worker = _g_dbus_worker_ref (worker);
1627 data->message = g_object_ref (message);
1628 data->blob = blob; /* steal! */
1629 data->blob_size = blob_len;
1631 g_mutex_lock (&worker->write_lock);
1632 schedule_writing_unlocked (worker, data, NULL, NULL);
1633 g_mutex_unlock (&worker->write_lock);
1636 /* ---------------------------------------------------------------------------------------------------- */
1639 _g_dbus_worker_new (GIOStream *stream,
1640 GDBusCapabilityFlags capabilities,
1641 gboolean initially_frozen,
1642 GDBusWorkerMessageReceivedCallback message_received_callback,
1643 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1644 GDBusWorkerDisconnectedCallback disconnected_callback,
1647 GDBusWorker *worker;
1648 GSource *idle_source;
1650 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1651 g_return_val_if_fail (message_received_callback != NULL, NULL);
1652 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1653 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1655 worker = g_new0 (GDBusWorker, 1);
1656 worker->ref_count = 1;
1658 g_mutex_init (&worker->read_lock);
1659 worker->message_received_callback = message_received_callback;
1660 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1661 worker->disconnected_callback = disconnected_callback;
1662 worker->user_data = user_data;
1663 worker->stream = g_object_ref (stream);
1664 worker->capabilities = capabilities;
1665 worker->cancellable = g_cancellable_new ();
1666 worker->output_pending = PENDING_NONE;
1668 worker->frozen = initially_frozen;
1669 worker->received_messages_while_frozen = g_queue_new ();
1671 g_mutex_init (&worker->write_lock);
1672 worker->write_queue = g_queue_new ();
1674 if (G_IS_SOCKET_CONNECTION (worker->stream))
1675 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1677 worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1680 idle_source = g_idle_source_new ();
1681 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1682 g_source_set_callback (idle_source,
1683 _g_dbus_worker_do_initial_read,
1684 _g_dbus_worker_ref (worker),
1685 (GDestroyNotify) _g_dbus_worker_unref);
1686 g_source_attach (idle_source, worker->shared_thread_data->context);
1687 g_source_unref (idle_source);
1692 /* ---------------------------------------------------------------------------------------------------- */
1694 /* can be called from any thread
1696 * write_lock is not held on entry
1697 * output_pending may be anything
1700 _g_dbus_worker_close (GDBusWorker *worker,
1701 GCancellable *cancellable,
1702 GSimpleAsyncResult *result)
1704 CloseData *close_data;
1706 close_data = g_slice_new0 (CloseData);
1707 close_data->worker = _g_dbus_worker_ref (worker);
1708 close_data->cancellable =
1709 (cancellable == NULL ? NULL : g_object_ref (cancellable));
1710 close_data->result = (result == NULL ? NULL : g_object_ref (result));
1712 /* Don't set worker->close_expected here - we're in the wrong thread.
1713 * It'll be set before the actual close happens.
1715 g_cancellable_cancel (worker->cancellable);
1716 g_mutex_lock (&worker->write_lock);
1717 schedule_writing_unlocked (worker, NULL, NULL, close_data);
1718 g_mutex_unlock (&worker->write_lock);
1721 /* This can be called from any thread - frees worker. Note that
1722 * callbacks might still happen if called from another thread than the
1723 * worker - use your own synchronization primitive in the callbacks.
1725 * write_lock is not held on entry
1726 * output_pending may be anything
1729 _g_dbus_worker_stop (GDBusWorker *worker)
1731 g_atomic_int_set (&worker->stopped, TRUE);
1733 /* Cancel any pending operations and schedule a close of the underlying I/O
1734 * stream in the worker thread
1736 _g_dbus_worker_close (worker, NULL, NULL);
1738 /* _g_dbus_worker_close holds a ref until after an idle in the worker
1739 * thread has run, so we no longer need to unref in an idle like in
1742 _g_dbus_worker_unref (worker);
1745 /* ---------------------------------------------------------------------------------------------------- */
1747 /* can be called from any thread (except the worker thread) - blocks
1748 * calling thread until all queued outgoing messages are written and
1749 * the transport has been flushed
1751 * write_lock is not held on entry
1752 * output_pending may be anything
1755 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1756 GCancellable *cancellable,
1761 guint64 pending_writes;
1766 g_mutex_lock (&worker->write_lock);
1768 /* if the queue is empty, no write is in-flight and we haven't written
1769 * anything since the last flush, then there's nothing to wait for
1771 pending_writes = g_queue_get_length (worker->write_queue);
1773 /* if a write is in-flight, we shouldn't be satisfied until the first
1774 * flush operation that follows it
1776 if (worker->output_pending == PENDING_WRITE)
1777 pending_writes += 1;
1779 if (pending_writes > 0 ||
1780 worker->write_num_messages_written != worker->write_num_messages_flushed)
1782 data = g_new0 (FlushData, 1);
1783 g_mutex_init (&data->mutex);
1784 g_cond_init (&data->cond);
1785 data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
1786 g_mutex_lock (&data->mutex);
1788 schedule_writing_unlocked (worker, NULL, data, NULL);
1790 g_mutex_unlock (&worker->write_lock);
1794 g_cond_wait (&data->cond, &data->mutex);
1795 g_mutex_unlock (&data->mutex);
1797 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1798 g_cond_clear (&data->cond);
1799 g_mutex_clear (&data->mutex);
1800 if (data->error != NULL)
1803 g_propagate_error (error, data->error);
1811 /* ---------------------------------------------------------------------------------------------------- */
1813 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1814 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1815 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1816 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1817 #define G_DBUS_DEBUG_CALL (1<<4)
1818 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1819 #define G_DBUS_DEBUG_INCOMING (1<<6)
1820 #define G_DBUS_DEBUG_RETURN (1<<7)
1821 #define G_DBUS_DEBUG_EMISSION (1<<8)
1822 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1824 static gint _gdbus_debug_flags = 0;
1827 _g_dbus_debug_authentication (void)
1829 _g_dbus_initialize ();
1830 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1834 _g_dbus_debug_transport (void)
1836 _g_dbus_initialize ();
1837 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1841 _g_dbus_debug_message (void)
1843 _g_dbus_initialize ();
1844 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1848 _g_dbus_debug_payload (void)
1850 _g_dbus_initialize ();
1851 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1855 _g_dbus_debug_call (void)
1857 _g_dbus_initialize ();
1858 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1862 _g_dbus_debug_signal (void)
1864 _g_dbus_initialize ();
1865 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1869 _g_dbus_debug_incoming (void)
1871 _g_dbus_initialize ();
1872 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1876 _g_dbus_debug_return (void)
1878 _g_dbus_initialize ();
1879 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1883 _g_dbus_debug_emission (void)
1885 _g_dbus_initialize ();
1886 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1890 _g_dbus_debug_address (void)
1892 _g_dbus_initialize ();
1893 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1896 G_LOCK_DEFINE_STATIC (print_lock);
1899 _g_dbus_debug_print_lock (void)
1901 G_LOCK (print_lock);
1905 _g_dbus_debug_print_unlock (void)
1907 G_UNLOCK (print_lock);
1911 * _g_dbus_initialize:
1913 * Does various one-time init things such as
1915 * - registering the G_DBUS_ERROR error domain
1916 * - parses the G_DBUS_DEBUG environment variable
1919 _g_dbus_initialize (void)
1921 static volatile gsize initialized = 0;
1923 if (g_once_init_enter (&initialized))
1925 volatile GQuark g_dbus_error_domain;
1928 g_dbus_error_domain = G_DBUS_ERROR;
1929 (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1931 debug = g_getenv ("G_DBUS_DEBUG");
1934 const GDebugKey keys[] = {
1935 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1936 { "transport", G_DBUS_DEBUG_TRANSPORT },
1937 { "message", G_DBUS_DEBUG_MESSAGE },
1938 { "payload", G_DBUS_DEBUG_PAYLOAD },
1939 { "call", G_DBUS_DEBUG_CALL },
1940 { "signal", G_DBUS_DEBUG_SIGNAL },
1941 { "incoming", G_DBUS_DEBUG_INCOMING },
1942 { "return", G_DBUS_DEBUG_RETURN },
1943 { "emission", G_DBUS_DEBUG_EMISSION },
1944 { "address", G_DBUS_DEBUG_ADDRESS }
1947 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1948 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1949 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1952 g_once_init_leave (&initialized, 1);
1956 /* ---------------------------------------------------------------------------------------------------- */
1959 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1961 const GVariantType *arg_types[256];
1965 for (n = 0; args[n] != NULL; n++)
1967 /* DBus places a hard limit of 255 on signature length.
1968 * therefore number of args must be less than 256.
1972 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1974 if G_UNLIKELY (arg_types[n] == NULL)
1980 return g_variant_type_new_tuple (arg_types, n);
1983 /* ---------------------------------------------------------------------------------------------------- */
1987 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1990 _g_dbus_win32_get_user_sid (void)
1994 DWORD token_information_len;
2001 h = INVALID_HANDLE_VALUE;
2003 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
2005 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
2009 /* Get length of buffer */
2010 token_information_len = 0;
2011 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
2013 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
2015 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2019 user = g_malloc (token_information_len);
2020 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
2022 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2026 psid = user->User.Sid;
2027 if (!IsValidSid (psid))
2029 g_warning ("Invalid SID");
2033 if (!ConvertSidToStringSidA (psid, &sid))
2035 g_warning ("Invalid SID");
2039 ret = g_strdup (sid);
2044 if (h != INVALID_HANDLE_VALUE)
2050 /* ---------------------------------------------------------------------------------------------------- */
2053 _g_dbus_get_machine_id (GError **error)
2056 HW_PROFILE_INFOA info;
2057 char *src, *dest, *res;
2060 if (!GetCurrentHwProfileA (&info))
2062 char *message = g_win32_error_message (GetLastError ());
2066 _("Unable to get Hardware profile: %s"), message);
2071 /* Form: {12340001-4980-1920-6788-123456789012} */
2072 src = &info.szHwProfileGuid[0];
2074 res = g_malloc (32+1);
2078 for (i = 0; i < 8; i++)
2081 for (i = 0; i < 4; i++)
2084 for (i = 0; i < 4; i++)
2087 for (i = 0; i < 4; i++)
2090 for (i = 0; i < 12; i++)
2097 GError *first_error;
2098 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2101 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2105 !g_file_get_contents ("/etc/machine-id",
2110 g_propagate_prefixed_error (error, first_error,
2111 _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2115 /* ignore the error from the first try, if any */
2116 g_clear_error (&first_error);
2117 /* TODO: validate value */
2124 /* ---------------------------------------------------------------------------------------------------- */
2127 _g_dbus_enum_to_string (GType enum_type, gint value)
2131 GEnumValue *enum_value;
2133 klass = g_type_class_ref (enum_type);
2134 enum_value = g_enum_get_value (klass, value);
2135 if (enum_value != NULL)
2136 ret = g_strdup (enum_value->value_nick);
2138 ret = g_strdup_printf ("unknown (value %d)", value);
2139 g_type_class_unref (klass);
2143 /* ---------------------------------------------------------------------------------------------------- */
2146 write_message_print_transport_debug (gssize bytes_written,
2147 MessageToWriteData *data)
2149 if (G_LIKELY (!_g_dbus_debug_transport ()))
2152 _g_dbus_debug_print_lock ();
2153 g_print ("========================================================================\n"
2154 "GDBus-debug:Transport:\n"
2155 " >>>> WROTE %" G_GSSIZE_FORMAT " bytes of message with serial %d and\n"
2156 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
2158 g_dbus_message_get_serial (data->message),
2160 data->total_written,
2161 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
2162 _g_dbus_debug_print_unlock ();
2167 /* ---------------------------------------------------------------------------------------------------- */
2170 read_message_print_transport_debug (gssize bytes_read,
2171 GDBusWorker *worker)
2175 gint32 message_length;
2177 if (G_LIKELY (!_g_dbus_debug_transport ()))
2180 size = bytes_read + worker->read_buffer_cur_size;
2184 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2187 switch (worker->read_buffer[0])
2191 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2195 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2198 /* an error will be set elsewhere if this happens */
2203 _g_dbus_debug_print_lock ();
2204 g_print ("========================================================================\n"
2205 "GDBus-debug:Transport:\n"
2206 " <<<< READ %" G_GSSIZE_FORMAT " bytes of message with serial %d and\n"
2207 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
2211 worker->read_buffer_cur_size,
2212 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
2213 _g_dbus_debug_print_unlock ();
2218 /* ---------------------------------------------------------------------------------------------------- */
2221 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2222 GValue *return_accu,
2223 const GValue *handler_return,
2226 gboolean continue_emission;
2227 gboolean signal_return;
2229 signal_return = g_value_get_boolean (handler_return);
2230 g_value_set_boolean (return_accu, signal_return);
2231 continue_emission = signal_return;
2233 return continue_emission;