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 "glib/gstdio.h"
43 #include "gsocketcontrolmessage.h"
44 #include "gsocketconnection.h"
45 #include "gkdbusconnection.h"
46 #include "gsocketoutputstream.h"
49 #include "gunixfdmessage.h"
50 #include "gunixconnection.h"
51 #include "gunixcredentialsmessage.h"
60 static gboolean _g_dbus_worker_do_initial_read (gpointer data);
62 /* ---------------------------------------------------------------------------------------------------- */
65 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
70 ret = g_string_new (NULL);
72 for (n = 0; n < len; n += 16)
74 g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
76 for (m = n; m < n + 16; m++)
78 if (m > n && (m%4) == 0)
79 g_string_append_c (ret, ' ');
81 g_string_append_printf (ret, "%02x ", (guchar) data[m]);
83 g_string_append (ret, " ");
86 g_string_append (ret, " ");
88 for (m = n; m < len && m < n + 16; m++)
89 g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
91 g_string_append_c (ret, '\n');
94 return g_string_free (ret, FALSE);
97 /* ---------------------------------------------------------------------------------------------------- */
99 /* Unfortunately ancillary messages are discarded when reading from a
100 * socket using the GSocketInputStream abstraction. So we provide a
101 * very GInputStream-ish API that uses GSocket in this case (very
102 * similar to GSocketInputStream).
108 GCancellable *cancellable;
113 GSocketControlMessage ***messages;
116 GSimpleAsyncResult *simple;
118 gboolean from_mainloop;
119 } ReadWithControlData;
122 read_with_control_data_free (ReadWithControlData *data)
124 g_object_unref (data->socket);
125 if (data->cancellable != NULL)
126 g_object_unref (data->cancellable);
127 g_object_unref (data->simple);
132 _g_socket_read_with_control_messages_ready (GSocket *socket,
133 GIOCondition condition,
136 ReadWithControlData *data = user_data;
142 vector.buffer = data->buffer;
143 vector.size = data->count;
144 result = g_socket_receive_message (data->socket,
155 g_simple_async_result_set_op_res_gssize (data->simple, result);
159 g_assert (error != NULL);
160 g_simple_async_result_take_error (data->simple, error);
163 if (data->from_mainloop)
164 g_simple_async_result_complete (data->simple);
166 g_simple_async_result_complete_in_idle (data->simple);
172 _g_socket_read_with_control_messages (GSocket *socket,
175 GSocketControlMessage ***messages,
178 GCancellable *cancellable,
179 GAsyncReadyCallback callback,
182 ReadWithControlData *data;
184 data = g_new0 (ReadWithControlData, 1);
185 data->socket = g_object_ref (socket);
186 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
187 data->buffer = buffer;
189 data->messages = messages;
190 data->num_messages = num_messages;
192 data->simple = g_simple_async_result_new (G_OBJECT (socket),
195 _g_socket_read_with_control_messages);
196 g_simple_async_result_set_check_cancellable (data->simple, cancellable);
198 if (!g_socket_condition_check (socket, G_IO_IN))
201 data->from_mainloop = TRUE;
202 source = g_socket_create_source (data->socket,
203 G_IO_IN | G_IO_HUP | G_IO_ERR,
205 g_source_set_callback (source,
206 (GSourceFunc) _g_socket_read_with_control_messages_ready,
208 (GDestroyNotify) read_with_control_data_free);
209 g_source_attach (source, g_main_context_get_thread_default ());
210 g_source_unref (source);
214 _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
215 read_with_control_data_free (data);
220 _g_socket_read_with_control_messages_finish (GSocket *socket,
221 GAsyncResult *result,
224 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
226 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
227 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
229 if (g_simple_async_result_propagate_error (simple, error))
232 return g_simple_async_result_get_op_res_gssize (simple);
235 /* ---------------------------------------------------------------------------------------------------- */
237 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
239 static GPtrArray *ensured_classes = NULL;
242 ensure_type (GType gtype)
244 g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
248 release_required_types (void)
250 g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
251 g_ptr_array_unref (ensured_classes);
252 ensured_classes = NULL;
256 ensure_required_types (void)
258 g_assert (ensured_classes == NULL);
259 ensured_classes = g_ptr_array_new ();
260 ensure_type (G_TYPE_SIMPLE_ASYNC_RESULT);
261 ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
263 /* ---------------------------------------------------------------------------------------------------- */
267 volatile gint refcount;
269 GMainContext *context;
274 gdbus_shared_thread_func (gpointer user_data)
276 SharedThreadData *data = user_data;
278 g_main_context_push_thread_default (data->context);
279 g_main_loop_run (data->loop);
280 g_main_context_pop_thread_default (data->context);
282 release_required_types ();
287 /* ---------------------------------------------------------------------------------------------------- */
289 static SharedThreadData *
290 _g_dbus_shared_thread_ref (void)
292 static gsize shared_thread_data = 0;
293 SharedThreadData *ret;
295 if (g_once_init_enter (&shared_thread_data))
297 SharedThreadData *data;
299 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
300 ensure_required_types ();
302 data = g_new0 (SharedThreadData, 1);
305 data->context = g_main_context_new ();
306 data->loop = g_main_loop_new (data->context, FALSE);
307 data->thread = g_thread_new ("gdbus",
308 gdbus_shared_thread_func,
310 /* We can cast between gsize and gpointer safely */
311 g_once_init_leave (&shared_thread_data, (gsize) data);
314 ret = (SharedThreadData*) shared_thread_data;
315 g_atomic_int_inc (&ret->refcount);
320 _g_dbus_shared_thread_unref (SharedThreadData *data)
322 /* TODO: actually destroy the shared thread here */
324 g_assert (data != NULL);
325 if (g_atomic_int_dec_and_test (&data->refcount))
327 g_main_loop_quit (data->loop);
328 //g_thread_join (data->thread);
329 g_main_loop_unref (data->loop);
330 g_main_context_unref (data->context);
335 /* ---------------------------------------------------------------------------------------------------- */
346 volatile gint ref_count;
348 SharedThreadData *shared_thread_data;
350 /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
351 volatile gint stopped;
353 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
354 * only affects messages received from the other peer (since GDBusServer is the
355 * only user) - we might want it to affect messages sent to the other peer too?
358 GDBusCapabilityFlags capabilities;
359 GQueue *received_messages_while_frozen;
362 GCancellable *cancellable;
363 GDBusWorkerMessageReceivedCallback message_received_callback;
364 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
365 GDBusWorkerDisconnectedCallback disconnected_callback;
368 /* if GSocket and GKdbus are NULL, stream is GSocketConnection */
372 /* used for reading */
375 gsize read_buffer_allocated_size;
376 gsize read_buffer_cur_size;
377 gsize read_buffer_bytes_wanted;
378 GUnixFDList *read_fd_list;
379 GSocketControlMessage **read_ancillary_messages;
380 gint read_num_ancillary_messages;
382 /* Whether an async write, flush or close, or none of those, is pending.
383 * Only the worker thread may change its value, and only with the write_lock.
384 * Other threads may read its value when holding the write_lock.
385 * The worker thread may read its value at any time.
387 OutputPending output_pending;
388 /* used for writing */
390 /* queue of MessageToWriteData, protected by write_lock */
392 /* protected by write_lock */
393 guint64 write_num_messages_written;
394 /* number of messages we'd written out last time we flushed;
395 * protected by write_lock
397 guint64 write_num_messages_flushed;
398 /* list of FlushData, protected by write_lock */
399 GList *write_pending_flushes;
400 /* list of CloseData, protected by write_lock */
401 GList *pending_close_attempts;
402 /* no lock - only used from the worker thread */
403 gboolean close_expected;
406 static void _g_dbus_worker_unref (GDBusWorker *worker);
408 /* ---------------------------------------------------------------------------------------------------- */
414 guint64 number_to_wait_for;
418 struct _MessageToWriteData ;
419 typedef struct _MessageToWriteData MessageToWriteData;
421 static void message_to_write_data_free (MessageToWriteData *data);
423 static void read_message_print_transport_debug (gssize bytes_read,
424 GDBusWorker *worker);
426 static void write_message_print_transport_debug (gssize bytes_written,
427 MessageToWriteData *data);
431 GCancellable *cancellable;
432 GSimpleAsyncResult *result;
435 static void close_data_free (CloseData *close_data)
437 if (close_data->cancellable != NULL)
438 g_object_unref (close_data->cancellable);
440 if (close_data->result != NULL)
441 g_object_unref (close_data->result);
443 _g_dbus_worker_unref (close_data->worker);
444 g_slice_free (CloseData, close_data);
447 /* ---------------------------------------------------------------------------------------------------- */
450 _g_dbus_worker_ref (GDBusWorker *worker)
452 g_atomic_int_inc (&worker->ref_count);
457 _g_dbus_worker_unref (GDBusWorker *worker)
459 if (g_atomic_int_dec_and_test (&worker->ref_count))
461 g_assert (worker->write_pending_flushes == NULL);
463 _g_dbus_shared_thread_unref (worker->shared_thread_data);
465 g_object_unref (worker->stream);
467 g_mutex_clear (&worker->read_lock);
468 g_object_unref (worker->cancellable);
469 if (worker->read_fd_list != NULL)
470 g_object_unref (worker->read_fd_list);
472 g_queue_free_full (worker->received_messages_while_frozen, (GDestroyNotify) g_object_unref);
473 g_mutex_clear (&worker->write_lock);
474 g_queue_free_full (worker->write_queue, (GDestroyNotify) message_to_write_data_free);
475 g_free (worker->read_buffer);
482 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
483 gboolean remote_peer_vanished,
486 if (!g_atomic_int_get (&worker->stopped))
487 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
491 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
492 GDBusMessage *message)
494 if (!g_atomic_int_get (&worker->stopped))
495 worker->message_received_callback (worker, message, worker->user_data);
498 static GDBusMessage *
499 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
500 GDBusMessage *message)
503 if (!g_atomic_int_get (&worker->stopped))
504 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
510 /* can only be called from private thread with read-lock held - takes ownership of @message */
512 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
513 GDBusMessage *message)
515 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
518 g_queue_push_tail (worker->received_messages_while_frozen, message);
522 /* not frozen, nor anything in queue */
523 _g_dbus_worker_emit_message_received (worker, message);
524 g_object_unref (message);
528 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
530 unfreeze_in_idle_cb (gpointer user_data)
532 GDBusWorker *worker = user_data;
533 GDBusMessage *message;
535 g_mutex_lock (&worker->read_lock);
538 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
540 _g_dbus_worker_emit_message_received (worker, message);
541 g_object_unref (message);
543 worker->frozen = FALSE;
547 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
549 g_mutex_unlock (&worker->read_lock);
553 /* can be called from any thread */
555 _g_dbus_worker_unfreeze (GDBusWorker *worker)
557 GSource *idle_source;
558 idle_source = g_idle_source_new ();
559 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
560 g_source_set_callback (idle_source,
562 _g_dbus_worker_ref (worker),
563 (GDestroyNotify) _g_dbus_worker_unref);
564 g_source_attach (idle_source, worker->shared_thread_data->context);
565 g_source_unref (idle_source);
568 /* ---------------------------------------------------------------------------------------------------- */
570 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
572 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
574 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
578 GDBusWorker *worker = user_data;
582 g_mutex_lock (&worker->read_lock);
584 /* If already stopped, don't even process the reply */
585 if (g_atomic_int_get (&worker->stopped))
589 if (worker->socket == NULL)
590 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
594 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
597 if (worker->read_num_ancillary_messages > 0)
600 for (n = 0; n < worker->read_num_ancillary_messages; n++)
602 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
608 else if (G_IS_UNIX_FD_MESSAGE (control_message))
610 GUnixFDMessage *fd_message;
614 fd_message = G_UNIX_FD_MESSAGE (control_message);
615 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
616 if (worker->read_fd_list == NULL)
618 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
623 for (n = 0; n < num_fds; n++)
625 /* TODO: really want a append_steal() */
626 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
627 (void) g_close (fds[n], NULL);
632 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
644 "Unexpected ancillary message of type %s received from peer",
645 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
646 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
647 g_error_free (error);
648 g_object_unref (control_message);
650 while (n < worker->read_num_ancillary_messages)
651 g_object_unref (worker->read_ancillary_messages[n++]);
652 g_free (worker->read_ancillary_messages);
656 g_object_unref (control_message);
658 g_free (worker->read_ancillary_messages);
661 if (bytes_read == -1)
663 if (G_UNLIKELY (_g_dbus_debug_transport ()))
665 _g_dbus_debug_print_lock ();
666 g_print ("========================================================================\n"
667 "GDBus-debug:Transport:\n"
668 " ---- READ ERROR on stream of type %s:\n"
670 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))),
671 g_quark_to_string (error->domain), error->code,
673 _g_dbus_debug_print_unlock ();
676 /* Every async read that uses this callback uses worker->cancellable
677 * as its GCancellable. worker->cancellable gets cancelled if and only
678 * if the GDBusConnection tells us to close (either via
679 * _g_dbus_worker_stop, which is called on last-unref, or directly),
680 * so a cancelled read must mean our connection was closed locally.
682 * If we're closing, other errors are possible - notably,
683 * G_IO_ERROR_CLOSED can be seen if we close the stream with an async
684 * read in-flight. It seems sensible to treat all read errors during
685 * closing as an expected thing that doesn't trip exit-on-close.
687 * Because close_expected can't be set until we get into the worker
688 * thread, but the cancellable is signalled sooner (from another
689 * thread), we do still need to check the error.
691 if (worker->close_expected ||
692 g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
693 _g_dbus_worker_emit_disconnected (worker, FALSE, NULL);
695 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
697 g_error_free (error);
702 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
704 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
705 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
706 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
707 G_IO_IN | G_IO_OUT | G_IO_HUP),
712 /* TODO: hmm, hmm... */
718 "Underlying GIOStream returned 0 bytes on an async read");
719 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
720 g_error_free (error);
724 read_message_print_transport_debug (bytes_read, worker);
726 worker->read_buffer_cur_size += bytes_read;
727 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
729 /* OK, got what we asked for! */
730 if (worker->read_buffer_bytes_wanted == 16)
733 /* OK, got the header - determine how many more bytes are needed */
735 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
738 if (message_len == -1)
740 g_warning ("_g_dbus_worker_do_read_cb: error determining bytes needed: %s", error->message);
741 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
742 g_error_free (error);
746 worker->read_buffer_bytes_wanted = message_len;
747 _g_dbus_worker_do_read_unlocked (worker);
751 GDBusMessage *message;
754 /* TODO: use connection->priv->auth to decode the message */
756 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
757 worker->read_buffer_cur_size,
758 worker->capabilities,
763 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
764 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
766 "The payload is as follows:\n"
768 worker->read_buffer_cur_size,
772 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
773 g_error_free (error);
778 if (worker->read_fd_list != NULL)
780 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
781 g_object_unref (worker->read_fd_list);
782 worker->read_fd_list = NULL;
786 if (G_UNLIKELY (_g_dbus_debug_message ()))
789 _g_dbus_debug_print_lock ();
790 g_print ("========================================================================\n"
791 "GDBus-debug:Message:\n"
792 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
793 worker->read_buffer_cur_size);
794 s = g_dbus_message_print (message, 2);
797 if (G_UNLIKELY (_g_dbus_debug_payload ()))
799 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
803 _g_dbus_debug_print_unlock ();
806 /* yay, got a message, go deliver it */
807 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
809 /* start reading another message! */
810 worker->read_buffer_bytes_wanted = 0;
811 worker->read_buffer_cur_size = 0;
812 _g_dbus_worker_do_read_unlocked (worker);
817 /* didn't get all the bytes we requested - so repeat the request... */
818 _g_dbus_worker_do_read_unlocked (worker);
822 g_mutex_unlock (&worker->read_lock);
824 /* gives up the reference acquired when calling g_input_stream_read_async() */
825 _g_dbus_worker_unref (worker);
828 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
830 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
832 /* Note that we do need to keep trying to read even if close_expected is
833 * true, because only failing a read causes us to signal 'closed'.
836 /* if bytes_wanted is zero, it means start reading a message */
837 if (worker->read_buffer_bytes_wanted == 0)
839 worker->read_buffer_cur_size = 0;
840 worker->read_buffer_bytes_wanted = 16;
843 /* ensure we have a (big enough) buffer */
844 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
846 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
847 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
848 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
851 if (worker->socket == NULL)
852 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
853 worker->read_buffer + worker->read_buffer_cur_size,
854 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
857 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
858 _g_dbus_worker_ref (worker));
861 worker->read_ancillary_messages = NULL;
862 worker->read_num_ancillary_messages = 0;
863 _g_socket_read_with_control_messages (worker->socket,
864 worker->read_buffer + worker->read_buffer_cur_size,
865 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
866 &worker->read_ancillary_messages,
867 &worker->read_num_ancillary_messages,
870 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
871 _g_dbus_worker_ref (worker));
875 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
877 _g_dbus_worker_do_initial_read (gpointer data)
879 //GDBusWorker *worker = data;
880 //g_mutex_lock (&worker->read_lock);
881 //_g_dbus_worker_do_read_unlocked (worker);
882 //g_mutex_unlock (&worker->read_lock);
886 /* ---------------------------------------------------------------------------------------------------- */
888 struct _MessageToWriteData
891 GDBusMessage *message;
896 GSimpleAsyncResult *simple;
901 message_to_write_data_free (MessageToWriteData *data)
903 _g_dbus_worker_unref (data->worker);
905 g_object_unref (data->message);
910 /* ---------------------------------------------------------------------------------------------------- */
912 static void write_message_continue_writing (MessageToWriteData *data);
914 /* called in private thread shared by all GDBusConnection instances
916 * write-lock is not held on entry
917 * output_pending is PENDING_WRITE on entry
920 write_message_async_cb (GObject *source_object,
924 MessageToWriteData *data = user_data;
925 GSimpleAsyncResult *simple;
926 gssize bytes_written;
929 /* Note: we can't access data->simple after calling g_async_result_complete () because the
930 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
932 simple = data->simple;
935 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
938 if (bytes_written == -1)
940 g_simple_async_result_take_error (simple, error);
941 g_simple_async_result_complete (simple);
942 g_object_unref (simple);
945 g_assert (bytes_written > 0); /* zero is never returned */
947 write_message_print_transport_debug (bytes_written, data);
949 data->total_written += bytes_written;
950 g_assert (data->total_written <= data->blob_size);
951 if (data->total_written == data->blob_size)
953 g_simple_async_result_complete (simple);
954 g_object_unref (simple);
958 write_message_continue_writing (data);
964 /* called in private thread shared by all GDBusConnection instances
966 * write-lock is not held on entry
967 * output_pending is PENDING_WRITE on entry
971 on_socket_ready (GSocket *socket,
972 GIOCondition condition,
975 MessageToWriteData *data = user_data;
976 write_message_continue_writing (data);
977 return FALSE; /* remove source */
981 /* called in private thread shared by all GDBusConnection instances
983 * write-lock is not held on entry
984 * output_pending is PENDING_WRITE on entry
987 write_message_continue_writing (MessageToWriteData *data)
990 GSimpleAsyncResult *simple;
991 simple = data->simple;
994 if (G_IS_KDBUS_CONNECTION (data->worker->stream))
998 g_print("TEST KDBUS!\n");
999 g_kdbus_send_message(data->worker->kdbus, data->message, data->blob, data->blob_size, error);
1003 GOutputStream *ostream;
1005 GUnixFDList *fd_list;
1008 ostream = g_io_stream_get_output_stream (data->worker->stream);
1010 fd_list = g_dbus_message_get_unix_fd_list (data->message);
1013 g_assert (!g_output_stream_has_pending (ostream));
1014 g_assert_cmpint (data->total_written, <, data->blob_size);
1020 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
1022 GOutputVector vector;
1023 GSocketControlMessage *control_message;
1024 gssize bytes_written;
1027 vector.buffer = data->blob;
1028 vector.size = data->blob_size;
1030 control_message = NULL;
1031 if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
1033 if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
1035 g_simple_async_result_set_error (simple,
1038 "Tried sending a file descriptor but remote peer does not support this capability");
1039 g_simple_async_result_complete (simple);
1040 g_object_unref (simple);
1043 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1047 bytes_written = g_socket_send_message (data->worker->socket,
1051 control_message != NULL ? &control_message : NULL,
1052 control_message != NULL ? 1 : 0,
1054 data->worker->cancellable,
1056 if (control_message != NULL)
1057 g_object_unref (control_message);
1059 if (bytes_written == -1)
1061 /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1062 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1065 source = g_socket_create_source (data->worker->socket,
1066 G_IO_OUT | G_IO_HUP | G_IO_ERR,
1067 data->worker->cancellable);
1068 g_source_set_callback (source,
1069 (GSourceFunc) on_socket_ready,
1071 NULL); /* GDestroyNotify */
1072 g_source_attach (source, g_main_context_get_thread_default ());
1073 g_source_unref (source);
1074 g_error_free (error);
1077 g_simple_async_result_take_error (simple, error);
1078 g_simple_async_result_complete (simple);
1079 g_object_unref (simple);
1082 g_assert (bytes_written > 0); /* zero is never returned */
1084 write_message_print_transport_debug (bytes_written, data);
1086 data->total_written += bytes_written;
1087 g_assert (data->total_written <= data->blob_size);
1088 if (data->total_written == data->blob_size)
1090 g_simple_async_result_complete (simple);
1091 g_object_unref (simple);
1095 write_message_continue_writing (data);
1101 if (fd_list != NULL)
1103 g_simple_async_result_set_error (simple,
1106 "Tried sending a file descriptor on unsupported stream of type %s",
1107 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1108 g_simple_async_result_complete (simple);
1109 g_object_unref (simple);
1114 g_output_stream_write_async (ostream,
1115 (const gchar *) data->blob + data->total_written,
1116 data->blob_size - data->total_written,
1118 data->worker->cancellable,
1119 write_message_async_cb,
1129 /* called in private thread shared by all GDBusConnection instances
1131 * write-lock is not held on entry
1132 * output_pending is PENDING_WRITE on entry
1135 write_message_async (GDBusWorker *worker,
1136 MessageToWriteData *data,
1137 GAsyncReadyCallback callback,
1140 data->simple = g_simple_async_result_new (NULL,
1143 write_message_async);
1144 data->total_written = 0;
1145 write_message_continue_writing (data);
1148 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1150 write_message_finish (GAsyncResult *res,
1153 g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1154 if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1159 /* ---------------------------------------------------------------------------------------------------- */
1161 static void continue_writing (GDBusWorker *worker);
1165 GDBusWorker *worker;
1170 flush_data_list_complete (const GList *flushers,
1171 const GError *error)
1175 for (l = flushers; l != NULL; l = l->next)
1177 FlushData *f = l->data;
1179 f->error = error != NULL ? g_error_copy (error) : NULL;
1181 g_mutex_lock (&f->mutex);
1182 g_cond_signal (&f->cond);
1183 g_mutex_unlock (&f->mutex);
1187 /* called in private thread shared by all GDBusConnection instances
1189 * write-lock is not held on entry
1190 * output_pending is PENDING_FLUSH on entry
1193 ostream_flush_cb (GObject *source_object,
1197 FlushAsyncData *data = user_data;
1201 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1207 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1209 _g_dbus_debug_print_lock ();
1210 g_print ("========================================================================\n"
1211 "GDBus-debug:Transport:\n"
1212 " ---- FLUSHED stream of type %s\n",
1213 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1214 _g_dbus_debug_print_unlock ();
1218 g_assert (data->flushers != NULL);
1219 flush_data_list_complete (data->flushers, error);
1220 g_list_free (data->flushers);
1223 g_error_free (error);
1225 /* Make sure we tell folks that we don't have additional
1227 g_mutex_lock (&data->worker->write_lock);
1228 data->worker->write_num_messages_flushed = data->worker->write_num_messages_written;
1229 g_assert (data->worker->output_pending == PENDING_FLUSH);
1230 data->worker->output_pending = PENDING_NONE;
1231 g_mutex_unlock (&data->worker->write_lock);
1233 /* OK, cool, finally kick off the next write */
1234 continue_writing (data->worker);
1236 _g_dbus_worker_unref (data->worker);
1240 /* called in private thread shared by all GDBusConnection instances
1242 * write-lock is not held on entry
1243 * output_pending is PENDING_FLUSH on entry
1246 start_flush (FlushAsyncData *data)
1248 g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1250 data->worker->cancellable,
1255 /* called in private thread shared by all GDBusConnection instances
1257 * write-lock is held on entry
1258 * output_pending is PENDING_NONE on entry
1261 message_written_unlocked (GDBusWorker *worker,
1262 MessageToWriteData *message_data)
1264 if (G_UNLIKELY (_g_dbus_debug_message ()))
1267 _g_dbus_debug_print_lock ();
1268 g_print ("========================================================================\n"
1269 "GDBus-debug:Message:\n"
1270 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1271 message_data->blob_size);
1272 s = g_dbus_message_print (message_data->message, 2);
1275 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1277 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1278 g_print ("%s\n", s);
1281 _g_dbus_debug_print_unlock ();
1284 worker->write_num_messages_written += 1;
1287 /* called in private thread shared by all GDBusConnection instances
1289 * write-lock is held on entry
1290 * output_pending is PENDING_NONE on entry
1292 * Returns: non-%NULL, setting @output_pending, if we need to flush now
1294 static FlushAsyncData *
1295 prepare_flush_unlocked (GDBusWorker *worker)
1302 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1304 FlushData *f = l->data;
1307 if (f->number_to_wait_for == worker->write_num_messages_written)
1309 flushers = g_list_append (flushers, f);
1310 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1313 if (flushers != NULL)
1315 g_assert (worker->output_pending == PENDING_NONE);
1316 worker->output_pending = PENDING_FLUSH;
1319 if (flushers != NULL)
1321 FlushAsyncData *data;
1323 data = g_new0 (FlushAsyncData, 1);
1324 data->worker = _g_dbus_worker_ref (worker);
1325 data->flushers = flushers;
1332 /* called in private thread shared by all GDBusConnection instances
1334 * write-lock is not held on entry
1335 * output_pending is PENDING_WRITE on entry
1338 write_message_cb (GObject *source_object,
1342 MessageToWriteData *data = user_data;
1345 g_mutex_lock (&data->worker->write_lock);
1346 g_assert (data->worker->output_pending == PENDING_WRITE);
1347 data->worker->output_pending = PENDING_NONE;
1350 if (!write_message_finish (res, &error))
1352 g_mutex_unlock (&data->worker->write_lock);
1355 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1356 g_error_free (error);
1358 g_mutex_lock (&data->worker->write_lock);
1361 message_written_unlocked (data->worker, data);
1363 g_mutex_unlock (&data->worker->write_lock);
1365 continue_writing (data->worker);
1367 message_to_write_data_free (data);
1370 /* called in private thread shared by all GDBusConnection instances
1372 * write-lock is not held on entry
1373 * output_pending is PENDING_CLOSE on entry
1376 iostream_close_cb (GObject *source_object,
1380 GDBusWorker *worker = user_data;
1381 GError *error = NULL;
1382 GList *pending_close_attempts, *pending_flush_attempts;
1385 g_io_stream_close_finish (worker->stream, res, &error);
1387 g_mutex_lock (&worker->write_lock);
1389 pending_close_attempts = worker->pending_close_attempts;
1390 worker->pending_close_attempts = NULL;
1392 pending_flush_attempts = worker->write_pending_flushes;
1393 worker->write_pending_flushes = NULL;
1395 send_queue = worker->write_queue;
1396 worker->write_queue = g_queue_new ();
1398 g_assert (worker->output_pending == PENDING_CLOSE);
1399 worker->output_pending = PENDING_NONE;
1401 g_mutex_unlock (&worker->write_lock);
1403 while (pending_close_attempts != NULL)
1405 CloseData *close_data = pending_close_attempts->data;
1407 pending_close_attempts = g_list_delete_link (pending_close_attempts,
1408 pending_close_attempts);
1410 if (close_data->result != NULL)
1413 g_simple_async_result_set_from_error (close_data->result, error);
1415 /* this must be in an idle because the result is likely to be
1416 * intended for another thread
1418 g_simple_async_result_complete_in_idle (close_data->result);
1421 close_data_free (close_data);
1424 g_clear_error (&error);
1426 /* all messages queued for sending are discarded */
1427 g_queue_free_full (send_queue, (GDestroyNotify) message_to_write_data_free);
1428 /* all queued flushes fail */
1429 error = g_error_new (G_IO_ERROR, G_IO_ERROR_CANCELLED,
1430 _("Operation was cancelled"));
1431 flush_data_list_complete (pending_flush_attempts, error);
1432 g_list_free (pending_flush_attempts);
1433 g_clear_error (&error);
1435 _g_dbus_worker_unref (worker);
1438 /* called in private thread shared by all GDBusConnection instances
1440 * write-lock is not held on entry
1441 * output_pending must be PENDING_NONE on entry
1444 continue_writing (GDBusWorker *worker)
1446 MessageToWriteData *data;
1447 FlushAsyncData *flush_async_data;
1450 /* we mustn't try to write two things at once */
1451 g_assert (worker->output_pending == PENDING_NONE);
1453 g_mutex_lock (&worker->write_lock);
1456 flush_async_data = NULL;
1458 /* if we want to close the connection, that takes precedence */
1459 if (worker->pending_close_attempts != NULL)
1461 worker->close_expected = TRUE;
1462 worker->output_pending = PENDING_CLOSE;
1464 g_io_stream_close_async (worker->stream, G_PRIORITY_DEFAULT,
1465 NULL, iostream_close_cb,
1466 _g_dbus_worker_ref (worker));
1470 flush_async_data = prepare_flush_unlocked (worker);
1472 if (flush_async_data == NULL)
1474 data = g_queue_pop_head (worker->write_queue);
1477 worker->output_pending = PENDING_WRITE;
1481 g_mutex_unlock (&worker->write_lock);
1483 /* Note that write_lock is only used for protecting the @write_queue
1484 * and @output_pending fields of the GDBusWorker struct ... which we
1485 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1487 * Therefore, it's fine to drop it here when calling back into user
1488 * code and then writing the message out onto the GIOStream since this
1489 * function only runs on the worker thread.
1492 if (flush_async_data != NULL)
1494 start_flush (flush_async_data);
1495 g_assert (data == NULL);
1497 else if (data != NULL)
1499 GDBusMessage *old_message;
1501 gsize new_blob_size;
1504 old_message = data->message;
1505 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1506 if (data->message == old_message)
1508 /* filters had no effect - do nothing */
1510 else if (data->message == NULL)
1512 /* filters dropped message */
1513 g_mutex_lock (&worker->write_lock);
1514 worker->output_pending = PENDING_NONE;
1515 g_mutex_unlock (&worker->write_lock);
1516 message_to_write_data_free (data);
1521 /* filters altered the message -> reencode */
1523 new_blob = g_dbus_message_to_blob (data->message,
1525 worker->capabilities,
1527 if (new_blob == NULL)
1529 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1530 * the old message instead
1532 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1533 g_dbus_message_get_serial (data->message),
1535 g_error_free (error);
1539 g_free (data->blob);
1540 data->blob = (gchar *) new_blob;
1541 data->blob_size = new_blob_size;
1545 write_message_async (worker,
1552 /* called in private thread shared by all GDBusConnection instances
1554 * write-lock is not held on entry
1555 * output_pending may be anything
1558 continue_writing_in_idle_cb (gpointer user_data)
1560 GDBusWorker *worker = user_data;
1562 /* Because this is the worker thread, we can read this struct member
1563 * without holding the lock: no other thread ever modifies it.
1565 if (worker->output_pending == PENDING_NONE)
1566 continue_writing (worker);
1572 * @write_data: (transfer full) (allow-none):
1573 * @flush_data: (transfer full) (allow-none):
1574 * @close_data: (transfer full) (allow-none):
1576 * Can be called from any thread
1578 * write_lock is held on entry
1579 * output_pending may be anything
1582 schedule_writing_unlocked (GDBusWorker *worker,
1583 MessageToWriteData *write_data,
1584 FlushData *flush_data,
1585 CloseData *close_data)
1587 if (write_data != NULL)
1588 g_queue_push_tail (worker->write_queue, write_data);
1590 if (flush_data != NULL)
1591 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, flush_data);
1593 if (close_data != NULL)
1594 worker->pending_close_attempts = g_list_prepend (worker->pending_close_attempts,
1597 /* If we had output pending, the next bit of output will happen
1598 * automatically when it finishes, so we only need to do this
1599 * if nothing was pending.
1601 * The idle callback will re-check that output_pending is still
1602 * PENDING_NONE, to guard against output starting before the idle.
1604 if (worker->output_pending == PENDING_NONE)
1606 GSource *idle_source;
1607 idle_source = g_idle_source_new ();
1608 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1609 g_source_set_callback (idle_source,
1610 continue_writing_in_idle_cb,
1611 _g_dbus_worker_ref (worker),
1612 (GDestroyNotify) _g_dbus_worker_unref);
1613 g_source_attach (idle_source, worker->shared_thread_data->context);
1614 g_source_unref (idle_source);
1618 /* ---------------------------------------------------------------------------------------------------- */
1620 /* can be called from any thread - steals blob
1622 * write_lock is not held on entry
1623 * output_pending may be anything
1626 _g_dbus_worker_send_message (GDBusWorker *worker,
1627 GDBusMessage *message,
1631 MessageToWriteData *data;
1633 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1634 g_return_if_fail (blob != NULL);
1635 g_return_if_fail (blob_len > 16);
1637 data = g_new0 (MessageToWriteData, 1);
1638 data->worker = _g_dbus_worker_ref (worker);
1639 data->message = g_object_ref (message);
1640 data->blob = blob; /* steal! */
1641 data->blob_size = blob_len;
1643 g_mutex_lock (&worker->write_lock);
1644 schedule_writing_unlocked (worker, data, NULL, NULL);
1645 g_mutex_unlock (&worker->write_lock);
1648 /* ---------------------------------------------------------------------------------------------------- */
1651 _g_dbus_worker_new (GIOStream *stream,
1652 GDBusCapabilityFlags capabilities,
1653 gboolean initially_frozen,
1654 GDBusWorkerMessageReceivedCallback message_received_callback,
1655 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1656 GDBusWorkerDisconnectedCallback disconnected_callback,
1659 GDBusWorker *worker;
1660 GSource *idle_source;
1662 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1663 g_return_val_if_fail (message_received_callback != NULL, NULL);
1664 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1665 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1667 worker = g_new0 (GDBusWorker, 1);
1668 worker->ref_count = 1;
1670 g_mutex_init (&worker->read_lock);
1671 worker->message_received_callback = message_received_callback;
1672 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1673 worker->disconnected_callback = disconnected_callback;
1674 worker->user_data = user_data;
1675 worker->stream = g_object_ref (stream);
1676 worker->capabilities = capabilities;
1677 worker->cancellable = g_cancellable_new ();
1678 worker->output_pending = PENDING_NONE;
1680 worker->frozen = initially_frozen;
1681 worker->received_messages_while_frozen = g_queue_new ();
1683 g_mutex_init (&worker->write_lock);
1684 worker->write_queue = g_queue_new ();
1686 if (G_IS_SOCKET_CONNECTION (worker->stream))
1687 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1689 if (G_IS_KDBUS_CONNECTION (worker->stream))
1690 worker->kdbus = g_kdbus_connection_get_kdbus (G_KDBUS_CONNECTION (worker->stream));
1692 worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1695 idle_source = g_idle_source_new ();
1696 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1697 g_source_set_callback (idle_source,
1698 _g_dbus_worker_do_initial_read,
1699 _g_dbus_worker_ref (worker),
1700 (GDestroyNotify) _g_dbus_worker_unref);
1701 g_source_attach (idle_source, worker->shared_thread_data->context);
1702 g_source_unref (idle_source);
1707 /* ---------------------------------------------------------------------------------------------------- */
1709 /* can be called from any thread
1711 * write_lock is not held on entry
1712 * output_pending may be anything
1715 _g_dbus_worker_close (GDBusWorker *worker,
1716 GCancellable *cancellable,
1717 GSimpleAsyncResult *result)
1719 CloseData *close_data;
1721 close_data = g_slice_new0 (CloseData);
1722 close_data->worker = _g_dbus_worker_ref (worker);
1723 close_data->cancellable =
1724 (cancellable == NULL ? NULL : g_object_ref (cancellable));
1725 close_data->result = (result == NULL ? NULL : g_object_ref (result));
1727 /* Don't set worker->close_expected here - we're in the wrong thread.
1728 * It'll be set before the actual close happens.
1730 g_cancellable_cancel (worker->cancellable);
1731 g_mutex_lock (&worker->write_lock);
1732 schedule_writing_unlocked (worker, NULL, NULL, close_data);
1733 g_mutex_unlock (&worker->write_lock);
1736 /* This can be called from any thread - frees worker. Note that
1737 * callbacks might still happen if called from another thread than the
1738 * worker - use your own synchronization primitive in the callbacks.
1740 * write_lock is not held on entry
1741 * output_pending may be anything
1744 _g_dbus_worker_stop (GDBusWorker *worker)
1746 g_atomic_int_set (&worker->stopped, TRUE);
1748 /* Cancel any pending operations and schedule a close of the underlying I/O
1749 * stream in the worker thread
1751 _g_dbus_worker_close (worker, NULL, NULL);
1753 /* _g_dbus_worker_close holds a ref until after an idle in the worker
1754 * thread has run, so we no longer need to unref in an idle like in
1757 _g_dbus_worker_unref (worker);
1760 /* ---------------------------------------------------------------------------------------------------- */
1762 /* can be called from any thread (except the worker thread) - blocks
1763 * calling thread until all queued outgoing messages are written and
1764 * the transport has been flushed
1766 * write_lock is not held on entry
1767 * output_pending may be anything
1770 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1771 GCancellable *cancellable,
1776 guint64 pending_writes;
1781 g_mutex_lock (&worker->write_lock);
1783 /* if the queue is empty, no write is in-flight and we haven't written
1784 * anything since the last flush, then there's nothing to wait for
1786 pending_writes = g_queue_get_length (worker->write_queue);
1788 /* if a write is in-flight, we shouldn't be satisfied until the first
1789 * flush operation that follows it
1791 if (worker->output_pending == PENDING_WRITE)
1792 pending_writes += 1;
1794 if (pending_writes > 0 ||
1795 worker->write_num_messages_written != worker->write_num_messages_flushed)
1797 data = g_new0 (FlushData, 1);
1798 g_mutex_init (&data->mutex);
1799 g_cond_init (&data->cond);
1800 data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
1801 g_mutex_lock (&data->mutex);
1803 schedule_writing_unlocked (worker, NULL, data, NULL);
1805 g_mutex_unlock (&worker->write_lock);
1809 g_cond_wait (&data->cond, &data->mutex);
1810 g_mutex_unlock (&data->mutex);
1812 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1813 g_cond_clear (&data->cond);
1814 g_mutex_clear (&data->mutex);
1815 if (data->error != NULL)
1818 g_propagate_error (error, data->error);
1826 /* ---------------------------------------------------------------------------------------------------- */
1828 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1829 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1830 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1831 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1832 #define G_DBUS_DEBUG_CALL (1<<4)
1833 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1834 #define G_DBUS_DEBUG_INCOMING (1<<6)
1835 #define G_DBUS_DEBUG_RETURN (1<<7)
1836 #define G_DBUS_DEBUG_EMISSION (1<<8)
1837 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1839 static gint _gdbus_debug_flags = 0;
1842 _g_dbus_debug_authentication (void)
1844 _g_dbus_initialize ();
1845 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1849 _g_dbus_debug_transport (void)
1851 _g_dbus_initialize ();
1852 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1856 _g_dbus_debug_message (void)
1858 _g_dbus_initialize ();
1859 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1863 _g_dbus_debug_payload (void)
1865 _g_dbus_initialize ();
1866 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1870 _g_dbus_debug_call (void)
1872 _g_dbus_initialize ();
1873 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1877 _g_dbus_debug_signal (void)
1879 _g_dbus_initialize ();
1880 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1884 _g_dbus_debug_incoming (void)
1886 _g_dbus_initialize ();
1887 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1891 _g_dbus_debug_return (void)
1893 _g_dbus_initialize ();
1894 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1898 _g_dbus_debug_emission (void)
1900 _g_dbus_initialize ();
1901 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1905 _g_dbus_debug_address (void)
1907 _g_dbus_initialize ();
1908 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1911 G_LOCK_DEFINE_STATIC (print_lock);
1914 _g_dbus_debug_print_lock (void)
1916 G_LOCK (print_lock);
1920 _g_dbus_debug_print_unlock (void)
1922 G_UNLOCK (print_lock);
1926 * _g_dbus_initialize:
1928 * Does various one-time init things such as
1930 * - registering the G_DBUS_ERROR error domain
1931 * - parses the G_DBUS_DEBUG environment variable
1934 _g_dbus_initialize (void)
1936 static volatile gsize initialized = 0;
1938 if (g_once_init_enter (&initialized))
1940 volatile GQuark g_dbus_error_domain;
1943 g_dbus_error_domain = G_DBUS_ERROR;
1944 (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1946 debug = g_getenv ("G_DBUS_DEBUG");
1949 const GDebugKey keys[] = {
1950 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1951 { "transport", G_DBUS_DEBUG_TRANSPORT },
1952 { "message", G_DBUS_DEBUG_MESSAGE },
1953 { "payload", G_DBUS_DEBUG_PAYLOAD },
1954 { "call", G_DBUS_DEBUG_CALL },
1955 { "signal", G_DBUS_DEBUG_SIGNAL },
1956 { "incoming", G_DBUS_DEBUG_INCOMING },
1957 { "return", G_DBUS_DEBUG_RETURN },
1958 { "emission", G_DBUS_DEBUG_EMISSION },
1959 { "address", G_DBUS_DEBUG_ADDRESS }
1962 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1963 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1964 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1967 g_once_init_leave (&initialized, 1);
1971 /* ---------------------------------------------------------------------------------------------------- */
1974 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1976 const GVariantType *arg_types[256];
1980 for (n = 0; args[n] != NULL; n++)
1982 /* DBus places a hard limit of 255 on signature length.
1983 * therefore number of args must be less than 256.
1987 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1989 if G_UNLIKELY (arg_types[n] == NULL)
1995 return g_variant_type_new_tuple (arg_types, n);
1998 /* ---------------------------------------------------------------------------------------------------- */
2002 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
2005 _g_dbus_win32_get_user_sid (void)
2009 DWORD token_information_len;
2016 h = INVALID_HANDLE_VALUE;
2018 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
2020 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
2024 /* Get length of buffer */
2025 token_information_len = 0;
2026 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
2028 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
2030 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2034 user = g_malloc (token_information_len);
2035 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
2037 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2041 psid = user->User.Sid;
2042 if (!IsValidSid (psid))
2044 g_warning ("Invalid SID");
2048 if (!ConvertSidToStringSidA (psid, &sid))
2050 g_warning ("Invalid SID");
2054 ret = g_strdup (sid);
2059 if (h != INVALID_HANDLE_VALUE)
2065 /* ---------------------------------------------------------------------------------------------------- */
2068 _g_dbus_get_machine_id (GError **error)
2071 HW_PROFILE_INFOA info;
2072 char *src, *dest, *res;
2075 if (!GetCurrentHwProfileA (&info))
2077 char *message = g_win32_error_message (GetLastError ());
2081 _("Unable to get Hardware profile: %s"), message);
2086 /* Form: {12340001-4980-1920-6788-123456789012} */
2087 src = &info.szHwProfileGuid[0];
2089 res = g_malloc (32+1);
2093 for (i = 0; i < 8; i++)
2096 for (i = 0; i < 4; i++)
2099 for (i = 0; i < 4; i++)
2102 for (i = 0; i < 4; i++)
2105 for (i = 0; i < 12; i++)
2112 GError *first_error;
2113 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2116 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2120 !g_file_get_contents ("/etc/machine-id",
2125 g_propagate_prefixed_error (error, first_error,
2126 _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2130 /* ignore the error from the first try, if any */
2131 g_clear_error (&first_error);
2132 /* TODO: validate value */
2139 /* ---------------------------------------------------------------------------------------------------- */
2142 _g_dbus_enum_to_string (GType enum_type, gint value)
2146 GEnumValue *enum_value;
2148 klass = g_type_class_ref (enum_type);
2149 enum_value = g_enum_get_value (klass, value);
2150 if (enum_value != NULL)
2151 ret = g_strdup (enum_value->value_nick);
2153 ret = g_strdup_printf ("unknown (value %d)", value);
2154 g_type_class_unref (klass);
2158 /* ---------------------------------------------------------------------------------------------------- */
2161 write_message_print_transport_debug (gssize bytes_written,
2162 MessageToWriteData *data)
2164 if (G_LIKELY (!_g_dbus_debug_transport ()))
2167 _g_dbus_debug_print_lock ();
2168 g_print ("========================================================================\n"
2169 "GDBus-debug:Transport:\n"
2170 " >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2171 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
2173 g_dbus_message_get_serial (data->message),
2175 data->total_written,
2176 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
2177 _g_dbus_debug_print_unlock ();
2182 /* ---------------------------------------------------------------------------------------------------- */
2185 read_message_print_transport_debug (gssize bytes_read,
2186 GDBusWorker *worker)
2190 gint32 message_length;
2192 if (G_LIKELY (!_g_dbus_debug_transport ()))
2195 size = bytes_read + worker->read_buffer_cur_size;
2199 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2202 switch (worker->read_buffer[0])
2206 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2210 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2213 /* an error will be set elsewhere if this happens */
2218 _g_dbus_debug_print_lock ();
2219 g_print ("========================================================================\n"
2220 "GDBus-debug:Transport:\n"
2221 " <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2222 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
2226 worker->read_buffer_cur_size,
2227 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
2228 _g_dbus_debug_print_unlock ();
2233 /* ---------------------------------------------------------------------------------------------------- */
2236 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2237 GValue *return_accu,
2238 const GValue *handler_return,
2241 gboolean continue_emission;
2242 gboolean signal_return;
2244 signal_return = g_value_get_boolean (handler_return);
2245 g_value_set_boolean (return_accu, signal_return);
2246 continue_emission = signal_return;
2248 return continue_emission;