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, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
28 #include "gdbusprivate.h"
29 #include "gdbusmessage.h"
30 #include "gdbuserror.h"
31 #include "gdbusintrospection.h"
32 #include "gasyncresult.h"
33 #include "gsimpleasyncresult.h"
34 #include "ginputstream.h"
35 #include "gmemoryinputstream.h"
36 #include "giostream.h"
37 #include "glib/gstdio.h"
38 #include "gsocketcontrolmessage.h"
39 #include "gsocketconnection.h"
40 #include "gsocketoutputstream.h"
43 #include "gunixfdmessage.h"
44 #include "gunixconnection.h"
45 #include "gunixcredentialsmessage.h"
54 static gboolean _g_dbus_worker_do_initial_read (gpointer data);
56 /* ---------------------------------------------------------------------------------------------------- */
59 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
64 ret = g_string_new (NULL);
66 for (n = 0; n < len; n += 16)
68 g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
70 for (m = n; m < n + 16; m++)
72 if (m > n && (m%4) == 0)
73 g_string_append_c (ret, ' ');
75 g_string_append_printf (ret, "%02x ", (guchar) data[m]);
77 g_string_append (ret, " ");
80 g_string_append (ret, " ");
82 for (m = n; m < len && m < n + 16; m++)
83 g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
85 g_string_append_c (ret, '\n');
88 return g_string_free (ret, FALSE);
91 /* ---------------------------------------------------------------------------------------------------- */
93 /* Unfortunately ancillary messages are discarded when reading from a
94 * socket using the GSocketInputStream abstraction. So we provide a
95 * very GInputStream-ish API that uses GSocket in this case (very
96 * similar to GSocketInputStream).
102 GCancellable *cancellable;
107 GSocketControlMessage ***messages;
110 GSimpleAsyncResult *simple;
112 gboolean from_mainloop;
113 } ReadWithControlData;
116 read_with_control_data_free (ReadWithControlData *data)
118 g_object_unref (data->socket);
119 if (data->cancellable != NULL)
120 g_object_unref (data->cancellable);
121 g_object_unref (data->simple);
126 _g_socket_read_with_control_messages_ready (GSocket *socket,
127 GIOCondition condition,
130 ReadWithControlData *data = user_data;
136 vector.buffer = data->buffer;
137 vector.size = data->count;
138 result = g_socket_receive_message (data->socket,
149 g_simple_async_result_set_op_res_gssize (data->simple, result);
153 g_assert (error != NULL);
154 g_simple_async_result_take_error (data->simple, error);
157 if (data->from_mainloop)
158 g_simple_async_result_complete (data->simple);
160 g_simple_async_result_complete_in_idle (data->simple);
166 _g_socket_read_with_control_messages (GSocket *socket,
169 GSocketControlMessage ***messages,
172 GCancellable *cancellable,
173 GAsyncReadyCallback callback,
176 ReadWithControlData *data;
178 data = g_new0 (ReadWithControlData, 1);
179 data->socket = g_object_ref (socket);
180 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
181 data->buffer = buffer;
183 data->messages = messages;
184 data->num_messages = num_messages;
186 data->simple = g_simple_async_result_new (G_OBJECT (socket),
189 _g_socket_read_with_control_messages);
190 g_simple_async_result_set_check_cancellable (data->simple, cancellable);
192 if (!g_socket_condition_check (socket, G_IO_IN))
195 data->from_mainloop = TRUE;
196 source = g_socket_create_source (data->socket,
197 G_IO_IN | G_IO_HUP | G_IO_ERR,
199 g_source_set_callback (source,
200 (GSourceFunc) _g_socket_read_with_control_messages_ready,
202 (GDestroyNotify) read_with_control_data_free);
203 g_source_attach (source, g_main_context_get_thread_default ());
204 g_source_unref (source);
208 _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
209 read_with_control_data_free (data);
214 _g_socket_read_with_control_messages_finish (GSocket *socket,
215 GAsyncResult *result,
218 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
220 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
221 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
223 if (g_simple_async_result_propagate_error (simple, error))
226 return g_simple_async_result_get_op_res_gssize (simple);
229 /* ---------------------------------------------------------------------------------------------------- */
231 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
233 static GPtrArray *ensured_classes = NULL;
236 ensure_type (GType gtype)
238 g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
242 release_required_types (void)
244 g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
245 g_ptr_array_unref (ensured_classes);
246 ensured_classes = NULL;
250 ensure_required_types (void)
252 g_assert (ensured_classes == NULL);
253 ensured_classes = g_ptr_array_new ();
254 ensure_type (G_TYPE_SIMPLE_ASYNC_RESULT);
255 ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
257 /* ---------------------------------------------------------------------------------------------------- */
261 volatile gint refcount;
263 GMainContext *context;
268 gdbus_shared_thread_func (gpointer user_data)
270 SharedThreadData *data = user_data;
272 g_main_context_push_thread_default (data->context);
273 g_main_loop_run (data->loop);
274 g_main_context_pop_thread_default (data->context);
276 release_required_types ();
281 /* ---------------------------------------------------------------------------------------------------- */
283 static SharedThreadData *
284 _g_dbus_shared_thread_ref (void)
286 static gsize shared_thread_data = 0;
287 SharedThreadData *ret;
289 if (g_once_init_enter (&shared_thread_data))
291 SharedThreadData *data;
293 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
294 ensure_required_types ();
296 data = g_new0 (SharedThreadData, 1);
299 data->context = g_main_context_new ();
300 data->loop = g_main_loop_new (data->context, FALSE);
301 data->thread = g_thread_new ("gdbus",
302 gdbus_shared_thread_func,
304 /* We can cast between gsize and gpointer safely */
305 g_once_init_leave (&shared_thread_data, (gsize) data);
308 ret = (SharedThreadData*) shared_thread_data;
309 g_atomic_int_inc (&ret->refcount);
314 _g_dbus_shared_thread_unref (SharedThreadData *data)
316 /* TODO: actually destroy the shared thread here */
318 g_assert (data != NULL);
319 if (g_atomic_int_dec_and_test (&data->refcount))
321 g_main_loop_quit (data->loop);
322 //g_thread_join (data->thread);
323 g_main_loop_unref (data->loop);
324 g_main_context_unref (data->context);
329 /* ---------------------------------------------------------------------------------------------------- */
340 volatile gint ref_count;
342 SharedThreadData *shared_thread_data;
344 /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
345 volatile gint stopped;
347 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
348 * only affects messages received from the other peer (since GDBusServer is the
349 * only user) - we might want it to affect messages sent to the other peer too?
352 GDBusCapabilityFlags capabilities;
353 GQueue *received_messages_while_frozen;
356 GCancellable *cancellable;
357 GDBusWorkerMessageReceivedCallback message_received_callback;
358 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
359 GDBusWorkerDisconnectedCallback disconnected_callback;
362 /* if not NULL, stream is GSocketConnection */
365 /* used for reading */
368 gsize read_buffer_allocated_size;
369 gsize read_buffer_cur_size;
370 gsize read_buffer_bytes_wanted;
371 GUnixFDList *read_fd_list;
372 GSocketControlMessage **read_ancillary_messages;
373 gint read_num_ancillary_messages;
375 /* Whether an async write, flush or close, or none of those, is pending.
376 * Only the worker thread may change its value, and only with the write_lock.
377 * Other threads may read its value when holding the write_lock.
378 * The worker thread may read its value at any time.
380 OutputPending output_pending;
381 /* used for writing */
383 /* queue of MessageToWriteData, protected by write_lock */
385 /* protected by write_lock */
386 guint64 write_num_messages_written;
387 /* number of messages we'd written out last time we flushed;
388 * protected by write_lock
390 guint64 write_num_messages_flushed;
391 /* list of FlushData, protected by write_lock */
392 GList *write_pending_flushes;
393 /* list of CloseData, protected by write_lock */
394 GList *pending_close_attempts;
395 /* no lock - only used from the worker thread */
396 gboolean close_expected;
399 static void _g_dbus_worker_unref (GDBusWorker *worker);
401 /* ---------------------------------------------------------------------------------------------------- */
407 guint64 number_to_wait_for;
411 struct _MessageToWriteData ;
412 typedef struct _MessageToWriteData MessageToWriteData;
414 static void message_to_write_data_free (MessageToWriteData *data);
416 static void read_message_print_transport_debug (gssize bytes_read,
417 GDBusWorker *worker);
419 static void write_message_print_transport_debug (gssize bytes_written,
420 MessageToWriteData *data);
424 GCancellable *cancellable;
425 GSimpleAsyncResult *result;
428 static void close_data_free (CloseData *close_data)
430 if (close_data->cancellable != NULL)
431 g_object_unref (close_data->cancellable);
433 if (close_data->result != NULL)
434 g_object_unref (close_data->result);
436 _g_dbus_worker_unref (close_data->worker);
437 g_slice_free (CloseData, close_data);
440 /* ---------------------------------------------------------------------------------------------------- */
443 _g_dbus_worker_ref (GDBusWorker *worker)
445 g_atomic_int_inc (&worker->ref_count);
450 _g_dbus_worker_unref (GDBusWorker *worker)
452 if (g_atomic_int_dec_and_test (&worker->ref_count))
454 g_assert (worker->write_pending_flushes == NULL);
456 _g_dbus_shared_thread_unref (worker->shared_thread_data);
458 g_object_unref (worker->stream);
460 g_mutex_clear (&worker->read_lock);
461 g_object_unref (worker->cancellable);
462 if (worker->read_fd_list != NULL)
463 g_object_unref (worker->read_fd_list);
465 g_queue_free_full (worker->received_messages_while_frozen, (GDestroyNotify) g_object_unref);
466 g_mutex_clear (&worker->write_lock);
467 g_queue_free_full (worker->write_queue, (GDestroyNotify) message_to_write_data_free);
468 g_free (worker->read_buffer);
475 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
476 gboolean remote_peer_vanished,
479 if (!g_atomic_int_get (&worker->stopped))
480 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
484 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
485 GDBusMessage *message)
487 if (!g_atomic_int_get (&worker->stopped))
488 worker->message_received_callback (worker, message, worker->user_data);
491 static GDBusMessage *
492 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
493 GDBusMessage *message)
496 if (!g_atomic_int_get (&worker->stopped))
497 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
503 /* can only be called from private thread with read-lock held - takes ownership of @message */
505 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
506 GDBusMessage *message)
508 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
511 g_queue_push_tail (worker->received_messages_while_frozen, message);
515 /* not frozen, nor anything in queue */
516 _g_dbus_worker_emit_message_received (worker, message);
517 g_object_unref (message);
521 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
523 unfreeze_in_idle_cb (gpointer user_data)
525 GDBusWorker *worker = user_data;
526 GDBusMessage *message;
528 g_mutex_lock (&worker->read_lock);
531 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
533 _g_dbus_worker_emit_message_received (worker, message);
534 g_object_unref (message);
536 worker->frozen = FALSE;
540 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
542 g_mutex_unlock (&worker->read_lock);
546 /* can be called from any thread */
548 _g_dbus_worker_unfreeze (GDBusWorker *worker)
550 GSource *idle_source;
551 idle_source = g_idle_source_new ();
552 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
553 g_source_set_callback (idle_source,
555 _g_dbus_worker_ref (worker),
556 (GDestroyNotify) _g_dbus_worker_unref);
557 g_source_attach (idle_source, worker->shared_thread_data->context);
558 g_source_unref (idle_source);
561 /* ---------------------------------------------------------------------------------------------------- */
563 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
565 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
567 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
571 GDBusWorker *worker = user_data;
575 g_mutex_lock (&worker->read_lock);
577 /* If already stopped, don't even process the reply */
578 if (g_atomic_int_get (&worker->stopped))
582 if (worker->socket == NULL)
583 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
587 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
590 if (worker->read_num_ancillary_messages > 0)
593 for (n = 0; n < worker->read_num_ancillary_messages; n++)
595 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
601 else if (G_IS_UNIX_FD_MESSAGE (control_message))
603 GUnixFDMessage *fd_message;
607 fd_message = G_UNIX_FD_MESSAGE (control_message);
608 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
609 if (worker->read_fd_list == NULL)
611 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
616 for (n = 0; n < num_fds; n++)
618 /* TODO: really want a append_steal() */
619 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
620 (void) g_close (fds[n], NULL);
625 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
637 "Unexpected ancillary message of type %s received from peer",
638 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
639 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
640 g_error_free (error);
641 g_object_unref (control_message);
643 while (n < worker->read_num_ancillary_messages)
644 g_object_unref (worker->read_ancillary_messages[n++]);
645 g_free (worker->read_ancillary_messages);
649 g_object_unref (control_message);
651 g_free (worker->read_ancillary_messages);
654 if (bytes_read == -1)
656 if (G_UNLIKELY (_g_dbus_debug_transport ()))
658 _g_dbus_debug_print_lock ();
659 g_print ("========================================================================\n"
660 "GDBus-debug:Transport:\n"
661 " ---- READ ERROR on stream of type %s:\n"
663 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))),
664 g_quark_to_string (error->domain), error->code,
666 _g_dbus_debug_print_unlock ();
669 /* Every async read that uses this callback uses worker->cancellable
670 * as its GCancellable. worker->cancellable gets cancelled if and only
671 * if the GDBusConnection tells us to close (either via
672 * _g_dbus_worker_stop, which is called on last-unref, or directly),
673 * so a cancelled read must mean our connection was closed locally.
675 * If we're closing, other errors are possible - notably,
676 * G_IO_ERROR_CLOSED can be seen if we close the stream with an async
677 * read in-flight. It seems sensible to treat all read errors during
678 * closing as an expected thing that doesn't trip exit-on-close.
680 * Because close_expected can't be set until we get into the worker
681 * thread, but the cancellable is signalled sooner (from another
682 * thread), we do still need to check the error.
684 if (worker->close_expected ||
685 g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
686 _g_dbus_worker_emit_disconnected (worker, FALSE, NULL);
688 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
690 g_error_free (error);
695 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
697 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
698 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
699 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
700 G_IO_IN | G_IO_OUT | G_IO_HUP),
705 /* TODO: hmm, hmm... */
711 "Underlying GIOStream returned 0 bytes on an async read");
712 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
713 g_error_free (error);
717 read_message_print_transport_debug (bytes_read, worker);
719 worker->read_buffer_cur_size += bytes_read;
720 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
722 /* OK, got what we asked for! */
723 if (worker->read_buffer_bytes_wanted == 16)
726 /* OK, got the header - determine how many more bytes are needed */
728 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
731 if (message_len == -1)
733 g_warning ("_g_dbus_worker_do_read_cb: error determining bytes needed: %s", error->message);
734 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
735 g_error_free (error);
739 worker->read_buffer_bytes_wanted = message_len;
740 _g_dbus_worker_do_read_unlocked (worker);
744 GDBusMessage *message;
747 /* TODO: use connection->priv->auth to decode the message */
749 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
750 worker->read_buffer_cur_size,
751 worker->capabilities,
756 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
757 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
759 "The payload is as follows:\n"
761 worker->read_buffer_cur_size,
765 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
766 g_error_free (error);
771 if (worker->read_fd_list != NULL)
773 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
774 g_object_unref (worker->read_fd_list);
775 worker->read_fd_list = NULL;
779 if (G_UNLIKELY (_g_dbus_debug_message ()))
782 _g_dbus_debug_print_lock ();
783 g_print ("========================================================================\n"
784 "GDBus-debug:Message:\n"
785 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
786 worker->read_buffer_cur_size);
787 s = g_dbus_message_print (message, 2);
790 if (G_UNLIKELY (_g_dbus_debug_payload ()))
792 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
796 _g_dbus_debug_print_unlock ();
799 /* yay, got a message, go deliver it */
800 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
802 /* start reading another message! */
803 worker->read_buffer_bytes_wanted = 0;
804 worker->read_buffer_cur_size = 0;
805 _g_dbus_worker_do_read_unlocked (worker);
810 /* didn't get all the bytes we requested - so repeat the request... */
811 _g_dbus_worker_do_read_unlocked (worker);
815 g_mutex_unlock (&worker->read_lock);
817 /* gives up the reference acquired when calling g_input_stream_read_async() */
818 _g_dbus_worker_unref (worker);
821 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
823 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
825 /* Note that we do need to keep trying to read even if close_expected is
826 * true, because only failing a read causes us to signal 'closed'.
829 /* if bytes_wanted is zero, it means start reading a message */
830 if (worker->read_buffer_bytes_wanted == 0)
832 worker->read_buffer_cur_size = 0;
833 worker->read_buffer_bytes_wanted = 16;
836 /* ensure we have a (big enough) buffer */
837 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
839 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
840 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
841 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
844 if (worker->socket == NULL)
845 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
846 worker->read_buffer + worker->read_buffer_cur_size,
847 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
850 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
851 _g_dbus_worker_ref (worker));
854 worker->read_ancillary_messages = NULL;
855 worker->read_num_ancillary_messages = 0;
856 _g_socket_read_with_control_messages (worker->socket,
857 worker->read_buffer + worker->read_buffer_cur_size,
858 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
859 &worker->read_ancillary_messages,
860 &worker->read_num_ancillary_messages,
863 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
864 _g_dbus_worker_ref (worker));
868 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
870 _g_dbus_worker_do_initial_read (gpointer data)
872 GDBusWorker *worker = data;
873 g_mutex_lock (&worker->read_lock);
874 _g_dbus_worker_do_read_unlocked (worker);
875 g_mutex_unlock (&worker->read_lock);
879 /* ---------------------------------------------------------------------------------------------------- */
881 struct _MessageToWriteData
884 GDBusMessage *message;
889 GSimpleAsyncResult *simple;
894 message_to_write_data_free (MessageToWriteData *data)
896 _g_dbus_worker_unref (data->worker);
898 g_object_unref (data->message);
903 /* ---------------------------------------------------------------------------------------------------- */
905 static void write_message_continue_writing (MessageToWriteData *data);
907 /* called in private thread shared by all GDBusConnection instances
909 * write-lock is not held on entry
910 * output_pending is PENDING_WRITE on entry
913 write_message_async_cb (GObject *source_object,
917 MessageToWriteData *data = user_data;
918 GSimpleAsyncResult *simple;
919 gssize bytes_written;
922 /* Note: we can't access data->simple after calling g_async_result_complete () because the
923 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
925 simple = data->simple;
928 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
931 if (bytes_written == -1)
933 g_simple_async_result_take_error (simple, error);
934 g_simple_async_result_complete (simple);
935 g_object_unref (simple);
938 g_assert (bytes_written > 0); /* zero is never returned */
940 write_message_print_transport_debug (bytes_written, data);
942 data->total_written += bytes_written;
943 g_assert (data->total_written <= data->blob_size);
944 if (data->total_written == data->blob_size)
946 g_simple_async_result_complete (simple);
947 g_object_unref (simple);
951 write_message_continue_writing (data);
957 /* called in private thread shared by all GDBusConnection instances
959 * write-lock is not held on entry
960 * output_pending is PENDING_WRITE on entry
964 on_socket_ready (GSocket *socket,
965 GIOCondition condition,
968 MessageToWriteData *data = user_data;
969 write_message_continue_writing (data);
970 return FALSE; /* remove source */
974 /* called in private thread shared by all GDBusConnection instances
976 * write-lock is not held on entry
977 * output_pending is PENDING_WRITE on entry
980 write_message_continue_writing (MessageToWriteData *data)
982 GOutputStream *ostream;
984 GSimpleAsyncResult *simple;
985 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;
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,
1115 /* called in private thread shared by all GDBusConnection instances
1117 * write-lock is not held on entry
1118 * output_pending is PENDING_WRITE on entry
1121 write_message_async (GDBusWorker *worker,
1122 MessageToWriteData *data,
1123 GAsyncReadyCallback callback,
1126 data->simple = g_simple_async_result_new (NULL,
1129 write_message_async);
1130 data->total_written = 0;
1131 write_message_continue_writing (data);
1134 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1136 write_message_finish (GAsyncResult *res,
1139 g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1140 if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1145 /* ---------------------------------------------------------------------------------------------------- */
1147 static void continue_writing (GDBusWorker *worker);
1151 GDBusWorker *worker;
1156 flush_data_list_complete (const GList *flushers,
1157 const GError *error)
1161 for (l = flushers; l != NULL; l = l->next)
1163 FlushData *f = l->data;
1165 f->error = error != NULL ? g_error_copy (error) : NULL;
1167 g_mutex_lock (&f->mutex);
1168 g_cond_signal (&f->cond);
1169 g_mutex_unlock (&f->mutex);
1173 /* called in private thread shared by all GDBusConnection instances
1175 * write-lock is not held on entry
1176 * output_pending is PENDING_FLUSH on entry
1179 ostream_flush_cb (GObject *source_object,
1183 FlushAsyncData *data = user_data;
1187 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1193 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1195 _g_dbus_debug_print_lock ();
1196 g_print ("========================================================================\n"
1197 "GDBus-debug:Transport:\n"
1198 " ---- FLUSHED stream of type %s\n",
1199 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1200 _g_dbus_debug_print_unlock ();
1204 g_assert (data->flushers != NULL);
1205 flush_data_list_complete (data->flushers, error);
1206 g_list_free (data->flushers);
1209 g_error_free (error);
1211 /* Make sure we tell folks that we don't have additional
1213 g_mutex_lock (&data->worker->write_lock);
1214 data->worker->write_num_messages_flushed = data->worker->write_num_messages_written;
1215 g_assert (data->worker->output_pending == PENDING_FLUSH);
1216 data->worker->output_pending = PENDING_NONE;
1217 g_mutex_unlock (&data->worker->write_lock);
1219 /* OK, cool, finally kick off the next write */
1220 continue_writing (data->worker);
1222 _g_dbus_worker_unref (data->worker);
1226 /* called in private thread shared by all GDBusConnection instances
1228 * write-lock is not held on entry
1229 * output_pending is PENDING_FLUSH on entry
1232 start_flush (FlushAsyncData *data)
1234 g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1236 data->worker->cancellable,
1241 /* called in private thread shared by all GDBusConnection instances
1243 * write-lock is held on entry
1244 * output_pending is PENDING_NONE on entry
1247 message_written_unlocked (GDBusWorker *worker,
1248 MessageToWriteData *message_data)
1250 if (G_UNLIKELY (_g_dbus_debug_message ()))
1253 _g_dbus_debug_print_lock ();
1254 g_print ("========================================================================\n"
1255 "GDBus-debug:Message:\n"
1256 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1257 message_data->blob_size);
1258 s = g_dbus_message_print (message_data->message, 2);
1261 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1263 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1264 g_print ("%s\n", s);
1267 _g_dbus_debug_print_unlock ();
1270 worker->write_num_messages_written += 1;
1273 /* called in private thread shared by all GDBusConnection instances
1275 * write-lock is held on entry
1276 * output_pending is PENDING_NONE on entry
1278 * Returns: non-%NULL, setting @output_pending, if we need to flush now
1280 static FlushAsyncData *
1281 prepare_flush_unlocked (GDBusWorker *worker)
1288 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1290 FlushData *f = l->data;
1293 if (f->number_to_wait_for == worker->write_num_messages_written)
1295 flushers = g_list_append (flushers, f);
1296 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1299 if (flushers != NULL)
1301 g_assert (worker->output_pending == PENDING_NONE);
1302 worker->output_pending = PENDING_FLUSH;
1305 if (flushers != NULL)
1307 FlushAsyncData *data;
1309 data = g_new0 (FlushAsyncData, 1);
1310 data->worker = _g_dbus_worker_ref (worker);
1311 data->flushers = flushers;
1318 /* called in private thread shared by all GDBusConnection instances
1320 * write-lock is not held on entry
1321 * output_pending is PENDING_WRITE on entry
1324 write_message_cb (GObject *source_object,
1328 MessageToWriteData *data = user_data;
1331 g_mutex_lock (&data->worker->write_lock);
1332 g_assert (data->worker->output_pending == PENDING_WRITE);
1333 data->worker->output_pending = PENDING_NONE;
1336 if (!write_message_finish (res, &error))
1338 g_mutex_unlock (&data->worker->write_lock);
1341 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1342 g_error_free (error);
1344 g_mutex_lock (&data->worker->write_lock);
1347 message_written_unlocked (data->worker, data);
1349 g_mutex_unlock (&data->worker->write_lock);
1351 continue_writing (data->worker);
1353 message_to_write_data_free (data);
1356 /* called in private thread shared by all GDBusConnection instances
1358 * write-lock is not held on entry
1359 * output_pending is PENDING_CLOSE on entry
1362 iostream_close_cb (GObject *source_object,
1366 GDBusWorker *worker = user_data;
1367 GError *error = NULL;
1368 GList *pending_close_attempts, *pending_flush_attempts;
1371 g_io_stream_close_finish (worker->stream, res, &error);
1373 g_mutex_lock (&worker->write_lock);
1375 pending_close_attempts = worker->pending_close_attempts;
1376 worker->pending_close_attempts = NULL;
1378 pending_flush_attempts = worker->write_pending_flushes;
1379 worker->write_pending_flushes = NULL;
1381 send_queue = worker->write_queue;
1382 worker->write_queue = g_queue_new ();
1384 g_assert (worker->output_pending == PENDING_CLOSE);
1385 worker->output_pending = PENDING_NONE;
1387 g_mutex_unlock (&worker->write_lock);
1389 while (pending_close_attempts != NULL)
1391 CloseData *close_data = pending_close_attempts->data;
1393 pending_close_attempts = g_list_delete_link (pending_close_attempts,
1394 pending_close_attempts);
1396 if (close_data->result != NULL)
1399 g_simple_async_result_set_from_error (close_data->result, error);
1401 /* this must be in an idle because the result is likely to be
1402 * intended for another thread
1404 g_simple_async_result_complete_in_idle (close_data->result);
1407 close_data_free (close_data);
1410 g_clear_error (&error);
1412 /* all messages queued for sending are discarded */
1413 g_queue_free_full (send_queue, (GDestroyNotify) message_to_write_data_free);
1414 /* all queued flushes fail */
1415 error = g_error_new (G_IO_ERROR, G_IO_ERROR_CANCELLED,
1416 _("Operation was cancelled"));
1417 flush_data_list_complete (pending_flush_attempts, error);
1418 g_list_free (pending_flush_attempts);
1419 g_clear_error (&error);
1421 _g_dbus_worker_unref (worker);
1424 /* called in private thread shared by all GDBusConnection instances
1426 * write-lock is not held on entry
1427 * output_pending must be PENDING_NONE on entry
1430 continue_writing (GDBusWorker *worker)
1432 MessageToWriteData *data;
1433 FlushAsyncData *flush_async_data;
1436 /* we mustn't try to write two things at once */
1437 g_assert (worker->output_pending == PENDING_NONE);
1439 g_mutex_lock (&worker->write_lock);
1442 flush_async_data = NULL;
1444 /* if we want to close the connection, that takes precedence */
1445 if (worker->pending_close_attempts != NULL)
1447 worker->close_expected = TRUE;
1448 worker->output_pending = PENDING_CLOSE;
1450 g_io_stream_close_async (worker->stream, G_PRIORITY_DEFAULT,
1451 NULL, iostream_close_cb,
1452 _g_dbus_worker_ref (worker));
1456 flush_async_data = prepare_flush_unlocked (worker);
1458 if (flush_async_data == NULL)
1460 data = g_queue_pop_head (worker->write_queue);
1463 worker->output_pending = PENDING_WRITE;
1467 g_mutex_unlock (&worker->write_lock);
1469 /* Note that write_lock is only used for protecting the @write_queue
1470 * and @output_pending fields of the GDBusWorker struct ... which we
1471 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1473 * Therefore, it's fine to drop it here when calling back into user
1474 * code and then writing the message out onto the GIOStream since this
1475 * function only runs on the worker thread.
1478 if (flush_async_data != NULL)
1480 start_flush (flush_async_data);
1481 g_assert (data == NULL);
1483 else if (data != NULL)
1485 GDBusMessage *old_message;
1487 gsize new_blob_size;
1490 old_message = data->message;
1491 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1492 if (data->message == old_message)
1494 /* filters had no effect - do nothing */
1496 else if (data->message == NULL)
1498 /* filters dropped message */
1499 g_mutex_lock (&worker->write_lock);
1500 worker->output_pending = PENDING_NONE;
1501 g_mutex_unlock (&worker->write_lock);
1502 message_to_write_data_free (data);
1507 /* filters altered the message -> reencode */
1509 new_blob = g_dbus_message_to_blob (data->message,
1511 worker->capabilities,
1513 if (new_blob == NULL)
1515 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1516 * the old message instead
1518 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1519 g_dbus_message_get_serial (data->message),
1521 g_error_free (error);
1525 g_free (data->blob);
1526 data->blob = (gchar *) new_blob;
1527 data->blob_size = new_blob_size;
1531 write_message_async (worker,
1538 /* called in private thread shared by all GDBusConnection instances
1540 * write-lock is not held on entry
1541 * output_pending may be anything
1544 continue_writing_in_idle_cb (gpointer user_data)
1546 GDBusWorker *worker = user_data;
1548 /* Because this is the worker thread, we can read this struct member
1549 * without holding the lock: no other thread ever modifies it.
1551 if (worker->output_pending == PENDING_NONE)
1552 continue_writing (worker);
1558 * @write_data: (transfer full) (allow-none):
1559 * @flush_data: (transfer full) (allow-none):
1560 * @close_data: (transfer full) (allow-none):
1562 * Can be called from any thread
1564 * write_lock is held on entry
1565 * output_pending may be anything
1568 schedule_writing_unlocked (GDBusWorker *worker,
1569 MessageToWriteData *write_data,
1570 FlushData *flush_data,
1571 CloseData *close_data)
1573 if (write_data != NULL)
1574 g_queue_push_tail (worker->write_queue, write_data);
1576 if (flush_data != NULL)
1577 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, flush_data);
1579 if (close_data != NULL)
1580 worker->pending_close_attempts = g_list_prepend (worker->pending_close_attempts,
1583 /* If we had output pending, the next bit of output will happen
1584 * automatically when it finishes, so we only need to do this
1585 * if nothing was pending.
1587 * The idle callback will re-check that output_pending is still
1588 * PENDING_NONE, to guard against output starting before the idle.
1590 if (worker->output_pending == PENDING_NONE)
1592 GSource *idle_source;
1593 idle_source = g_idle_source_new ();
1594 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1595 g_source_set_callback (idle_source,
1596 continue_writing_in_idle_cb,
1597 _g_dbus_worker_ref (worker),
1598 (GDestroyNotify) _g_dbus_worker_unref);
1599 g_source_attach (idle_source, worker->shared_thread_data->context);
1600 g_source_unref (idle_source);
1604 /* ---------------------------------------------------------------------------------------------------- */
1606 /* can be called from any thread - steals blob
1608 * write_lock is not held on entry
1609 * output_pending may be anything
1612 _g_dbus_worker_send_message (GDBusWorker *worker,
1613 GDBusMessage *message,
1617 MessageToWriteData *data;
1619 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1620 g_return_if_fail (blob != NULL);
1621 g_return_if_fail (blob_len > 16);
1623 data = g_new0 (MessageToWriteData, 1);
1624 data->worker = _g_dbus_worker_ref (worker);
1625 data->message = g_object_ref (message);
1626 data->blob = blob; /* steal! */
1627 data->blob_size = blob_len;
1629 g_mutex_lock (&worker->write_lock);
1630 schedule_writing_unlocked (worker, data, NULL, NULL);
1631 g_mutex_unlock (&worker->write_lock);
1634 /* ---------------------------------------------------------------------------------------------------- */
1637 _g_dbus_worker_new (GIOStream *stream,
1638 GDBusCapabilityFlags capabilities,
1639 gboolean initially_frozen,
1640 GDBusWorkerMessageReceivedCallback message_received_callback,
1641 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1642 GDBusWorkerDisconnectedCallback disconnected_callback,
1645 GDBusWorker *worker;
1646 GSource *idle_source;
1648 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1649 g_return_val_if_fail (message_received_callback != NULL, NULL);
1650 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1651 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1653 worker = g_new0 (GDBusWorker, 1);
1654 worker->ref_count = 1;
1656 g_mutex_init (&worker->read_lock);
1657 worker->message_received_callback = message_received_callback;
1658 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1659 worker->disconnected_callback = disconnected_callback;
1660 worker->user_data = user_data;
1661 worker->stream = g_object_ref (stream);
1662 worker->capabilities = capabilities;
1663 worker->cancellable = g_cancellable_new ();
1664 worker->output_pending = PENDING_NONE;
1666 worker->frozen = initially_frozen;
1667 worker->received_messages_while_frozen = g_queue_new ();
1669 g_mutex_init (&worker->write_lock);
1670 worker->write_queue = g_queue_new ();
1672 if (G_IS_SOCKET_CONNECTION (worker->stream))
1673 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1675 worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1678 idle_source = g_idle_source_new ();
1679 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1680 g_source_set_callback (idle_source,
1681 _g_dbus_worker_do_initial_read,
1682 _g_dbus_worker_ref (worker),
1683 (GDestroyNotify) _g_dbus_worker_unref);
1684 g_source_attach (idle_source, worker->shared_thread_data->context);
1685 g_source_unref (idle_source);
1690 /* ---------------------------------------------------------------------------------------------------- */
1692 /* can be called from any thread
1694 * write_lock is not held on entry
1695 * output_pending may be anything
1698 _g_dbus_worker_close (GDBusWorker *worker,
1699 GCancellable *cancellable,
1700 GSimpleAsyncResult *result)
1702 CloseData *close_data;
1704 close_data = g_slice_new0 (CloseData);
1705 close_data->worker = _g_dbus_worker_ref (worker);
1706 close_data->cancellable =
1707 (cancellable == NULL ? NULL : g_object_ref (cancellable));
1708 close_data->result = (result == NULL ? NULL : g_object_ref (result));
1710 /* Don't set worker->close_expected here - we're in the wrong thread.
1711 * It'll be set before the actual close happens.
1713 g_cancellable_cancel (worker->cancellable);
1714 g_mutex_lock (&worker->write_lock);
1715 schedule_writing_unlocked (worker, NULL, NULL, close_data);
1716 g_mutex_unlock (&worker->write_lock);
1719 /* This can be called from any thread - frees worker. Note that
1720 * callbacks might still happen if called from another thread than the
1721 * worker - use your own synchronization primitive in the callbacks.
1723 * write_lock is not held on entry
1724 * output_pending may be anything
1727 _g_dbus_worker_stop (GDBusWorker *worker)
1729 g_atomic_int_set (&worker->stopped, TRUE);
1731 /* Cancel any pending operations and schedule a close of the underlying I/O
1732 * stream in the worker thread
1734 _g_dbus_worker_close (worker, NULL, NULL);
1736 /* _g_dbus_worker_close holds a ref until after an idle in the worker
1737 * thread has run, so we no longer need to unref in an idle like in
1740 _g_dbus_worker_unref (worker);
1743 /* ---------------------------------------------------------------------------------------------------- */
1745 /* can be called from any thread (except the worker thread) - blocks
1746 * calling thread until all queued outgoing messages are written and
1747 * the transport has been flushed
1749 * write_lock is not held on entry
1750 * output_pending may be anything
1753 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1754 GCancellable *cancellable,
1759 guint64 pending_writes;
1764 g_mutex_lock (&worker->write_lock);
1766 /* if the queue is empty, no write is in-flight and we haven't written
1767 * anything since the last flush, then there's nothing to wait for
1769 pending_writes = g_queue_get_length (worker->write_queue);
1771 /* if a write is in-flight, we shouldn't be satisfied until the first
1772 * flush operation that follows it
1774 if (worker->output_pending == PENDING_WRITE)
1775 pending_writes += 1;
1777 if (pending_writes > 0 ||
1778 worker->write_num_messages_written != worker->write_num_messages_flushed)
1780 data = g_new0 (FlushData, 1);
1781 g_mutex_init (&data->mutex);
1782 g_cond_init (&data->cond);
1783 data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
1784 g_mutex_lock (&data->mutex);
1786 schedule_writing_unlocked (worker, NULL, data, NULL);
1788 g_mutex_unlock (&worker->write_lock);
1792 g_cond_wait (&data->cond, &data->mutex);
1793 g_mutex_unlock (&data->mutex);
1795 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1796 g_cond_clear (&data->cond);
1797 g_mutex_clear (&data->mutex);
1798 if (data->error != NULL)
1801 g_propagate_error (error, data->error);
1809 /* ---------------------------------------------------------------------------------------------------- */
1811 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1812 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1813 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1814 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1815 #define G_DBUS_DEBUG_CALL (1<<4)
1816 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1817 #define G_DBUS_DEBUG_INCOMING (1<<6)
1818 #define G_DBUS_DEBUG_RETURN (1<<7)
1819 #define G_DBUS_DEBUG_EMISSION (1<<8)
1820 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1822 static gint _gdbus_debug_flags = 0;
1825 _g_dbus_debug_authentication (void)
1827 _g_dbus_initialize ();
1828 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1832 _g_dbus_debug_transport (void)
1834 _g_dbus_initialize ();
1835 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1839 _g_dbus_debug_message (void)
1841 _g_dbus_initialize ();
1842 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1846 _g_dbus_debug_payload (void)
1848 _g_dbus_initialize ();
1849 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1853 _g_dbus_debug_call (void)
1855 _g_dbus_initialize ();
1856 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1860 _g_dbus_debug_signal (void)
1862 _g_dbus_initialize ();
1863 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1867 _g_dbus_debug_incoming (void)
1869 _g_dbus_initialize ();
1870 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1874 _g_dbus_debug_return (void)
1876 _g_dbus_initialize ();
1877 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1881 _g_dbus_debug_emission (void)
1883 _g_dbus_initialize ();
1884 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1888 _g_dbus_debug_address (void)
1890 _g_dbus_initialize ();
1891 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1894 G_LOCK_DEFINE_STATIC (print_lock);
1897 _g_dbus_debug_print_lock (void)
1899 G_LOCK (print_lock);
1903 _g_dbus_debug_print_unlock (void)
1905 G_UNLOCK (print_lock);
1909 * _g_dbus_initialize:
1911 * Does various one-time init things such as
1913 * - registering the G_DBUS_ERROR error domain
1914 * - parses the G_DBUS_DEBUG environment variable
1917 _g_dbus_initialize (void)
1919 static volatile gsize initialized = 0;
1921 if (g_once_init_enter (&initialized))
1923 volatile GQuark g_dbus_error_domain;
1926 g_dbus_error_domain = G_DBUS_ERROR;
1927 (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1929 debug = g_getenv ("G_DBUS_DEBUG");
1932 const GDebugKey keys[] = {
1933 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1934 { "transport", G_DBUS_DEBUG_TRANSPORT },
1935 { "message", G_DBUS_DEBUG_MESSAGE },
1936 { "payload", G_DBUS_DEBUG_PAYLOAD },
1937 { "call", G_DBUS_DEBUG_CALL },
1938 { "signal", G_DBUS_DEBUG_SIGNAL },
1939 { "incoming", G_DBUS_DEBUG_INCOMING },
1940 { "return", G_DBUS_DEBUG_RETURN },
1941 { "emission", G_DBUS_DEBUG_EMISSION },
1942 { "address", G_DBUS_DEBUG_ADDRESS }
1945 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1946 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1947 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1950 g_once_init_leave (&initialized, 1);
1954 /* ---------------------------------------------------------------------------------------------------- */
1957 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1959 const GVariantType *arg_types[256];
1963 for (n = 0; args[n] != NULL; n++)
1965 /* DBus places a hard limit of 255 on signature length.
1966 * therefore number of args must be less than 256.
1970 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1972 if G_UNLIKELY (arg_types[n] == NULL)
1978 return g_variant_type_new_tuple (arg_types, n);
1981 /* ---------------------------------------------------------------------------------------------------- */
1985 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1988 _g_dbus_win32_get_user_sid (void)
1992 DWORD token_information_len;
1999 h = INVALID_HANDLE_VALUE;
2001 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
2003 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
2007 /* Get length of buffer */
2008 token_information_len = 0;
2009 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
2011 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
2013 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2017 user = g_malloc (token_information_len);
2018 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
2020 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2024 psid = user->User.Sid;
2025 if (!IsValidSid (psid))
2027 g_warning ("Invalid SID");
2031 if (!ConvertSidToStringSidA (psid, &sid))
2033 g_warning ("Invalid SID");
2037 ret = g_strdup (sid);
2042 if (h != INVALID_HANDLE_VALUE)
2048 /* ---------------------------------------------------------------------------------------------------- */
2051 _g_dbus_get_machine_id (GError **error)
2054 HW_PROFILE_INFOA info;
2055 char *src, *dest, *res;
2058 if (!GetCurrentHwProfileA (&info))
2060 char *message = g_win32_error_message (GetLastError ());
2064 _("Unable to get Hardware profile: %s"), message);
2069 /* Form: {12340001-4980-1920-6788-123456789012} */
2070 src = &info.szHwProfileGuid[0];
2072 res = g_malloc (32+1);
2076 for (i = 0; i < 8; i++)
2079 for (i = 0; i < 4; i++)
2082 for (i = 0; i < 4; i++)
2085 for (i = 0; i < 4; i++)
2088 for (i = 0; i < 12; i++)
2095 GError *first_error;
2096 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2099 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2103 !g_file_get_contents ("/etc/machine-id",
2108 g_propagate_prefixed_error (error, first_error,
2109 _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2113 /* ignore the error from the first try, if any */
2114 g_clear_error (&first_error);
2115 /* TODO: validate value */
2122 /* ---------------------------------------------------------------------------------------------------- */
2125 _g_dbus_enum_to_string (GType enum_type, gint value)
2129 GEnumValue *enum_value;
2131 klass = g_type_class_ref (enum_type);
2132 enum_value = g_enum_get_value (klass, value);
2133 if (enum_value != NULL)
2134 ret = g_strdup (enum_value->value_nick);
2136 ret = g_strdup_printf ("unknown (value %d)", value);
2137 g_type_class_unref (klass);
2141 /* ---------------------------------------------------------------------------------------------------- */
2144 write_message_print_transport_debug (gssize bytes_written,
2145 MessageToWriteData *data)
2147 if (G_LIKELY (!_g_dbus_debug_transport ()))
2150 _g_dbus_debug_print_lock ();
2151 g_print ("========================================================================\n"
2152 "GDBus-debug:Transport:\n"
2153 " >>>> WROTE %" G_GSSIZE_FORMAT " bytes of message with serial %d and\n"
2154 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
2156 g_dbus_message_get_serial (data->message),
2158 data->total_written,
2159 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
2160 _g_dbus_debug_print_unlock ();
2165 /* ---------------------------------------------------------------------------------------------------- */
2168 read_message_print_transport_debug (gssize bytes_read,
2169 GDBusWorker *worker)
2173 gint32 message_length;
2175 if (G_LIKELY (!_g_dbus_debug_transport ()))
2178 size = bytes_read + worker->read_buffer_cur_size;
2182 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2185 switch (worker->read_buffer[0])
2189 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2193 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2196 /* an error will be set elsewhere if this happens */
2201 _g_dbus_debug_print_lock ();
2202 g_print ("========================================================================\n"
2203 "GDBus-debug:Transport:\n"
2204 " <<<< READ %" G_GSSIZE_FORMAT " bytes of message with serial %d and\n"
2205 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
2209 worker->read_buffer_cur_size,
2210 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
2211 _g_dbus_debug_print_unlock ();
2216 /* ---------------------------------------------------------------------------------------------------- */
2219 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2220 GValue *return_accu,
2221 const GValue *handler_return,
2224 gboolean continue_emission;
2225 gboolean signal_return;
2227 signal_return = g_value_get_boolean (handler_return);
2228 g_value_set_boolean (return_accu, signal_return);
2229 continue_emission = signal_return;
2231 return continue_emission;