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);
194 g_simple_async_result_set_check_cancellable (data->simple, cancellable);
196 if (!g_socket_condition_check (socket, G_IO_IN))
199 data->from_mainloop = TRUE;
200 source = g_socket_create_source (data->socket,
201 G_IO_IN | G_IO_HUP | G_IO_ERR,
203 g_source_set_callback (source,
204 (GSourceFunc) _g_socket_read_with_control_messages_ready,
206 (GDestroyNotify) read_with_control_data_free);
207 g_source_attach (source, g_main_context_get_thread_default ());
208 g_source_unref (source);
212 _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
213 read_with_control_data_free (data);
218 _g_socket_read_with_control_messages_finish (GSocket *socket,
219 GAsyncResult *result,
222 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
224 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
225 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
227 if (g_simple_async_result_propagate_error (simple, error))
230 return g_simple_async_result_get_op_res_gssize (simple);
233 /* ---------------------------------------------------------------------------------------------------- */
235 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
237 static GPtrArray *ensured_classes = NULL;
240 ensure_type (GType gtype)
242 g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
246 release_required_types (void)
248 g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
249 g_ptr_array_unref (ensured_classes);
250 ensured_classes = NULL;
254 ensure_required_types (void)
256 g_assert (ensured_classes == NULL);
257 ensured_classes = g_ptr_array_new ();
258 ensure_type (G_TYPE_SIMPLE_ASYNC_RESULT);
259 ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
261 /* ---------------------------------------------------------------------------------------------------- */
265 volatile gint refcount;
267 GMainContext *context;
272 gdbus_shared_thread_func (gpointer user_data)
274 SharedThreadData *data = user_data;
276 g_main_context_push_thread_default (data->context);
277 g_main_loop_run (data->loop);
278 g_main_context_pop_thread_default (data->context);
280 release_required_types ();
285 /* ---------------------------------------------------------------------------------------------------- */
287 static SharedThreadData *
288 _g_dbus_shared_thread_ref (void)
290 static gsize shared_thread_data = 0;
291 SharedThreadData *ret;
293 if (g_once_init_enter (&shared_thread_data))
295 SharedThreadData *data;
297 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
298 ensure_required_types ();
300 data = g_new0 (SharedThreadData, 1);
303 data->context = g_main_context_new ();
304 data->loop = g_main_loop_new (data->context, FALSE);
305 data->thread = g_thread_new ("gdbus",
306 gdbus_shared_thread_func,
308 /* We can cast between gsize and gpointer safely */
309 g_once_init_leave (&shared_thread_data, (gsize) data);
312 ret = (SharedThreadData*) shared_thread_data;
313 g_atomic_int_inc (&ret->refcount);
318 _g_dbus_shared_thread_unref (SharedThreadData *data)
320 /* TODO: actually destroy the shared thread here */
322 g_assert (data != NULL);
323 if (g_atomic_int_dec_and_test (&data->refcount))
325 g_main_loop_quit (data->loop);
326 //g_thread_join (data->thread);
327 g_main_loop_unref (data->loop);
328 g_main_context_unref (data->context);
333 /* ---------------------------------------------------------------------------------------------------- */
344 volatile gint ref_count;
346 SharedThreadData *shared_thread_data;
348 /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
349 volatile gint stopped;
351 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
352 * only affects messages received from the other peer (since GDBusServer is the
353 * only user) - we might want it to affect messages sent to the other peer too?
356 GDBusCapabilityFlags capabilities;
357 GQueue *received_messages_while_frozen;
360 GCancellable *cancellable;
361 GDBusWorkerMessageReceivedCallback message_received_callback;
362 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
363 GDBusWorkerDisconnectedCallback disconnected_callback;
366 /* if not NULL, stream is GSocketConnection */
369 /* used for reading */
372 gsize read_buffer_allocated_size;
373 gsize read_buffer_cur_size;
374 gsize read_buffer_bytes_wanted;
375 GUnixFDList *read_fd_list;
376 GSocketControlMessage **read_ancillary_messages;
377 gint read_num_ancillary_messages;
379 /* Whether an async write, flush or close, or none of those, is pending.
380 * Only the worker thread may change its value, and only with the write_lock.
381 * Other threads may read its value when holding the write_lock.
382 * The worker thread may read its value at any time.
384 OutputPending output_pending;
385 /* used for writing */
387 /* queue of MessageToWriteData, protected by write_lock */
389 /* protected by write_lock */
390 guint64 write_num_messages_written;
391 /* number of messages we'd written out last time we flushed;
392 * protected by write_lock
394 guint64 write_num_messages_flushed;
395 /* list of FlushData, protected by write_lock */
396 GList *write_pending_flushes;
397 /* list of CloseData, protected by write_lock */
398 GList *pending_close_attempts;
399 /* no lock - only used from the worker thread */
400 gboolean close_expected;
403 static void _g_dbus_worker_unref (GDBusWorker *worker);
405 /* ---------------------------------------------------------------------------------------------------- */
411 guint64 number_to_wait_for;
415 struct _MessageToWriteData ;
416 typedef struct _MessageToWriteData MessageToWriteData;
418 static void message_to_write_data_free (MessageToWriteData *data);
420 static void read_message_print_transport_debug (gssize bytes_read,
421 GDBusWorker *worker);
423 static void write_message_print_transport_debug (gssize bytes_written,
424 MessageToWriteData *data);
428 GCancellable *cancellable;
429 GSimpleAsyncResult *result;
432 static void close_data_free (CloseData *close_data)
434 if (close_data->cancellable != NULL)
435 g_object_unref (close_data->cancellable);
437 if (close_data->result != NULL)
438 g_object_unref (close_data->result);
440 _g_dbus_worker_unref (close_data->worker);
441 g_slice_free (CloseData, close_data);
444 /* ---------------------------------------------------------------------------------------------------- */
447 _g_dbus_worker_ref (GDBusWorker *worker)
449 g_atomic_int_inc (&worker->ref_count);
454 _g_dbus_worker_unref (GDBusWorker *worker)
456 if (g_atomic_int_dec_and_test (&worker->ref_count))
458 g_assert (worker->write_pending_flushes == NULL);
460 _g_dbus_shared_thread_unref (worker->shared_thread_data);
462 g_object_unref (worker->stream);
464 g_mutex_clear (&worker->read_lock);
465 g_object_unref (worker->cancellable);
466 if (worker->read_fd_list != NULL)
467 g_object_unref (worker->read_fd_list);
469 g_queue_free_full (worker->received_messages_while_frozen, (GDestroyNotify) g_object_unref);
470 g_mutex_clear (&worker->write_lock);
471 g_queue_free_full (worker->write_queue, (GDestroyNotify) message_to_write_data_free);
472 g_free (worker->read_buffer);
479 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
480 gboolean remote_peer_vanished,
483 if (!g_atomic_int_get (&worker->stopped))
484 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
488 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
489 GDBusMessage *message)
491 if (!g_atomic_int_get (&worker->stopped))
492 worker->message_received_callback (worker, message, worker->user_data);
495 static GDBusMessage *
496 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
497 GDBusMessage *message)
500 if (!g_atomic_int_get (&worker->stopped))
501 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
507 /* can only be called from private thread with read-lock held - takes ownership of @message */
509 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
510 GDBusMessage *message)
512 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
515 g_queue_push_tail (worker->received_messages_while_frozen, message);
519 /* not frozen, nor anything in queue */
520 _g_dbus_worker_emit_message_received (worker, message);
521 g_object_unref (message);
525 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
527 unfreeze_in_idle_cb (gpointer user_data)
529 GDBusWorker *worker = user_data;
530 GDBusMessage *message;
532 g_mutex_lock (&worker->read_lock);
535 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
537 _g_dbus_worker_emit_message_received (worker, message);
538 g_object_unref (message);
540 worker->frozen = FALSE;
544 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
546 g_mutex_unlock (&worker->read_lock);
550 /* can be called from any thread */
552 _g_dbus_worker_unfreeze (GDBusWorker *worker)
554 GSource *idle_source;
555 idle_source = g_idle_source_new ();
556 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
557 g_source_set_callback (idle_source,
559 _g_dbus_worker_ref (worker),
560 (GDestroyNotify) _g_dbus_worker_unref);
561 g_source_attach (idle_source, worker->shared_thread_data->context);
562 g_source_unref (idle_source);
565 /* ---------------------------------------------------------------------------------------------------- */
567 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
569 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
571 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
575 GDBusWorker *worker = user_data;
579 g_mutex_lock (&worker->read_lock);
581 /* If already stopped, don't even process the reply */
582 if (g_atomic_int_get (&worker->stopped))
586 if (worker->socket == NULL)
587 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
591 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
594 if (worker->read_num_ancillary_messages > 0)
597 for (n = 0; n < worker->read_num_ancillary_messages; n++)
599 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
605 else if (G_IS_UNIX_FD_MESSAGE (control_message))
607 GUnixFDMessage *fd_message;
611 fd_message = G_UNIX_FD_MESSAGE (control_message);
612 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
613 if (worker->read_fd_list == NULL)
615 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
620 for (n = 0; n < num_fds; n++)
622 /* TODO: really want a append_steal() */
623 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
629 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
641 "Unexpected ancillary message of type %s received from peer",
642 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
643 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
644 g_error_free (error);
645 g_object_unref (control_message);
647 while (n < worker->read_num_ancillary_messages)
648 g_object_unref (worker->read_ancillary_messages[n++]);
649 g_free (worker->read_ancillary_messages);
653 g_object_unref (control_message);
655 g_free (worker->read_ancillary_messages);
658 if (bytes_read == -1)
660 if (G_UNLIKELY (_g_dbus_debug_transport ()))
662 _g_dbus_debug_print_lock ();
663 g_print ("========================================================================\n"
664 "GDBus-debug:Transport:\n"
665 " ---- READ ERROR on stream of type %s:\n"
667 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))),
668 g_quark_to_string (error->domain), error->code,
670 _g_dbus_debug_print_unlock ();
673 /* Every async read that uses this callback uses worker->cancellable
674 * as its GCancellable. worker->cancellable gets cancelled if and only
675 * if the GDBusConnection tells us to close (either via
676 * _g_dbus_worker_stop, which is called on last-unref, or directly),
677 * so a cancelled read must mean our connection was closed locally.
679 * If we're closing, other errors are possible - notably,
680 * G_IO_ERROR_CLOSED can be seen if we close the stream with an async
681 * read in-flight. It seems sensible to treat all read errors during
682 * closing as an expected thing that doesn't trip exit-on-close.
684 * Because close_expected can't be set until we get into the worker
685 * thread, but the cancellable is signalled sooner (from another
686 * thread), we do still need to check the error.
688 if (worker->close_expected ||
689 g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
690 _g_dbus_worker_emit_disconnected (worker, FALSE, NULL);
692 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
694 g_error_free (error);
699 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
701 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
702 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
703 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
704 G_IO_IN | G_IO_OUT | G_IO_HUP),
709 /* TODO: hmm, hmm... */
715 "Underlying GIOStream returned 0 bytes on an async read");
716 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
717 g_error_free (error);
721 read_message_print_transport_debug (bytes_read, worker);
723 worker->read_buffer_cur_size += bytes_read;
724 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
726 /* OK, got what we asked for! */
727 if (worker->read_buffer_bytes_wanted == 16)
730 /* OK, got the header - determine how many more bytes are needed */
732 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
735 if (message_len == -1)
737 g_warning ("_g_dbus_worker_do_read_cb: error determing bytes needed: %s", error->message);
738 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
739 g_error_free (error);
743 worker->read_buffer_bytes_wanted = message_len;
744 _g_dbus_worker_do_read_unlocked (worker);
748 GDBusMessage *message;
751 /* TODO: use connection->priv->auth to decode the message */
753 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
754 worker->read_buffer_cur_size,
755 worker->capabilities,
760 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
761 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
763 "The payload is as follows:\n"
765 worker->read_buffer_cur_size,
769 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
770 g_error_free (error);
775 if (worker->read_fd_list != NULL)
777 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
778 g_object_unref (worker->read_fd_list);
779 worker->read_fd_list = NULL;
783 if (G_UNLIKELY (_g_dbus_debug_message ()))
786 _g_dbus_debug_print_lock ();
787 g_print ("========================================================================\n"
788 "GDBus-debug:Message:\n"
789 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
790 worker->read_buffer_cur_size);
791 s = g_dbus_message_print (message, 2);
794 if (G_UNLIKELY (_g_dbus_debug_payload ()))
796 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
800 _g_dbus_debug_print_unlock ();
803 /* yay, got a message, go deliver it */
804 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
806 /* start reading another message! */
807 worker->read_buffer_bytes_wanted = 0;
808 worker->read_buffer_cur_size = 0;
809 _g_dbus_worker_do_read_unlocked (worker);
814 /* didn't get all the bytes we requested - so repeat the request... */
815 _g_dbus_worker_do_read_unlocked (worker);
819 g_mutex_unlock (&worker->read_lock);
821 /* gives up the reference acquired when calling g_input_stream_read_async() */
822 _g_dbus_worker_unref (worker);
825 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
827 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
829 /* Note that we do need to keep trying to read even if close_expected is
830 * true, because only failing a read causes us to signal 'closed'.
833 /* if bytes_wanted is zero, it means start reading a message */
834 if (worker->read_buffer_bytes_wanted == 0)
836 worker->read_buffer_cur_size = 0;
837 worker->read_buffer_bytes_wanted = 16;
840 /* ensure we have a (big enough) buffer */
841 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
843 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
844 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
845 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
848 if (worker->socket == NULL)
849 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
850 worker->read_buffer + worker->read_buffer_cur_size,
851 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
854 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
855 _g_dbus_worker_ref (worker));
858 worker->read_ancillary_messages = NULL;
859 worker->read_num_ancillary_messages = 0;
860 _g_socket_read_with_control_messages (worker->socket,
861 worker->read_buffer + worker->read_buffer_cur_size,
862 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
863 &worker->read_ancillary_messages,
864 &worker->read_num_ancillary_messages,
867 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
868 _g_dbus_worker_ref (worker));
872 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
874 _g_dbus_worker_do_initial_read (gpointer data)
876 GDBusWorker *worker = data;
877 g_mutex_lock (&worker->read_lock);
878 _g_dbus_worker_do_read_unlocked (worker);
879 g_mutex_unlock (&worker->read_lock);
883 /* ---------------------------------------------------------------------------------------------------- */
885 struct _MessageToWriteData
888 GDBusMessage *message;
893 GSimpleAsyncResult *simple;
898 message_to_write_data_free (MessageToWriteData *data)
900 _g_dbus_worker_unref (data->worker);
902 g_object_unref (data->message);
907 /* ---------------------------------------------------------------------------------------------------- */
909 static void write_message_continue_writing (MessageToWriteData *data);
911 /* called in private thread shared by all GDBusConnection instances
913 * write-lock is not held on entry
914 * output_pending is PENDING_WRITE on entry
917 write_message_async_cb (GObject *source_object,
921 MessageToWriteData *data = user_data;
922 GSimpleAsyncResult *simple;
923 gssize bytes_written;
926 /* Note: we can't access data->simple after calling g_async_result_complete () because the
927 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
929 simple = data->simple;
932 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
935 if (bytes_written == -1)
937 g_simple_async_result_take_error (simple, error);
938 g_simple_async_result_complete (simple);
939 g_object_unref (simple);
942 g_assert (bytes_written > 0); /* zero is never returned */
944 write_message_print_transport_debug (bytes_written, data);
946 data->total_written += bytes_written;
947 g_assert (data->total_written <= data->blob_size);
948 if (data->total_written == data->blob_size)
950 g_simple_async_result_complete (simple);
951 g_object_unref (simple);
955 write_message_continue_writing (data);
961 /* called in private thread shared by all GDBusConnection instances
963 * write-lock is not held on entry
964 * output_pending is PENDING_WRITE on entry
967 on_socket_ready (GSocket *socket,
968 GIOCondition condition,
971 MessageToWriteData *data = user_data;
972 write_message_continue_writing (data);
973 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;
985 GSimpleAsyncResult *simple;
987 GUnixFDList *fd_list;
990 /* Note: we can't access data->simple after calling g_async_result_complete () because the
991 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
993 simple = data->simple;
995 ostream = g_io_stream_get_output_stream (data->worker->stream);
997 fd_list = g_dbus_message_get_unix_fd_list (data->message);
1000 g_assert (!g_output_stream_has_pending (ostream));
1001 g_assert_cmpint (data->total_written, <, data->blob_size);
1007 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
1009 GOutputVector vector;
1010 GSocketControlMessage *control_message;
1011 gssize bytes_written;
1014 vector.buffer = data->blob;
1015 vector.size = data->blob_size;
1017 control_message = NULL;
1018 if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
1020 if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
1022 g_simple_async_result_set_error (simple,
1025 "Tried sending a file descriptor but remote peer does not support this capability");
1026 g_simple_async_result_complete (simple);
1027 g_object_unref (simple);
1030 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1034 bytes_written = g_socket_send_message (data->worker->socket,
1038 control_message != NULL ? &control_message : NULL,
1039 control_message != NULL ? 1 : 0,
1041 data->worker->cancellable,
1043 if (control_message != NULL)
1044 g_object_unref (control_message);
1046 if (bytes_written == -1)
1048 /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1049 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1052 source = g_socket_create_source (data->worker->socket,
1053 G_IO_OUT | G_IO_HUP | G_IO_ERR,
1054 data->worker->cancellable);
1055 g_source_set_callback (source,
1056 (GSourceFunc) on_socket_ready,
1058 NULL); /* GDestroyNotify */
1059 g_source_attach (source, g_main_context_get_thread_default ());
1060 g_source_unref (source);
1061 g_error_free (error);
1064 g_simple_async_result_take_error (simple, error);
1065 g_simple_async_result_complete (simple);
1066 g_object_unref (simple);
1069 g_assert (bytes_written > 0); /* zero is never returned */
1071 write_message_print_transport_debug (bytes_written, data);
1073 data->total_written += bytes_written;
1074 g_assert (data->total_written <= data->blob_size);
1075 if (data->total_written == data->blob_size)
1077 g_simple_async_result_complete (simple);
1078 g_object_unref (simple);
1082 write_message_continue_writing (data);
1088 if (fd_list != NULL)
1090 g_simple_async_result_set_error (simple,
1093 "Tried sending a file descriptor on unsupported stream of type %s",
1094 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1095 g_simple_async_result_complete (simple);
1096 g_object_unref (simple);
1101 g_output_stream_write_async (ostream,
1102 (const gchar *) data->blob + data->total_written,
1103 data->blob_size - data->total_written,
1105 data->worker->cancellable,
1106 write_message_async_cb,
1113 /* called in private thread shared by all GDBusConnection instances
1115 * write-lock is not held on entry
1116 * output_pending is PENDING_WRITE on entry
1119 write_message_async (GDBusWorker *worker,
1120 MessageToWriteData *data,
1121 GAsyncReadyCallback callback,
1124 data->simple = g_simple_async_result_new (NULL,
1127 write_message_async);
1128 data->total_written = 0;
1129 write_message_continue_writing (data);
1132 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1134 write_message_finish (GAsyncResult *res,
1137 g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1138 if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1143 /* ---------------------------------------------------------------------------------------------------- */
1145 static void continue_writing (GDBusWorker *worker);
1149 GDBusWorker *worker;
1154 flush_data_list_complete (const GList *flushers,
1155 const GError *error)
1159 for (l = flushers; l != NULL; l = l->next)
1161 FlushData *f = l->data;
1163 f->error = error != NULL ? g_error_copy (error) : NULL;
1165 g_mutex_lock (&f->mutex);
1166 g_cond_signal (&f->cond);
1167 g_mutex_unlock (&f->mutex);
1171 /* called in private thread shared by all GDBusConnection instances
1173 * write-lock is not held on entry
1174 * output_pending is PENDING_FLUSH on entry
1177 ostream_flush_cb (GObject *source_object,
1181 FlushAsyncData *data = user_data;
1185 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1191 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1193 _g_dbus_debug_print_lock ();
1194 g_print ("========================================================================\n"
1195 "GDBus-debug:Transport:\n"
1196 " ---- FLUSHED stream of type %s\n",
1197 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1198 _g_dbus_debug_print_unlock ();
1202 g_assert (data->flushers != NULL);
1203 flush_data_list_complete (data->flushers, error);
1204 g_list_free (data->flushers);
1207 g_error_free (error);
1209 /* Make sure we tell folks that we don't have additional
1211 g_mutex_lock (&data->worker->write_lock);
1212 data->worker->write_num_messages_flushed = data->worker->write_num_messages_written;
1213 g_assert (data->worker->output_pending == PENDING_FLUSH);
1214 data->worker->output_pending = PENDING_NONE;
1215 g_mutex_unlock (&data->worker->write_lock);
1217 /* OK, cool, finally kick off the next write */
1218 continue_writing (data->worker);
1220 _g_dbus_worker_unref (data->worker);
1224 /* called in private thread shared by all GDBusConnection instances
1226 * write-lock is not held on entry
1227 * output_pending is PENDING_FLUSH on entry
1230 start_flush (FlushAsyncData *data)
1232 g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1234 data->worker->cancellable,
1239 /* called in private thread shared by all GDBusConnection instances
1241 * write-lock is held on entry
1242 * output_pending is PENDING_NONE on entry
1245 message_written_unlocked (GDBusWorker *worker,
1246 MessageToWriteData *message_data)
1248 if (G_UNLIKELY (_g_dbus_debug_message ()))
1251 _g_dbus_debug_print_lock ();
1252 g_print ("========================================================================\n"
1253 "GDBus-debug:Message:\n"
1254 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1255 message_data->blob_size);
1256 s = g_dbus_message_print (message_data->message, 2);
1259 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1261 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1262 g_print ("%s\n", s);
1265 _g_dbus_debug_print_unlock ();
1268 worker->write_num_messages_written += 1;
1271 /* called in private thread shared by all GDBusConnection instances
1273 * write-lock is held on entry
1274 * output_pending is PENDING_NONE on entry
1276 * Returns: non-%NULL, setting @output_pending, if we need to flush now
1278 static FlushAsyncData *
1279 prepare_flush_unlocked (GDBusWorker *worker)
1286 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1288 FlushData *f = l->data;
1291 if (f->number_to_wait_for == worker->write_num_messages_written)
1293 flushers = g_list_append (flushers, f);
1294 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1297 if (flushers != NULL)
1299 g_assert (worker->output_pending == PENDING_NONE);
1300 worker->output_pending = PENDING_FLUSH;
1303 if (flushers != NULL)
1305 FlushAsyncData *data;
1307 data = g_new0 (FlushAsyncData, 1);
1308 data->worker = _g_dbus_worker_ref (worker);
1309 data->flushers = flushers;
1316 /* called in private thread shared by all GDBusConnection instances
1318 * write-lock is not held on entry
1319 * output_pending is PENDING_WRITE on entry
1322 write_message_cb (GObject *source_object,
1326 MessageToWriteData *data = user_data;
1329 g_mutex_lock (&data->worker->write_lock);
1330 g_assert (data->worker->output_pending == PENDING_WRITE);
1331 data->worker->output_pending = PENDING_NONE;
1334 if (!write_message_finish (res, &error))
1336 g_mutex_unlock (&data->worker->write_lock);
1339 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1340 g_error_free (error);
1342 g_mutex_lock (&data->worker->write_lock);
1345 message_written_unlocked (data->worker, data);
1347 g_mutex_unlock (&data->worker->write_lock);
1349 continue_writing (data->worker);
1351 message_to_write_data_free (data);
1354 /* called in private thread shared by all GDBusConnection instances
1356 * write-lock is not held on entry
1357 * output_pending is PENDING_CLOSE on entry
1360 iostream_close_cb (GObject *source_object,
1364 GDBusWorker *worker = user_data;
1365 GError *error = NULL;
1366 GList *pending_close_attempts, *pending_flush_attempts;
1369 g_io_stream_close_finish (worker->stream, res, &error);
1371 g_mutex_lock (&worker->write_lock);
1373 pending_close_attempts = worker->pending_close_attempts;
1374 worker->pending_close_attempts = NULL;
1376 pending_flush_attempts = worker->write_pending_flushes;
1377 worker->write_pending_flushes = NULL;
1379 send_queue = worker->write_queue;
1380 worker->write_queue = g_queue_new ();
1382 g_assert (worker->output_pending == PENDING_CLOSE);
1383 worker->output_pending = PENDING_NONE;
1385 g_mutex_unlock (&worker->write_lock);
1387 while (pending_close_attempts != NULL)
1389 CloseData *close_data = pending_close_attempts->data;
1391 pending_close_attempts = g_list_delete_link (pending_close_attempts,
1392 pending_close_attempts);
1394 if (close_data->result != NULL)
1397 g_simple_async_result_set_from_error (close_data->result, error);
1399 /* this must be in an idle because the result is likely to be
1400 * intended for another thread
1402 g_simple_async_result_complete_in_idle (close_data->result);
1405 close_data_free (close_data);
1408 g_clear_error (&error);
1410 /* all messages queued for sending are discarded */
1411 g_queue_free_full (send_queue, (GDestroyNotify) message_to_write_data_free);
1412 /* all queued flushes fail */
1413 error = g_error_new (G_IO_ERROR, G_IO_ERROR_CANCELLED,
1414 _("Operation was cancelled"));
1415 flush_data_list_complete (pending_flush_attempts, error);
1416 g_list_free (pending_flush_attempts);
1417 g_clear_error (&error);
1419 _g_dbus_worker_unref (worker);
1422 /* called in private thread shared by all GDBusConnection instances
1424 * write-lock is not held on entry
1425 * output_pending must be PENDING_NONE on entry
1428 continue_writing (GDBusWorker *worker)
1430 MessageToWriteData *data;
1431 FlushAsyncData *flush_async_data;
1434 /* we mustn't try to write two things at once */
1435 g_assert (worker->output_pending == PENDING_NONE);
1437 g_mutex_lock (&worker->write_lock);
1440 flush_async_data = NULL;
1442 /* if we want to close the connection, that takes precedence */
1443 if (worker->pending_close_attempts != NULL)
1445 worker->close_expected = TRUE;
1446 worker->output_pending = PENDING_CLOSE;
1448 g_io_stream_close_async (worker->stream, G_PRIORITY_DEFAULT,
1449 NULL, iostream_close_cb,
1450 _g_dbus_worker_ref (worker));
1454 flush_async_data = prepare_flush_unlocked (worker);
1456 if (flush_async_data == NULL)
1458 data = g_queue_pop_head (worker->write_queue);
1461 worker->output_pending = PENDING_WRITE;
1465 g_mutex_unlock (&worker->write_lock);
1467 /* Note that write_lock is only used for protecting the @write_queue
1468 * and @output_pending fields of the GDBusWorker struct ... which we
1469 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1471 * Therefore, it's fine to drop it here when calling back into user
1472 * code and then writing the message out onto the GIOStream since this
1473 * function only runs on the worker thread.
1476 if (flush_async_data != NULL)
1478 start_flush (flush_async_data);
1479 g_assert (data == NULL);
1481 else if (data != NULL)
1483 GDBusMessage *old_message;
1485 gsize new_blob_size;
1488 old_message = data->message;
1489 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1490 if (data->message == old_message)
1492 /* filters had no effect - do nothing */
1494 else if (data->message == NULL)
1496 /* filters dropped message */
1497 g_mutex_lock (&worker->write_lock);
1498 worker->output_pending = PENDING_NONE;
1499 g_mutex_unlock (&worker->write_lock);
1500 message_to_write_data_free (data);
1505 /* filters altered the message -> reencode */
1507 new_blob = g_dbus_message_to_blob (data->message,
1509 worker->capabilities,
1511 if (new_blob == NULL)
1513 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1514 * the old message instead
1516 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1517 g_dbus_message_get_serial (data->message),
1519 g_error_free (error);
1523 g_free (data->blob);
1524 data->blob = (gchar *) new_blob;
1525 data->blob_size = new_blob_size;
1529 write_message_async (worker,
1536 /* called in private thread shared by all GDBusConnection instances
1538 * write-lock is not held on entry
1539 * output_pending may be anything
1542 continue_writing_in_idle_cb (gpointer user_data)
1544 GDBusWorker *worker = user_data;
1546 /* Because this is the worker thread, we can read this struct member
1547 * without holding the lock: no other thread ever modifies it.
1549 if (worker->output_pending == PENDING_NONE)
1550 continue_writing (worker);
1556 * @write_data: (transfer full) (allow-none):
1557 * @flush_data: (transfer full) (allow-none):
1558 * @close_data: (transfer full) (allow-none):
1560 * Can be called from any thread
1562 * write_lock is held on entry
1563 * output_pending may be anything
1566 schedule_writing_unlocked (GDBusWorker *worker,
1567 MessageToWriteData *write_data,
1568 FlushData *flush_data,
1569 CloseData *close_data)
1571 if (write_data != NULL)
1572 g_queue_push_tail (worker->write_queue, write_data);
1574 if (flush_data != NULL)
1575 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, flush_data);
1577 if (close_data != NULL)
1578 worker->pending_close_attempts = g_list_prepend (worker->pending_close_attempts,
1581 /* If we had output pending, the next bit of output will happen
1582 * automatically when it finishes, so we only need to do this
1583 * if nothing was pending.
1585 * The idle callback will re-check that output_pending is still
1586 * PENDING_NONE, to guard against output starting before the idle.
1588 if (worker->output_pending == PENDING_NONE)
1590 GSource *idle_source;
1591 idle_source = g_idle_source_new ();
1592 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1593 g_source_set_callback (idle_source,
1594 continue_writing_in_idle_cb,
1595 _g_dbus_worker_ref (worker),
1596 (GDestroyNotify) _g_dbus_worker_unref);
1597 g_source_attach (idle_source, worker->shared_thread_data->context);
1598 g_source_unref (idle_source);
1602 /* ---------------------------------------------------------------------------------------------------- */
1604 /* can be called from any thread - steals blob
1606 * write_lock is not held on entry
1607 * output_pending may be anything
1610 _g_dbus_worker_send_message (GDBusWorker *worker,
1611 GDBusMessage *message,
1615 MessageToWriteData *data;
1617 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1618 g_return_if_fail (blob != NULL);
1619 g_return_if_fail (blob_len > 16);
1621 data = g_new0 (MessageToWriteData, 1);
1622 data->worker = _g_dbus_worker_ref (worker);
1623 data->message = g_object_ref (message);
1624 data->blob = blob; /* steal! */
1625 data->blob_size = blob_len;
1627 g_mutex_lock (&worker->write_lock);
1628 schedule_writing_unlocked (worker, data, NULL, NULL);
1629 g_mutex_unlock (&worker->write_lock);
1632 /* ---------------------------------------------------------------------------------------------------- */
1635 _g_dbus_worker_new (GIOStream *stream,
1636 GDBusCapabilityFlags capabilities,
1637 gboolean initially_frozen,
1638 GDBusWorkerMessageReceivedCallback message_received_callback,
1639 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1640 GDBusWorkerDisconnectedCallback disconnected_callback,
1643 GDBusWorker *worker;
1644 GSource *idle_source;
1646 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1647 g_return_val_if_fail (message_received_callback != NULL, NULL);
1648 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1649 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1651 worker = g_new0 (GDBusWorker, 1);
1652 worker->ref_count = 1;
1654 g_mutex_init (&worker->read_lock);
1655 worker->message_received_callback = message_received_callback;
1656 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1657 worker->disconnected_callback = disconnected_callback;
1658 worker->user_data = user_data;
1659 worker->stream = g_object_ref (stream);
1660 worker->capabilities = capabilities;
1661 worker->cancellable = g_cancellable_new ();
1662 worker->output_pending = PENDING_NONE;
1664 worker->frozen = initially_frozen;
1665 worker->received_messages_while_frozen = g_queue_new ();
1667 g_mutex_init (&worker->write_lock);
1668 worker->write_queue = g_queue_new ();
1670 if (G_IS_SOCKET_CONNECTION (worker->stream))
1671 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1673 worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1676 idle_source = g_idle_source_new ();
1677 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1678 g_source_set_callback (idle_source,
1679 _g_dbus_worker_do_initial_read,
1680 _g_dbus_worker_ref (worker),
1681 (GDestroyNotify) _g_dbus_worker_unref);
1682 g_source_attach (idle_source, worker->shared_thread_data->context);
1683 g_source_unref (idle_source);
1688 /* ---------------------------------------------------------------------------------------------------- */
1690 /* can be called from any thread
1692 * write_lock is not held on entry
1693 * output_pending may be anything
1696 _g_dbus_worker_close (GDBusWorker *worker,
1697 GCancellable *cancellable,
1698 GSimpleAsyncResult *result)
1700 CloseData *close_data;
1702 close_data = g_slice_new0 (CloseData);
1703 close_data->worker = _g_dbus_worker_ref (worker);
1704 close_data->cancellable =
1705 (cancellable == NULL ? NULL : g_object_ref (cancellable));
1706 close_data->result = (result == NULL ? NULL : g_object_ref (result));
1708 /* Don't set worker->close_expected here - we're in the wrong thread.
1709 * It'll be set before the actual close happens.
1711 g_cancellable_cancel (worker->cancellable);
1712 g_mutex_lock (&worker->write_lock);
1713 schedule_writing_unlocked (worker, NULL, NULL, close_data);
1714 g_mutex_unlock (&worker->write_lock);
1717 /* This can be called from any thread - frees worker. Note that
1718 * callbacks might still happen if called from another thread than the
1719 * worker - use your own synchronization primitive in the callbacks.
1721 * write_lock is not held on entry
1722 * output_pending may be anything
1725 _g_dbus_worker_stop (GDBusWorker *worker)
1727 g_atomic_int_set (&worker->stopped, TRUE);
1729 /* Cancel any pending operations and schedule a close of the underlying I/O
1730 * stream in the worker thread
1732 _g_dbus_worker_close (worker, NULL, NULL);
1734 /* _g_dbus_worker_close holds a ref until after an idle in the the worker
1735 * thread has run, so we no longer need to unref in an idle like in
1738 _g_dbus_worker_unref (worker);
1741 /* ---------------------------------------------------------------------------------------------------- */
1743 /* can be called from any thread (except the worker thread) - blocks
1744 * calling thread until all queued outgoing messages are written and
1745 * the transport has been flushed
1747 * write_lock is not held on entry
1748 * output_pending may be anything
1751 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1752 GCancellable *cancellable,
1757 guint64 pending_writes;
1762 g_mutex_lock (&worker->write_lock);
1764 /* if the queue is empty, no write is in-flight and we haven't written
1765 * anything since the last flush, then there's nothing to wait for
1767 pending_writes = g_queue_get_length (worker->write_queue);
1769 /* if a write is in-flight, we shouldn't be satisfied until the first
1770 * flush operation that follows it
1772 if (worker->output_pending == PENDING_WRITE)
1773 pending_writes += 1;
1775 if (pending_writes > 0 ||
1776 worker->write_num_messages_written != worker->write_num_messages_flushed)
1778 data = g_new0 (FlushData, 1);
1779 g_mutex_init (&data->mutex);
1780 g_cond_init (&data->cond);
1781 data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
1782 g_mutex_lock (&data->mutex);
1784 schedule_writing_unlocked (worker, NULL, data, NULL);
1786 g_mutex_unlock (&worker->write_lock);
1790 g_cond_wait (&data->cond, &data->mutex);
1791 g_mutex_unlock (&data->mutex);
1793 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1794 g_cond_clear (&data->cond);
1795 g_mutex_clear (&data->mutex);
1796 if (data->error != NULL)
1799 g_propagate_error (error, data->error);
1807 /* ---------------------------------------------------------------------------------------------------- */
1809 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1810 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1811 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1812 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1813 #define G_DBUS_DEBUG_CALL (1<<4)
1814 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1815 #define G_DBUS_DEBUG_INCOMING (1<<6)
1816 #define G_DBUS_DEBUG_RETURN (1<<7)
1817 #define G_DBUS_DEBUG_EMISSION (1<<8)
1818 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1820 static gint _gdbus_debug_flags = 0;
1823 _g_dbus_debug_authentication (void)
1825 _g_dbus_initialize ();
1826 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1830 _g_dbus_debug_transport (void)
1832 _g_dbus_initialize ();
1833 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1837 _g_dbus_debug_message (void)
1839 _g_dbus_initialize ();
1840 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1844 _g_dbus_debug_payload (void)
1846 _g_dbus_initialize ();
1847 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1851 _g_dbus_debug_call (void)
1853 _g_dbus_initialize ();
1854 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1858 _g_dbus_debug_signal (void)
1860 _g_dbus_initialize ();
1861 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1865 _g_dbus_debug_incoming (void)
1867 _g_dbus_initialize ();
1868 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1872 _g_dbus_debug_return (void)
1874 _g_dbus_initialize ();
1875 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1879 _g_dbus_debug_emission (void)
1881 _g_dbus_initialize ();
1882 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1886 _g_dbus_debug_address (void)
1888 _g_dbus_initialize ();
1889 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1892 G_LOCK_DEFINE_STATIC (print_lock);
1895 _g_dbus_debug_print_lock (void)
1897 G_LOCK (print_lock);
1901 _g_dbus_debug_print_unlock (void)
1903 G_UNLOCK (print_lock);
1907 * _g_dbus_initialize:
1909 * Does various one-time init things such as
1911 * - registering the G_DBUS_ERROR error domain
1912 * - parses the G_DBUS_DEBUG environment variable
1915 _g_dbus_initialize (void)
1917 static volatile gsize initialized = 0;
1919 if (g_once_init_enter (&initialized))
1921 volatile GQuark g_dbus_error_domain;
1924 g_dbus_error_domain = G_DBUS_ERROR;
1925 (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1927 debug = g_getenv ("G_DBUS_DEBUG");
1930 const GDebugKey keys[] = {
1931 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1932 { "transport", G_DBUS_DEBUG_TRANSPORT },
1933 { "message", G_DBUS_DEBUG_MESSAGE },
1934 { "payload", G_DBUS_DEBUG_PAYLOAD },
1935 { "call", G_DBUS_DEBUG_CALL },
1936 { "signal", G_DBUS_DEBUG_SIGNAL },
1937 { "incoming", G_DBUS_DEBUG_INCOMING },
1938 { "return", G_DBUS_DEBUG_RETURN },
1939 { "emission", G_DBUS_DEBUG_EMISSION },
1940 { "address", G_DBUS_DEBUG_ADDRESS }
1943 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1944 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1945 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1948 g_once_init_leave (&initialized, 1);
1952 /* ---------------------------------------------------------------------------------------------------- */
1955 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1957 const GVariantType *arg_types[256];
1961 for (n = 0; args[n] != NULL; n++)
1963 /* DBus places a hard limit of 255 on signature length.
1964 * therefore number of args must be less than 256.
1968 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1970 if G_UNLIKELY (arg_types[n] == NULL)
1976 return g_variant_type_new_tuple (arg_types, n);
1979 /* ---------------------------------------------------------------------------------------------------- */
1983 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1986 _g_dbus_win32_get_user_sid (void)
1990 DWORD token_information_len;
1997 h = INVALID_HANDLE_VALUE;
1999 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
2001 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
2005 /* Get length of buffer */
2006 token_information_len = 0;
2007 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
2009 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
2011 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2015 user = g_malloc (token_information_len);
2016 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
2018 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2022 psid = user->User.Sid;
2023 if (!IsValidSid (psid))
2025 g_warning ("Invalid SID");
2029 if (!ConvertSidToStringSidA (psid, &sid))
2031 g_warning ("Invalid SID");
2035 ret = g_strdup (sid);
2040 if (h != INVALID_HANDLE_VALUE)
2046 /* ---------------------------------------------------------------------------------------------------- */
2049 _g_dbus_get_machine_id (GError **error)
2052 GError *first_error;
2053 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2056 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2060 !g_file_get_contents ("/etc/machine-id",
2065 g_propagate_prefixed_error (error, first_error,
2066 _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2070 /* ignore the error from the first try, if any */
2071 g_clear_error (&first_error);
2072 /* TODO: validate value */
2078 /* ---------------------------------------------------------------------------------------------------- */
2081 _g_dbus_enum_to_string (GType enum_type, gint value)
2085 GEnumValue *enum_value;
2087 klass = g_type_class_ref (enum_type);
2088 enum_value = g_enum_get_value (klass, value);
2089 if (enum_value != NULL)
2090 ret = g_strdup (enum_value->value_nick);
2092 ret = g_strdup_printf ("unknown (value %d)", value);
2093 g_type_class_unref (klass);
2097 /* ---------------------------------------------------------------------------------------------------- */
2100 write_message_print_transport_debug (gssize bytes_written,
2101 MessageToWriteData *data)
2103 if (G_LIKELY (!_g_dbus_debug_transport ()))
2106 _g_dbus_debug_print_lock ();
2107 g_print ("========================================================================\n"
2108 "GDBus-debug:Transport:\n"
2109 " >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2110 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
2112 g_dbus_message_get_serial (data->message),
2114 data->total_written,
2115 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
2116 _g_dbus_debug_print_unlock ();
2121 /* ---------------------------------------------------------------------------------------------------- */
2124 read_message_print_transport_debug (gssize bytes_read,
2125 GDBusWorker *worker)
2129 gint32 message_length;
2131 if (G_LIKELY (!_g_dbus_debug_transport ()))
2134 size = bytes_read + worker->read_buffer_cur_size;
2138 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2141 switch (worker->read_buffer[0])
2145 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2149 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2152 /* an error will be set elsewhere if this happens */
2157 _g_dbus_debug_print_lock ();
2158 g_print ("========================================================================\n"
2159 "GDBus-debug:Transport:\n"
2160 " <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2161 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
2165 worker->read_buffer_cur_size,
2166 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
2167 _g_dbus_debug_print_unlock ();
2172 /* ---------------------------------------------------------------------------------------------------- */
2175 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2176 GValue *return_accu,
2177 const GValue *handler_return,
2180 gboolean continue_emission;
2181 gboolean signal_return;
2183 signal_return = g_value_get_boolean (handler_return);
2184 g_value_set_boolean (return_accu, signal_return);
2185 continue_emission = signal_return;
2187 return continue_emission;