1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
33 #include "gdbusprivate.h"
34 #include "gdbusmessage.h"
35 #include "gdbuserror.h"
36 #include "gdbusintrospection.h"
37 #include "gasyncresult.h"
38 #include "gsimpleasyncresult.h"
39 #include "ginputstream.h"
40 #include "gmemoryinputstream.h"
41 #include "giostream.h"
42 #include "gsocketcontrolmessage.h"
43 #include "gsocketconnection.h"
44 #include "gsocketoutputstream.h"
47 #include "gunixfdmessage.h"
48 #include "gunixconnection.h"
49 #include "gunixcredentialsmessage.h"
58 static gboolean _g_dbus_worker_do_initial_read (gpointer data);
60 /* ---------------------------------------------------------------------------------------------------- */
63 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
68 ret = g_string_new (NULL);
70 for (n = 0; n < len; n += 16)
72 g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
74 for (m = n; m < n + 16; m++)
76 if (m > n && (m%4) == 0)
77 g_string_append_c (ret, ' ');
79 g_string_append_printf (ret, "%02x ", (guchar) data[m]);
81 g_string_append (ret, " ");
84 g_string_append (ret, " ");
86 for (m = n; m < len && m < n + 16; m++)
87 g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
89 g_string_append_c (ret, '\n');
92 return g_string_free (ret, FALSE);
95 /* ---------------------------------------------------------------------------------------------------- */
97 /* Unfortunately ancillary messages are discarded when reading from a
98 * socket using the GSocketInputStream abstraction. So we provide a
99 * very GInputStream-ish API that uses GSocket in this case (very
100 * similar to GSocketInputStream).
106 GCancellable *cancellable;
111 GSocketControlMessage ***messages;
114 GSimpleAsyncResult *simple;
116 gboolean from_mainloop;
117 } ReadWithControlData;
120 read_with_control_data_free (ReadWithControlData *data)
122 g_object_unref (data->socket);
123 if (data->cancellable != NULL)
124 g_object_unref (data->cancellable);
125 g_object_unref (data->simple);
130 _g_socket_read_with_control_messages_ready (GSocket *socket,
131 GIOCondition condition,
134 ReadWithControlData *data = user_data;
140 vector.buffer = data->buffer;
141 vector.size = data->count;
142 result = g_socket_receive_message (data->socket,
153 g_simple_async_result_set_op_res_gssize (data->simple, result);
157 g_assert (error != NULL);
158 g_simple_async_result_take_error (data->simple, error);
161 if (data->from_mainloop)
162 g_simple_async_result_complete (data->simple);
164 g_simple_async_result_complete_in_idle (data->simple);
170 _g_socket_read_with_control_messages (GSocket *socket,
173 GSocketControlMessage ***messages,
176 GCancellable *cancellable,
177 GAsyncReadyCallback callback,
180 ReadWithControlData *data;
182 data = g_new0 (ReadWithControlData, 1);
183 data->socket = g_object_ref (socket);
184 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
185 data->buffer = buffer;
187 data->messages = messages;
188 data->num_messages = num_messages;
190 data->simple = g_simple_async_result_new (G_OBJECT (socket),
193 _g_socket_read_with_control_messages);
195 if (!g_socket_condition_check (socket, G_IO_IN))
198 data->from_mainloop = TRUE;
199 source = g_socket_create_source (data->socket,
200 G_IO_IN | G_IO_HUP | G_IO_ERR,
202 g_source_set_callback (source,
203 (GSourceFunc) _g_socket_read_with_control_messages_ready,
205 (GDestroyNotify) read_with_control_data_free);
206 g_source_attach (source, g_main_context_get_thread_default ());
207 g_source_unref (source);
211 _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
212 read_with_control_data_free (data);
217 _g_socket_read_with_control_messages_finish (GSocket *socket,
218 GAsyncResult *result,
221 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
223 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
224 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
226 if (g_simple_async_result_propagate_error (simple, error))
229 return g_simple_async_result_get_op_res_gssize (simple);
232 /* ---------------------------------------------------------------------------------------------------- */
234 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
236 static GPtrArray *ensured_classes = NULL;
239 ensure_type (GType gtype)
241 g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
245 release_required_types (void)
247 g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
248 g_ptr_array_unref (ensured_classes);
249 ensured_classes = NULL;
253 ensure_required_types (void)
255 g_assert (ensured_classes == NULL);
256 ensured_classes = g_ptr_array_new ();
257 ensure_type (G_TYPE_SIMPLE_ASYNC_RESULT);
258 ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
260 /* ---------------------------------------------------------------------------------------------------- */
264 volatile gint refcount;
266 GMainContext *context;
271 gdbus_shared_thread_func (gpointer user_data)
273 SharedThreadData *data = user_data;
275 g_main_context_push_thread_default (data->context);
276 g_main_loop_run (data->loop);
277 g_main_context_pop_thread_default (data->context);
279 release_required_types ();
284 /* ---------------------------------------------------------------------------------------------------- */
286 static SharedThreadData *
287 _g_dbus_shared_thread_ref (void)
289 static gsize shared_thread_data = 0;
290 SharedThreadData *ret;
292 if (g_once_init_enter (&shared_thread_data))
294 SharedThreadData *data;
296 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
297 ensure_required_types ();
299 data = g_new0 (SharedThreadData, 1);
302 data->context = g_main_context_new ();
303 data->loop = g_main_loop_new (data->context, FALSE);
304 data->thread = g_thread_new ("gdbus",
305 gdbus_shared_thread_func,
307 /* We can cast between gsize and gpointer safely */
308 g_once_init_leave (&shared_thread_data, (gsize) data);
311 ret = (SharedThreadData*) shared_thread_data;
312 g_atomic_int_inc (&ret->refcount);
317 _g_dbus_shared_thread_unref (SharedThreadData *data)
319 /* TODO: actually destroy the shared thread here */
321 g_assert (data != NULL);
322 if (g_atomic_int_dec_and_test (&data->refcount))
324 g_main_loop_quit (data->loop);
325 //g_thread_join (data->thread);
326 g_main_loop_unref (data->loop);
327 g_main_context_unref (data->context);
332 /* ---------------------------------------------------------------------------------------------------- */
343 volatile gint ref_count;
345 SharedThreadData *shared_thread_data;
347 /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
348 volatile gint stopped;
350 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
351 * only affects messages received from the other peer (since GDBusServer is the
352 * only user) - we might want it to affect messages sent to the other peer too?
355 GDBusCapabilityFlags capabilities;
356 GQueue *received_messages_while_frozen;
359 GCancellable *cancellable;
360 GDBusWorkerMessageReceivedCallback message_received_callback;
361 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
362 GDBusWorkerDisconnectedCallback disconnected_callback;
365 /* if not NULL, stream is GSocketConnection */
368 /* used for reading */
371 gsize read_buffer_allocated_size;
372 gsize read_buffer_cur_size;
373 gsize read_buffer_bytes_wanted;
374 GUnixFDList *read_fd_list;
375 GSocketControlMessage **read_ancillary_messages;
376 gint read_num_ancillary_messages;
378 /* Whether an async write, flush or close, or none of those, is pending.
379 * Only the worker thread may change its value, and only with the write_lock.
380 * Other threads may read its value when holding the write_lock.
381 * The worker thread may read its value at any time.
383 OutputPending output_pending;
384 /* used for writing */
386 /* queue of MessageToWriteData, protected by write_lock */
388 /* protected by write_lock */
389 guint64 write_num_messages_written;
390 /* number of messages we'd written out last time we flushed;
391 * protected by write_lock
393 guint64 write_num_messages_flushed;
394 /* list of FlushData, protected by write_lock */
395 GList *write_pending_flushes;
396 /* list of CloseData, protected by write_lock */
397 GList *pending_close_attempts;
398 /* no lock - only used from the worker thread */
399 gboolean close_expected;
402 static void _g_dbus_worker_unref (GDBusWorker *worker);
404 /* ---------------------------------------------------------------------------------------------------- */
410 guint64 number_to_wait_for;
414 struct _MessageToWriteData ;
415 typedef struct _MessageToWriteData MessageToWriteData;
417 static void message_to_write_data_free (MessageToWriteData *data);
419 static void read_message_print_transport_debug (gssize bytes_read,
420 GDBusWorker *worker);
422 static void write_message_print_transport_debug (gssize bytes_written,
423 MessageToWriteData *data);
427 GCancellable *cancellable;
428 GSimpleAsyncResult *result;
431 static void close_data_free (CloseData *close_data)
433 if (close_data->cancellable != NULL)
434 g_object_unref (close_data->cancellable);
436 if (close_data->result != NULL)
437 g_object_unref (close_data->result);
439 _g_dbus_worker_unref (close_data->worker);
440 g_slice_free (CloseData, close_data);
443 /* ---------------------------------------------------------------------------------------------------- */
446 _g_dbus_worker_ref (GDBusWorker *worker)
448 g_atomic_int_inc (&worker->ref_count);
453 _g_dbus_worker_unref (GDBusWorker *worker)
455 if (g_atomic_int_dec_and_test (&worker->ref_count))
457 g_assert (worker->write_pending_flushes == NULL);
459 _g_dbus_shared_thread_unref (worker->shared_thread_data);
461 g_object_unref (worker->stream);
463 g_mutex_clear (&worker->read_lock);
464 g_object_unref (worker->cancellable);
465 if (worker->read_fd_list != NULL)
466 g_object_unref (worker->read_fd_list);
468 g_queue_free_full (worker->received_messages_while_frozen, (GDestroyNotify) g_object_unref);
469 g_mutex_clear (&worker->write_lock);
470 g_queue_free_full (worker->write_queue, (GDestroyNotify) message_to_write_data_free);
471 g_free (worker->read_buffer);
478 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
479 gboolean remote_peer_vanished,
482 if (!g_atomic_int_get (&worker->stopped))
483 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
487 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
488 GDBusMessage *message)
490 if (!g_atomic_int_get (&worker->stopped))
491 worker->message_received_callback (worker, message, worker->user_data);
494 static GDBusMessage *
495 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
496 GDBusMessage *message)
499 if (!g_atomic_int_get (&worker->stopped))
500 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
506 /* can only be called from private thread with read-lock held - takes ownership of @message */
508 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
509 GDBusMessage *message)
511 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
514 g_queue_push_tail (worker->received_messages_while_frozen, message);
518 /* not frozen, nor anything in queue */
519 _g_dbus_worker_emit_message_received (worker, message);
520 g_object_unref (message);
524 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
526 unfreeze_in_idle_cb (gpointer user_data)
528 GDBusWorker *worker = user_data;
529 GDBusMessage *message;
531 g_mutex_lock (&worker->read_lock);
534 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
536 _g_dbus_worker_emit_message_received (worker, message);
537 g_object_unref (message);
539 worker->frozen = FALSE;
543 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
545 g_mutex_unlock (&worker->read_lock);
549 /* can be called from any thread */
551 _g_dbus_worker_unfreeze (GDBusWorker *worker)
553 GSource *idle_source;
554 idle_source = g_idle_source_new ();
555 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
556 g_source_set_callback (idle_source,
558 _g_dbus_worker_ref (worker),
559 (GDestroyNotify) _g_dbus_worker_unref);
560 g_source_attach (idle_source, worker->shared_thread_data->context);
561 g_source_unref (idle_source);
564 /* ---------------------------------------------------------------------------------------------------- */
566 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
568 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
570 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
574 GDBusWorker *worker = user_data;
578 g_mutex_lock (&worker->read_lock);
580 /* If already stopped, don't even process the reply */
581 if (g_atomic_int_get (&worker->stopped))
585 if (worker->socket == NULL)
586 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
590 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
593 if (worker->read_num_ancillary_messages > 0)
596 for (n = 0; n < worker->read_num_ancillary_messages; n++)
598 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
604 else if (G_IS_UNIX_FD_MESSAGE (control_message))
606 GUnixFDMessage *fd_message;
610 fd_message = G_UNIX_FD_MESSAGE (control_message);
611 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
612 if (worker->read_fd_list == NULL)
614 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
619 for (n = 0; n < num_fds; n++)
621 /* TODO: really want a append_steal() */
622 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
628 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
640 "Unexpected ancillary message of type %s received from peer",
641 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
642 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
643 g_error_free (error);
644 g_object_unref (control_message);
646 while (n < worker->read_num_ancillary_messages)
647 g_object_unref (worker->read_ancillary_messages[n++]);
648 g_free (worker->read_ancillary_messages);
652 g_object_unref (control_message);
654 g_free (worker->read_ancillary_messages);
657 if (bytes_read == -1)
659 if (G_UNLIKELY (_g_dbus_debug_transport ()))
661 _g_dbus_debug_print_lock ();
662 g_print ("========================================================================\n"
663 "GDBus-debug:Transport:\n"
664 " ---- READ ERROR on stream of type %s:\n"
666 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))),
667 g_quark_to_string (error->domain), error->code,
669 _g_dbus_debug_print_unlock ();
672 /* Every async read that uses this callback uses worker->cancellable
673 * as its GCancellable. worker->cancellable gets cancelled if and only
674 * if the GDBusConnection tells us to close (either via
675 * _g_dbus_worker_stop, which is called on last-unref, or directly),
676 * so a cancelled read must mean our connection was closed locally.
678 * If we're closing, other errors are possible - notably,
679 * G_IO_ERROR_CLOSED can be seen if we close the stream with an async
680 * read in-flight. It seems sensible to treat all read errors during
681 * closing as an expected thing that doesn't trip exit-on-close.
683 * Because close_expected can't be set until we get into the worker
684 * thread, but the cancellable is signalled sooner (from another
685 * thread), we do still need to check the error.
687 if (worker->close_expected ||
688 g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
689 _g_dbus_worker_emit_disconnected (worker, FALSE, NULL);
691 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
693 g_error_free (error);
698 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
700 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
701 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
702 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
703 G_IO_IN | G_IO_OUT | G_IO_HUP),
708 /* TODO: hmm, hmm... */
714 "Underlying GIOStream returned 0 bytes on an async read");
715 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
716 g_error_free (error);
720 read_message_print_transport_debug (bytes_read, worker);
722 worker->read_buffer_cur_size += bytes_read;
723 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
725 /* OK, got what we asked for! */
726 if (worker->read_buffer_bytes_wanted == 16)
729 /* OK, got the header - determine how many more bytes are needed */
731 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
734 if (message_len == -1)
736 g_warning ("_g_dbus_worker_do_read_cb: error determing bytes needed: %s", error->message);
737 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
738 g_error_free (error);
742 worker->read_buffer_bytes_wanted = message_len;
743 _g_dbus_worker_do_read_unlocked (worker);
747 GDBusMessage *message;
750 /* TODO: use connection->priv->auth to decode the message */
752 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
753 worker->read_buffer_cur_size,
754 worker->capabilities,
759 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
760 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
762 "The payload is as follows:\n"
764 worker->read_buffer_cur_size,
768 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
769 g_error_free (error);
774 if (worker->read_fd_list != NULL)
776 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
777 g_object_unref (worker->read_fd_list);
778 worker->read_fd_list = NULL;
782 if (G_UNLIKELY (_g_dbus_debug_message ()))
785 _g_dbus_debug_print_lock ();
786 g_print ("========================================================================\n"
787 "GDBus-debug:Message:\n"
788 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
789 worker->read_buffer_cur_size);
790 s = g_dbus_message_print (message, 2);
793 if (G_UNLIKELY (_g_dbus_debug_payload ()))
795 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
799 _g_dbus_debug_print_unlock ();
802 /* yay, got a message, go deliver it */
803 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
805 /* start reading another message! */
806 worker->read_buffer_bytes_wanted = 0;
807 worker->read_buffer_cur_size = 0;
808 _g_dbus_worker_do_read_unlocked (worker);
813 /* didn't get all the bytes we requested - so repeat the request... */
814 _g_dbus_worker_do_read_unlocked (worker);
818 g_mutex_unlock (&worker->read_lock);
820 /* gives up the reference acquired when calling g_input_stream_read_async() */
821 _g_dbus_worker_unref (worker);
824 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
826 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
828 /* Note that we do need to keep trying to read even if close_expected is
829 * true, because only failing a read causes us to signal 'closed'.
832 /* if bytes_wanted is zero, it means start reading a message */
833 if (worker->read_buffer_bytes_wanted == 0)
835 worker->read_buffer_cur_size = 0;
836 worker->read_buffer_bytes_wanted = 16;
839 /* ensure we have a (big enough) buffer */
840 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
842 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
843 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
844 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
847 if (worker->socket == NULL)
848 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
849 worker->read_buffer + worker->read_buffer_cur_size,
850 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
853 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
854 _g_dbus_worker_ref (worker));
857 worker->read_ancillary_messages = NULL;
858 worker->read_num_ancillary_messages = 0;
859 _g_socket_read_with_control_messages (worker->socket,
860 worker->read_buffer + worker->read_buffer_cur_size,
861 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
862 &worker->read_ancillary_messages,
863 &worker->read_num_ancillary_messages,
866 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
867 _g_dbus_worker_ref (worker));
871 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
873 _g_dbus_worker_do_initial_read (gpointer data)
875 GDBusWorker *worker = data;
876 g_mutex_lock (&worker->read_lock);
877 _g_dbus_worker_do_read_unlocked (worker);
878 g_mutex_unlock (&worker->read_lock);
882 /* ---------------------------------------------------------------------------------------------------- */
884 struct _MessageToWriteData
887 GDBusMessage *message;
892 GSimpleAsyncResult *simple;
897 message_to_write_data_free (MessageToWriteData *data)
899 _g_dbus_worker_unref (data->worker);
901 g_object_unref (data->message);
906 /* ---------------------------------------------------------------------------------------------------- */
908 static void write_message_continue_writing (MessageToWriteData *data);
910 /* called in private thread shared by all GDBusConnection instances
912 * write-lock is not held on entry
913 * output_pending is PENDING_WRITE on entry
916 write_message_async_cb (GObject *source_object,
920 MessageToWriteData *data = user_data;
921 GSimpleAsyncResult *simple;
922 gssize bytes_written;
925 /* Note: we can't access data->simple after calling g_async_result_complete () because the
926 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
928 simple = data->simple;
931 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
934 if (bytes_written == -1)
936 g_simple_async_result_take_error (simple, error);
937 g_simple_async_result_complete (simple);
938 g_object_unref (simple);
941 g_assert (bytes_written > 0); /* zero is never returned */
943 write_message_print_transport_debug (bytes_written, data);
945 data->total_written += bytes_written;
946 g_assert (data->total_written <= data->blob_size);
947 if (data->total_written == data->blob_size)
949 g_simple_async_result_complete (simple);
950 g_object_unref (simple);
954 write_message_continue_writing (data);
960 /* called in private thread shared by all GDBusConnection instances
962 * write-lock is not held on entry
963 * 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 */
975 /* called in private thread shared by all GDBusConnection instances
977 * write-lock is not held on entry
978 * output_pending is PENDING_WRITE on entry
981 write_message_continue_writing (MessageToWriteData *data)
983 GOutputStream *ostream;
984 GSimpleAsyncResult *simple;
986 GUnixFDList *fd_list;
989 /* Note: we can't access data->simple after calling g_async_result_complete () because the
990 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
992 simple = data->simple;
994 ostream = g_io_stream_get_output_stream (data->worker->stream);
996 fd_list = g_dbus_message_get_unix_fd_list (data->message);
999 g_assert (!g_output_stream_has_pending (ostream));
1000 g_assert_cmpint (data->total_written, <, data->blob_size);
1006 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
1008 GOutputVector vector;
1009 GSocketControlMessage *control_message;
1010 gssize bytes_written;
1013 vector.buffer = data->blob;
1014 vector.size = data->blob_size;
1016 control_message = NULL;
1017 if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
1019 if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
1021 g_simple_async_result_set_error (simple,
1024 "Tried sending a file descriptor but remote peer does not support this capability");
1025 g_simple_async_result_complete (simple);
1026 g_object_unref (simple);
1029 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1033 bytes_written = g_socket_send_message (data->worker->socket,
1037 control_message != NULL ? &control_message : NULL,
1038 control_message != NULL ? 1 : 0,
1040 data->worker->cancellable,
1042 if (control_message != NULL)
1043 g_object_unref (control_message);
1045 if (bytes_written == -1)
1047 /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1048 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1051 source = g_socket_create_source (data->worker->socket,
1052 G_IO_OUT | G_IO_HUP | G_IO_ERR,
1053 data->worker->cancellable);
1054 g_source_set_callback (source,
1055 (GSourceFunc) on_socket_ready,
1057 NULL); /* GDestroyNotify */
1058 g_source_attach (source, g_main_context_get_thread_default ());
1059 g_source_unref (source);
1060 g_error_free (error);
1063 g_simple_async_result_take_error (simple, error);
1064 g_simple_async_result_complete (simple);
1065 g_object_unref (simple);
1068 g_assert (bytes_written > 0); /* zero is never returned */
1070 write_message_print_transport_debug (bytes_written, data);
1072 data->total_written += bytes_written;
1073 g_assert (data->total_written <= data->blob_size);
1074 if (data->total_written == data->blob_size)
1076 g_simple_async_result_complete (simple);
1077 g_object_unref (simple);
1081 write_message_continue_writing (data);
1087 if (fd_list != NULL)
1089 g_simple_async_result_set_error (simple,
1092 "Tried sending a file descriptor on unsupported stream of type %s",
1093 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1094 g_simple_async_result_complete (simple);
1095 g_object_unref (simple);
1100 g_output_stream_write_async (ostream,
1101 (const gchar *) data->blob + data->total_written,
1102 data->blob_size - data->total_written,
1104 data->worker->cancellable,
1105 write_message_async_cb,
1112 /* called in private thread shared by all GDBusConnection instances
1114 * write-lock is not held on entry
1115 * output_pending is PENDING_WRITE on entry
1118 write_message_async (GDBusWorker *worker,
1119 MessageToWriteData *data,
1120 GAsyncReadyCallback callback,
1123 data->simple = g_simple_async_result_new (NULL,
1126 write_message_async);
1127 data->total_written = 0;
1128 write_message_continue_writing (data);
1131 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1133 write_message_finish (GAsyncResult *res,
1136 g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1137 if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1142 /* ---------------------------------------------------------------------------------------------------- */
1144 static void continue_writing (GDBusWorker *worker);
1148 GDBusWorker *worker;
1153 flush_data_list_complete (const GList *flushers,
1154 const GError *error)
1158 for (l = flushers; l != NULL; l = l->next)
1160 FlushData *f = l->data;
1162 f->error = error != NULL ? g_error_copy (error) : NULL;
1164 g_mutex_lock (&f->mutex);
1165 g_cond_signal (&f->cond);
1166 g_mutex_unlock (&f->mutex);
1170 /* called in private thread shared by all GDBusConnection instances
1172 * write-lock is not held on entry
1173 * output_pending is PENDING_FLUSH on entry
1176 ostream_flush_cb (GObject *source_object,
1180 FlushAsyncData *data = user_data;
1184 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1190 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1192 _g_dbus_debug_print_lock ();
1193 g_print ("========================================================================\n"
1194 "GDBus-debug:Transport:\n"
1195 " ---- FLUSHED stream of type %s\n",
1196 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1197 _g_dbus_debug_print_unlock ();
1201 g_assert (data->flushers != NULL);
1202 flush_data_list_complete (data->flushers, error);
1203 g_list_free (data->flushers);
1206 g_error_free (error);
1208 /* Make sure we tell folks that we don't have additional
1210 g_mutex_lock (&data->worker->write_lock);
1211 data->worker->write_num_messages_flushed = data->worker->write_num_messages_written;
1212 g_assert (data->worker->output_pending == PENDING_FLUSH);
1213 data->worker->output_pending = PENDING_NONE;
1214 g_mutex_unlock (&data->worker->write_lock);
1216 /* OK, cool, finally kick off the next write */
1217 continue_writing (data->worker);
1219 _g_dbus_worker_unref (data->worker);
1223 /* called in private thread shared by all GDBusConnection instances
1225 * write-lock is not held on entry
1226 * output_pending is PENDING_FLUSH on entry
1229 start_flush (FlushAsyncData *data)
1231 g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1233 data->worker->cancellable,
1238 /* called in private thread shared by all GDBusConnection instances
1240 * write-lock is held on entry
1241 * output_pending is PENDING_NONE on entry
1244 message_written_unlocked (GDBusWorker *worker,
1245 MessageToWriteData *message_data)
1247 if (G_UNLIKELY (_g_dbus_debug_message ()))
1250 _g_dbus_debug_print_lock ();
1251 g_print ("========================================================================\n"
1252 "GDBus-debug:Message:\n"
1253 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1254 message_data->blob_size);
1255 s = g_dbus_message_print (message_data->message, 2);
1258 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1260 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1261 g_print ("%s\n", s);
1264 _g_dbus_debug_print_unlock ();
1267 worker->write_num_messages_written += 1;
1270 /* called in private thread shared by all GDBusConnection instances
1272 * write-lock is held on entry
1273 * output_pending is PENDING_NONE on entry
1275 * Returns: non-%NULL, setting @output_pending, if we need to flush now
1277 static FlushAsyncData *
1278 prepare_flush_unlocked (GDBusWorker *worker)
1285 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1287 FlushData *f = l->data;
1290 if (f->number_to_wait_for == worker->write_num_messages_written)
1292 flushers = g_list_append (flushers, f);
1293 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1296 if (flushers != NULL)
1298 g_assert (worker->output_pending == PENDING_NONE);
1299 worker->output_pending = PENDING_FLUSH;
1302 if (flushers != NULL)
1304 FlushAsyncData *data;
1306 data = g_new0 (FlushAsyncData, 1);
1307 data->worker = _g_dbus_worker_ref (worker);
1308 data->flushers = flushers;
1315 /* called in private thread shared by all GDBusConnection instances
1317 * write-lock is not held on entry
1318 * output_pending is PENDING_WRITE on entry
1321 write_message_cb (GObject *source_object,
1325 MessageToWriteData *data = user_data;
1328 g_mutex_lock (&data->worker->write_lock);
1329 g_assert (data->worker->output_pending == PENDING_WRITE);
1330 data->worker->output_pending = PENDING_NONE;
1333 if (!write_message_finish (res, &error))
1335 g_mutex_unlock (&data->worker->write_lock);
1338 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1339 g_error_free (error);
1341 g_mutex_lock (&data->worker->write_lock);
1344 message_written_unlocked (data->worker, data);
1346 g_mutex_unlock (&data->worker->write_lock);
1348 continue_writing (data->worker);
1350 message_to_write_data_free (data);
1353 /* called in private thread shared by all GDBusConnection instances
1355 * write-lock is not held on entry
1356 * output_pending is PENDING_CLOSE on entry
1359 iostream_close_cb (GObject *source_object,
1363 GDBusWorker *worker = user_data;
1364 GError *error = NULL;
1365 GList *pending_close_attempts, *pending_flush_attempts;
1368 g_io_stream_close_finish (worker->stream, res, &error);
1370 g_mutex_lock (&worker->write_lock);
1372 pending_close_attempts = worker->pending_close_attempts;
1373 worker->pending_close_attempts = NULL;
1375 pending_flush_attempts = worker->write_pending_flushes;
1376 worker->write_pending_flushes = NULL;
1378 send_queue = worker->write_queue;
1379 worker->write_queue = g_queue_new ();
1381 g_assert (worker->output_pending == PENDING_CLOSE);
1382 worker->output_pending = PENDING_NONE;
1384 g_mutex_unlock (&worker->write_lock);
1386 while (pending_close_attempts != NULL)
1388 CloseData *close_data = pending_close_attempts->data;
1390 pending_close_attempts = g_list_delete_link (pending_close_attempts,
1391 pending_close_attempts);
1393 if (close_data->result != NULL)
1396 g_simple_async_result_set_from_error (close_data->result, error);
1398 /* this must be in an idle because the result is likely to be
1399 * intended for another thread
1401 g_simple_async_result_complete_in_idle (close_data->result);
1404 close_data_free (close_data);
1407 g_clear_error (&error);
1409 /* all messages queued for sending are discarded */
1410 g_queue_free_full (send_queue, (GDestroyNotify) message_to_write_data_free);
1411 /* all queued flushes fail */
1412 error = g_error_new (G_IO_ERROR, G_IO_ERROR_CANCELLED,
1413 _("Operation was cancelled"));
1414 flush_data_list_complete (pending_flush_attempts, error);
1415 g_list_free (pending_flush_attempts);
1416 g_clear_error (&error);
1418 _g_dbus_worker_unref (worker);
1421 /* called in private thread shared by all GDBusConnection instances
1423 * write-lock is not held on entry
1424 * output_pending must be PENDING_NONE on entry
1427 continue_writing (GDBusWorker *worker)
1429 MessageToWriteData *data;
1430 FlushAsyncData *flush_async_data;
1433 /* we mustn't try to write two things at once */
1434 g_assert (worker->output_pending == PENDING_NONE);
1436 g_mutex_lock (&worker->write_lock);
1439 flush_async_data = NULL;
1441 /* if we want to close the connection, that takes precedence */
1442 if (worker->pending_close_attempts != NULL)
1444 worker->close_expected = TRUE;
1445 worker->output_pending = PENDING_CLOSE;
1447 g_io_stream_close_async (worker->stream, G_PRIORITY_DEFAULT,
1448 NULL, iostream_close_cb,
1449 _g_dbus_worker_ref (worker));
1453 flush_async_data = prepare_flush_unlocked (worker);
1455 if (flush_async_data == NULL)
1457 data = g_queue_pop_head (worker->write_queue);
1460 worker->output_pending = PENDING_WRITE;
1464 g_mutex_unlock (&worker->write_lock);
1466 /* Note that write_lock is only used for protecting the @write_queue
1467 * and @output_pending fields of the GDBusWorker struct ... which we
1468 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1470 * Therefore, it's fine to drop it here when calling back into user
1471 * code and then writing the message out onto the GIOStream since this
1472 * function only runs on the worker thread.
1475 if (flush_async_data != NULL)
1477 start_flush (flush_async_data);
1478 g_assert (data == NULL);
1480 else if (data != NULL)
1482 GDBusMessage *old_message;
1484 gsize new_blob_size;
1487 old_message = data->message;
1488 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1489 if (data->message == old_message)
1491 /* filters had no effect - do nothing */
1493 else if (data->message == NULL)
1495 /* filters dropped message */
1496 g_mutex_lock (&worker->write_lock);
1497 worker->output_pending = PENDING_NONE;
1498 g_mutex_unlock (&worker->write_lock);
1499 message_to_write_data_free (data);
1504 /* filters altered the message -> reencode */
1506 new_blob = g_dbus_message_to_blob (data->message,
1508 worker->capabilities,
1510 if (new_blob == NULL)
1512 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1513 * the old message instead
1515 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1516 g_dbus_message_get_serial (data->message),
1518 g_error_free (error);
1522 g_free (data->blob);
1523 data->blob = (gchar *) new_blob;
1524 data->blob_size = new_blob_size;
1528 write_message_async (worker,
1535 /* called in private thread shared by all GDBusConnection instances
1537 * write-lock is not held on entry
1538 * output_pending may be anything
1541 continue_writing_in_idle_cb (gpointer user_data)
1543 GDBusWorker *worker = user_data;
1545 /* Because this is the worker thread, we can read this struct member
1546 * without holding the lock: no other thread ever modifies it.
1548 if (worker->output_pending == PENDING_NONE)
1549 continue_writing (worker);
1555 * @write_data: (transfer full) (allow-none):
1556 * @flush_data: (transfer full) (allow-none):
1557 * @close_data: (transfer full) (allow-none):
1559 * Can be called from any thread
1561 * write_lock is held on entry
1562 * output_pending may be anything
1565 schedule_writing_unlocked (GDBusWorker *worker,
1566 MessageToWriteData *write_data,
1567 FlushData *flush_data,
1568 CloseData *close_data)
1570 if (write_data != NULL)
1571 g_queue_push_tail (worker->write_queue, write_data);
1573 if (flush_data != NULL)
1574 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, flush_data);
1576 if (close_data != NULL)
1577 worker->pending_close_attempts = g_list_prepend (worker->pending_close_attempts,
1580 /* If we had output pending, the next bit of output will happen
1581 * automatically when it finishes, so we only need to do this
1582 * if nothing was pending.
1584 * The idle callback will re-check that output_pending is still
1585 * PENDING_NONE, to guard against output starting before the idle.
1587 if (worker->output_pending == PENDING_NONE)
1589 GSource *idle_source;
1590 idle_source = g_idle_source_new ();
1591 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1592 g_source_set_callback (idle_source,
1593 continue_writing_in_idle_cb,
1594 _g_dbus_worker_ref (worker),
1595 (GDestroyNotify) _g_dbus_worker_unref);
1596 g_source_attach (idle_source, worker->shared_thread_data->context);
1597 g_source_unref (idle_source);
1601 /* ---------------------------------------------------------------------------------------------------- */
1603 /* can be called from any thread - steals blob
1605 * write_lock is not held on entry
1606 * output_pending may be anything
1609 _g_dbus_worker_send_message (GDBusWorker *worker,
1610 GDBusMessage *message,
1614 MessageToWriteData *data;
1616 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1617 g_return_if_fail (blob != NULL);
1618 g_return_if_fail (blob_len > 16);
1620 data = g_new0 (MessageToWriteData, 1);
1621 data->worker = _g_dbus_worker_ref (worker);
1622 data->message = g_object_ref (message);
1623 data->blob = blob; /* steal! */
1624 data->blob_size = blob_len;
1626 g_mutex_lock (&worker->write_lock);
1627 schedule_writing_unlocked (worker, data, NULL, NULL);
1628 g_mutex_unlock (&worker->write_lock);
1631 /* ---------------------------------------------------------------------------------------------------- */
1634 _g_dbus_worker_new (GIOStream *stream,
1635 GDBusCapabilityFlags capabilities,
1636 gboolean initially_frozen,
1637 GDBusWorkerMessageReceivedCallback message_received_callback,
1638 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1639 GDBusWorkerDisconnectedCallback disconnected_callback,
1642 GDBusWorker *worker;
1643 GSource *idle_source;
1645 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1646 g_return_val_if_fail (message_received_callback != NULL, NULL);
1647 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1648 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1650 worker = g_new0 (GDBusWorker, 1);
1651 worker->ref_count = 1;
1653 g_mutex_init (&worker->read_lock);
1654 worker->message_received_callback = message_received_callback;
1655 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1656 worker->disconnected_callback = disconnected_callback;
1657 worker->user_data = user_data;
1658 worker->stream = g_object_ref (stream);
1659 worker->capabilities = capabilities;
1660 worker->cancellable = g_cancellable_new ();
1661 worker->output_pending = PENDING_NONE;
1663 worker->frozen = initially_frozen;
1664 worker->received_messages_while_frozen = g_queue_new ();
1666 g_mutex_init (&worker->write_lock);
1667 worker->write_queue = g_queue_new ();
1669 if (G_IS_SOCKET_CONNECTION (worker->stream))
1670 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1672 worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1675 idle_source = g_idle_source_new ();
1676 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1677 g_source_set_callback (idle_source,
1678 _g_dbus_worker_do_initial_read,
1679 _g_dbus_worker_ref (worker),
1680 (GDestroyNotify) _g_dbus_worker_unref);
1681 g_source_attach (idle_source, worker->shared_thread_data->context);
1682 g_source_unref (idle_source);
1687 /* ---------------------------------------------------------------------------------------------------- */
1689 /* can be called from any thread
1691 * write_lock is not held on entry
1692 * output_pending may be anything
1695 _g_dbus_worker_close (GDBusWorker *worker,
1696 GCancellable *cancellable,
1697 GSimpleAsyncResult *result)
1699 CloseData *close_data;
1701 close_data = g_slice_new0 (CloseData);
1702 close_data->worker = _g_dbus_worker_ref (worker);
1703 close_data->cancellable =
1704 (cancellable == NULL ? NULL : g_object_ref (cancellable));
1705 close_data->result = (result == NULL ? NULL : g_object_ref (result));
1707 /* Don't set worker->close_expected here - we're in the wrong thread.
1708 * It'll be set before the actual close happens.
1710 g_cancellable_cancel (worker->cancellable);
1711 g_mutex_lock (&worker->write_lock);
1712 schedule_writing_unlocked (worker, NULL, NULL, close_data);
1713 g_mutex_unlock (&worker->write_lock);
1716 /* This can be called from any thread - frees worker. Note that
1717 * callbacks might still happen if called from another thread than the
1718 * worker - use your own synchronization primitive in the callbacks.
1720 * write_lock is not held on entry
1721 * output_pending may be anything
1724 _g_dbus_worker_stop (GDBusWorker *worker)
1726 g_atomic_int_set (&worker->stopped, TRUE);
1728 /* Cancel any pending operations and schedule a close of the underlying I/O
1729 * stream in the worker thread
1731 _g_dbus_worker_close (worker, NULL, NULL);
1733 /* _g_dbus_worker_close holds a ref until after an idle in the the worker
1734 * thread has run, so we no longer need to unref in an idle like in
1737 _g_dbus_worker_unref (worker);
1740 /* ---------------------------------------------------------------------------------------------------- */
1742 /* can be called from any thread (except the worker thread) - blocks
1743 * calling thread until all queued outgoing messages are written and
1744 * the transport has been flushed
1746 * write_lock is not held on entry
1747 * output_pending may be anything
1750 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1751 GCancellable *cancellable,
1756 guint64 pending_writes;
1761 g_mutex_lock (&worker->write_lock);
1763 /* if the queue is empty, no write is in-flight and we haven't written
1764 * anything since the last flush, then there's nothing to wait for
1766 pending_writes = g_queue_get_length (worker->write_queue);
1768 /* if a write is in-flight, we shouldn't be satisfied until the first
1769 * flush operation that follows it
1771 if (worker->output_pending == PENDING_WRITE)
1772 pending_writes += 1;
1774 if (pending_writes > 0 ||
1775 worker->write_num_messages_written != worker->write_num_messages_flushed)
1777 data = g_new0 (FlushData, 1);
1778 g_mutex_init (&data->mutex);
1779 g_cond_init (&data->cond);
1780 data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
1781 g_mutex_lock (&data->mutex);
1783 schedule_writing_unlocked (worker, NULL, data, NULL);
1785 g_mutex_unlock (&worker->write_lock);
1789 g_cond_wait (&data->cond, &data->mutex);
1790 g_mutex_unlock (&data->mutex);
1792 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1793 g_cond_clear (&data->cond);
1794 g_mutex_clear (&data->mutex);
1795 if (data->error != NULL)
1798 g_propagate_error (error, data->error);
1806 /* ---------------------------------------------------------------------------------------------------- */
1808 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1809 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1810 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1811 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1812 #define G_DBUS_DEBUG_CALL (1<<4)
1813 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1814 #define G_DBUS_DEBUG_INCOMING (1<<6)
1815 #define G_DBUS_DEBUG_RETURN (1<<7)
1816 #define G_DBUS_DEBUG_EMISSION (1<<8)
1817 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1819 static gint _gdbus_debug_flags = 0;
1822 _g_dbus_debug_authentication (void)
1824 _g_dbus_initialize ();
1825 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1829 _g_dbus_debug_transport (void)
1831 _g_dbus_initialize ();
1832 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1836 _g_dbus_debug_message (void)
1838 _g_dbus_initialize ();
1839 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1843 _g_dbus_debug_payload (void)
1845 _g_dbus_initialize ();
1846 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1850 _g_dbus_debug_call (void)
1852 _g_dbus_initialize ();
1853 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1857 _g_dbus_debug_signal (void)
1859 _g_dbus_initialize ();
1860 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1864 _g_dbus_debug_incoming (void)
1866 _g_dbus_initialize ();
1867 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1871 _g_dbus_debug_return (void)
1873 _g_dbus_initialize ();
1874 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1878 _g_dbus_debug_emission (void)
1880 _g_dbus_initialize ();
1881 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1885 _g_dbus_debug_address (void)
1887 _g_dbus_initialize ();
1888 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1891 G_LOCK_DEFINE_STATIC (print_lock);
1894 _g_dbus_debug_print_lock (void)
1896 G_LOCK (print_lock);
1900 _g_dbus_debug_print_unlock (void)
1902 G_UNLOCK (print_lock);
1906 * _g_dbus_initialize:
1908 * Does various one-time init things such as
1910 * - registering the G_DBUS_ERROR error domain
1911 * - parses the G_DBUS_DEBUG environment variable
1914 _g_dbus_initialize (void)
1916 static volatile gsize initialized = 0;
1918 if (g_once_init_enter (&initialized))
1920 volatile GQuark g_dbus_error_domain;
1923 g_dbus_error_domain = G_DBUS_ERROR;
1924 (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1926 debug = g_getenv ("G_DBUS_DEBUG");
1929 const GDebugKey keys[] = {
1930 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1931 { "transport", G_DBUS_DEBUG_TRANSPORT },
1932 { "message", G_DBUS_DEBUG_MESSAGE },
1933 { "payload", G_DBUS_DEBUG_PAYLOAD },
1934 { "call", G_DBUS_DEBUG_CALL },
1935 { "signal", G_DBUS_DEBUG_SIGNAL },
1936 { "incoming", G_DBUS_DEBUG_INCOMING },
1937 { "return", G_DBUS_DEBUG_RETURN },
1938 { "emission", G_DBUS_DEBUG_EMISSION },
1939 { "address", G_DBUS_DEBUG_ADDRESS }
1942 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1943 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1944 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1947 g_once_init_leave (&initialized, 1);
1951 /* ---------------------------------------------------------------------------------------------------- */
1954 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1956 const GVariantType *arg_types[256];
1960 for (n = 0; args[n] != NULL; n++)
1962 /* DBus places a hard limit of 255 on signature length.
1963 * therefore number of args must be less than 256.
1967 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1969 if G_UNLIKELY (arg_types[n] == NULL)
1975 return g_variant_type_new_tuple (arg_types, n);
1978 /* ---------------------------------------------------------------------------------------------------- */
1982 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1985 _g_dbus_win32_get_user_sid (void)
1989 DWORD token_information_len;
1996 h = INVALID_HANDLE_VALUE;
1998 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
2000 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
2004 /* Get length of buffer */
2005 token_information_len = 0;
2006 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
2008 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
2010 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2014 user = g_malloc (token_information_len);
2015 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
2017 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2021 psid = user->User.Sid;
2022 if (!IsValidSid (psid))
2024 g_warning ("Invalid SID");
2028 if (!ConvertSidToStringSidA (psid, &sid))
2030 g_warning ("Invalid SID");
2034 ret = g_strdup (sid);
2039 if (h != INVALID_HANDLE_VALUE)
2045 /* ---------------------------------------------------------------------------------------------------- */
2048 _g_dbus_get_machine_id (GError **error)
2051 GError *first_error;
2052 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2055 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2059 !g_file_get_contents ("/etc/machine-id",
2064 g_propagate_prefixed_error (error, first_error,
2065 _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2069 /* ignore the error from the first try, if any */
2070 g_clear_error (&first_error);
2071 /* TODO: validate value */
2077 /* ---------------------------------------------------------------------------------------------------- */
2080 _g_dbus_enum_to_string (GType enum_type, gint value)
2084 GEnumValue *enum_value;
2086 klass = g_type_class_ref (enum_type);
2087 enum_value = g_enum_get_value (klass, value);
2088 if (enum_value != NULL)
2089 ret = g_strdup (enum_value->value_nick);
2091 ret = g_strdup_printf ("unknown (value %d)", value);
2092 g_type_class_unref (klass);
2096 /* ---------------------------------------------------------------------------------------------------- */
2099 write_message_print_transport_debug (gssize bytes_written,
2100 MessageToWriteData *data)
2102 if (G_LIKELY (!_g_dbus_debug_transport ()))
2105 _g_dbus_debug_print_lock ();
2106 g_print ("========================================================================\n"
2107 "GDBus-debug:Transport:\n"
2108 " >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2109 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
2111 g_dbus_message_get_serial (data->message),
2113 data->total_written,
2114 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
2115 _g_dbus_debug_print_unlock ();
2120 /* ---------------------------------------------------------------------------------------------------- */
2123 read_message_print_transport_debug (gssize bytes_read,
2124 GDBusWorker *worker)
2128 gint32 message_length;
2130 if (G_LIKELY (!_g_dbus_debug_transport ()))
2133 size = bytes_read + worker->read_buffer_cur_size;
2137 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2140 switch (worker->read_buffer[0])
2144 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2148 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2151 /* an error will be set elsewhere if this happens */
2156 _g_dbus_debug_print_lock ();
2157 g_print ("========================================================================\n"
2158 "GDBus-debug:Transport:\n"
2159 " <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2160 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
2164 worker->read_buffer_cur_size,
2165 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
2166 _g_dbus_debug_print_unlock ();
2171 /* ---------------------------------------------------------------------------------------------------- */
2174 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2175 GValue *return_accu,
2176 const GValue *handler_return,
2179 gboolean continue_emission;
2180 gboolean signal_return;
2182 signal_return = g_value_get_boolean (handler_return);
2183 g_value_set_boolean (return_accu, signal_return);
2184 continue_emission = signal_return;
2186 return continue_emission;