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.1 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>
27 #include "gioenumtypes.h"
29 #include "gdbusauthobserver.h"
30 #include "gdbusprivate.h"
31 #include "gdbusmessage.h"
32 #include "gdbusconnection.h"
33 #include "gdbusproxy.h"
34 #include "gdbuserror.h"
35 #include "gdbusintrospection.h"
36 #include "gdbusdaemon.h"
37 #include "giomodule-priv.h"
39 #include "ginputstream.h"
40 #include "gmemoryinputstream.h"
41 #include "giostream.h"
42 #include "glib/gstdio.h"
43 #include "gsocketaddress.h"
44 #include "gsocketcontrolmessage.h"
45 #include "gsocketconnection.h"
46 #include "gsocketoutputstream.h"
49 #include "gunixfdmessage.h"
50 #include "gunixconnection.h"
51 #include "gunixcredentialsmessage.h"
62 static gboolean _g_dbus_worker_do_initial_read (gpointer data);
63 static void schedule_pending_close (GDBusWorker *worker);
65 /* ---------------------------------------------------------------------------------------------------- */
68 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
73 ret = g_string_new (NULL);
75 for (n = 0; n < len; n += 16)
77 g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
79 for (m = n; m < n + 16; m++)
81 if (m > n && (m%4) == 0)
82 g_string_append_c (ret, ' ');
84 g_string_append_printf (ret, "%02x ", (guchar) data[m]);
86 g_string_append (ret, " ");
89 g_string_append (ret, " ");
91 for (m = n; m < len && m < n + 16; m++)
92 g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
94 g_string_append_c (ret, '\n');
97 return g_string_free (ret, FALSE);
100 /* ---------------------------------------------------------------------------------------------------- */
102 /* Unfortunately ancillary messages are discarded when reading from a
103 * socket using the GSocketInputStream abstraction. So we provide a
104 * very GInputStream-ish API that uses GSocket in this case (very
105 * similar to GSocketInputStream).
113 GSocketControlMessage ***messages;
115 } ReadWithControlData;
118 read_with_control_data_free (ReadWithControlData *data)
120 g_slice_free (ReadWithControlData, data);
124 _g_socket_read_with_control_messages_ready (GSocket *socket,
125 GIOCondition condition,
128 GTask *task = user_data;
129 ReadWithControlData *data = g_task_get_task_data (task);
135 vector.buffer = data->buffer;
136 vector.size = data->count;
137 result = g_socket_receive_message (socket,
144 g_task_get_cancellable (task),
147 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
149 g_error_free (error);
153 g_assert (result >= 0 || error != NULL);
155 g_task_return_int (task, result);
157 g_task_return_error (task, error);
158 g_object_unref (task);
164 _g_socket_read_with_control_messages (GSocket *socket,
167 GSocketControlMessage ***messages,
170 GCancellable *cancellable,
171 GAsyncReadyCallback callback,
175 ReadWithControlData *data;
178 data = g_slice_new0 (ReadWithControlData);
179 data->buffer = buffer;
181 data->messages = messages;
182 data->num_messages = num_messages;
184 task = g_task_new (socket, cancellable, callback, user_data);
185 g_task_set_source_tag (task, _g_socket_read_with_control_messages);
186 g_task_set_name (task, "[gio] D-Bus read");
187 g_task_set_task_data (task, data, (GDestroyNotify) read_with_control_data_free);
189 if (g_socket_condition_check (socket, G_IO_IN))
191 if (!_g_socket_read_with_control_messages_ready (socket, G_IO_IN, task))
195 source = g_socket_create_source (socket,
196 G_IO_IN | G_IO_HUP | G_IO_ERR,
198 g_task_attach_source (task, source, (GSourceFunc) _g_socket_read_with_control_messages_ready);
199 g_source_unref (source);
203 _g_socket_read_with_control_messages_finish (GSocket *socket,
204 GAsyncResult *result,
207 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
208 g_return_val_if_fail (g_task_is_valid (result, socket), -1);
210 return g_task_propagate_int (G_TASK (result), error);
213 /* ---------------------------------------------------------------------------------------------------- */
215 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=674885
216 and see also the original https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
218 static GPtrArray *ensured_classes = NULL;
221 ensure_type (GType gtype)
223 g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
227 release_required_types (void)
229 g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
230 g_ptr_array_unref (ensured_classes);
231 ensured_classes = NULL;
235 ensure_required_types (void)
237 g_assert (ensured_classes == NULL);
238 ensured_classes = g_ptr_array_new ();
239 /* Generally in this list, you should initialize types which are used as
240 * properties first, then the class which has them. For example, GDBusProxy
241 * has a type of GDBusConnection, so we initialize GDBusConnection first.
242 * And because GDBusConnection has a property of type GDBusConnectionFlags,
243 * we initialize that first.
245 * Similarly, GSocket has a type of GSocketAddress.
247 * We don't fill out the whole dependency tree right now because in practice
248 * it tends to be just types that GDBus use that cause pain, and there
249 * is work on a more general approach in https://bugzilla.gnome.org/show_bug.cgi?id=674885
251 ensure_type (G_TYPE_TASK);
252 ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
253 ensure_type (G_TYPE_DBUS_CONNECTION_FLAGS);
254 ensure_type (G_TYPE_DBUS_CAPABILITY_FLAGS);
255 ensure_type (G_TYPE_DBUS_AUTH_OBSERVER);
256 ensure_type (G_TYPE_DBUS_CONNECTION);
257 ensure_type (G_TYPE_DBUS_PROXY);
258 ensure_type (G_TYPE_SOCKET_FAMILY);
259 ensure_type (G_TYPE_SOCKET_TYPE);
260 ensure_type (G_TYPE_SOCKET_PROTOCOL);
261 ensure_type (G_TYPE_SOCKET_ADDRESS);
262 ensure_type (G_TYPE_SOCKET);
264 /* ---------------------------------------------------------------------------------------------------- */
268 volatile gint refcount;
270 GMainContext *context;
275 gdbus_shared_thread_func (gpointer user_data)
277 SharedThreadData *data = user_data;
279 g_main_context_push_thread_default (data->context);
280 g_main_loop_run (data->loop);
281 g_main_context_pop_thread_default (data->context);
283 release_required_types ();
288 /* ---------------------------------------------------------------------------------------------------- */
290 static SharedThreadData *
291 _g_dbus_shared_thread_ref (void)
293 static gsize shared_thread_data = 0;
294 SharedThreadData *ret;
296 if (g_once_init_enter (&shared_thread_data))
298 SharedThreadData *data;
300 data = g_new0 (SharedThreadData, 1);
303 data->context = g_main_context_new ();
304 data->loop = g_main_loop_new (data->context, FALSE);
305 data->thread = g_thread_new ("gdbus",
306 gdbus_shared_thread_func,
308 /* We can cast between gsize and gpointer safely */
309 g_once_init_leave (&shared_thread_data, (gsize) data);
312 ret = (SharedThreadData*) shared_thread_data;
313 g_atomic_int_inc (&ret->refcount);
318 _g_dbus_shared_thread_unref (SharedThreadData *data)
320 /* TODO: actually destroy the shared thread here */
322 g_assert (data != NULL);
323 if (g_atomic_int_dec_and_test (&data->refcount))
325 g_main_loop_quit (data->loop);
326 //g_thread_join (data->thread);
327 g_main_loop_unref (data->loop);
328 g_main_context_unref (data->context);
333 /* ---------------------------------------------------------------------------------------------------- */
344 volatile gint ref_count;
346 SharedThreadData *shared_thread_data;
348 /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
349 volatile gint stopped;
351 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
352 * only affects messages received from the other peer (since GDBusServer is the
353 * only user) - we might want it to affect messages sent to the other peer too?
356 GDBusCapabilityFlags capabilities;
357 GQueue *received_messages_while_frozen;
360 GCancellable *cancellable;
361 GDBusWorkerMessageReceivedCallback message_received_callback;
362 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
363 GDBusWorkerDisconnectedCallback disconnected_callback;
366 /* if not NULL, stream is GSocketConnection */
369 /* used for reading */
372 gsize read_buffer_allocated_size;
373 gsize read_buffer_cur_size;
374 gsize read_buffer_bytes_wanted;
375 GUnixFDList *read_fd_list;
376 GSocketControlMessage **read_ancillary_messages;
377 gint read_num_ancillary_messages;
379 /* Whether an async write, flush or close, or none of those, is pending.
380 * Only the worker thread may change its value, and only with the write_lock.
381 * Other threads may read its value when holding the write_lock.
382 * The worker thread may read its value at any time.
384 OutputPending output_pending;
385 /* used for writing */
387 /* queue of MessageToWriteData, protected by write_lock */
389 /* protected by write_lock */
390 guint64 write_num_messages_written;
391 /* number of messages we'd written out last time we flushed;
392 * protected by write_lock
394 guint64 write_num_messages_flushed;
395 /* list of FlushData, protected by write_lock */
396 GList *write_pending_flushes;
397 /* list of CloseData, protected by write_lock */
398 GList *pending_close_attempts;
399 /* no lock - only used from the worker thread */
400 gboolean close_expected;
403 static void _g_dbus_worker_unref (GDBusWorker *worker);
405 /* ---------------------------------------------------------------------------------------------------- */
411 guint64 number_to_wait_for;
416 struct _MessageToWriteData ;
417 typedef struct _MessageToWriteData MessageToWriteData;
419 static void message_to_write_data_free (MessageToWriteData *data);
421 static void read_message_print_transport_debug (gssize bytes_read,
422 GDBusWorker *worker);
424 static void write_message_print_transport_debug (gssize bytes_written,
425 MessageToWriteData *data);
432 static void close_data_free (CloseData *close_data)
434 g_clear_object (&close_data->task);
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, g_steal_pointer (&message), worker->user_data);
499 ret = g_steal_pointer (&message);
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, g_steal_pointer (&message));
515 /* not frozen, nor anything in queue */
516 _g_dbus_worker_emit_message_received (worker, message);
517 g_clear_object (&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_clear_object (&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_set_name (idle_source, "[gio] unfreeze_in_idle_cb");
558 g_source_attach (idle_source, worker->shared_thread_data->context);
559 g_source_unref (idle_source);
562 /* ---------------------------------------------------------------------------------------------------- */
564 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
566 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
568 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
572 GDBusWorker *worker = user_data;
576 g_mutex_lock (&worker->read_lock);
578 /* If already stopped, don't even process the reply */
579 if (g_atomic_int_get (&worker->stopped))
583 if (worker->socket == NULL)
584 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
588 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
591 if (worker->read_num_ancillary_messages > 0)
594 for (n = 0; n < worker->read_num_ancillary_messages; n++)
596 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
602 else if (G_IS_UNIX_FD_MESSAGE (control_message))
604 GUnixFDMessage *fd_message;
608 fd_message = G_UNIX_FD_MESSAGE (control_message);
609 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
610 if (worker->read_fd_list == NULL)
612 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
617 for (n = 0; n < num_fds; n++)
619 /* TODO: really want a append_steal() */
620 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
621 (void) g_close (fds[n], NULL);
626 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
638 "Unexpected ancillary message of type %s received from peer",
639 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
640 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
641 g_error_free (error);
642 g_object_unref (control_message);
644 while (n < worker->read_num_ancillary_messages)
645 g_object_unref (worker->read_ancillary_messages[n++]);
646 g_free (worker->read_ancillary_messages);
650 g_object_unref (control_message);
652 g_free (worker->read_ancillary_messages);
655 if (bytes_read == -1)
657 if (G_UNLIKELY (_g_dbus_debug_transport ()))
659 _g_dbus_debug_print_lock ();
660 g_print ("========================================================================\n"
661 "GDBus-debug:Transport:\n"
662 " ---- READ ERROR on stream of type %s:\n"
664 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))),
665 g_quark_to_string (error->domain), error->code,
667 _g_dbus_debug_print_unlock ();
670 /* Every async read that uses this callback uses worker->cancellable
671 * as its GCancellable. worker->cancellable gets cancelled if and only
672 * if the GDBusConnection tells us to close (either via
673 * _g_dbus_worker_stop, which is called on last-unref, or directly),
674 * so a cancelled read must mean our connection was closed locally.
676 * If we're closing, other errors are possible - notably,
677 * G_IO_ERROR_CLOSED can be seen if we close the stream with an async
678 * read in-flight. It seems sensible to treat all read errors during
679 * closing as an expected thing that doesn't trip exit-on-close.
681 * Because close_expected can't be set until we get into the worker
682 * thread, but the cancellable is signalled sooner (from another
683 * thread), we do still need to check the error.
685 if (worker->close_expected ||
686 g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
687 _g_dbus_worker_emit_disconnected (worker, FALSE, NULL);
689 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
691 g_error_free (error);
696 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
698 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
699 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
700 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
701 G_IO_IN | G_IO_OUT | G_IO_HUP),
706 /* The read failed, which could mean the dbus-daemon was sent SIGTERM. */
712 "Underlying GIOStream returned 0 bytes on an async read");
713 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
714 g_error_free (error);
718 read_message_print_transport_debug (bytes_read, worker);
720 worker->read_buffer_cur_size += bytes_read;
721 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
723 /* OK, got what we asked for! */
724 if (worker->read_buffer_bytes_wanted == 16)
727 /* OK, got the header - determine how many more bytes are needed */
729 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
732 if (message_len == -1)
734 g_warning ("_g_dbus_worker_do_read_cb: error determining bytes needed: %s", error->message);
735 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
736 g_error_free (error);
740 worker->read_buffer_bytes_wanted = message_len;
741 _g_dbus_worker_do_read_unlocked (worker);
745 GDBusMessage *message;
748 /* TODO: use connection->priv->auth to decode the message */
750 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
751 worker->read_buffer_cur_size,
752 worker->capabilities,
757 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
758 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
760 "The payload is as follows:\n"
762 worker->read_buffer_cur_size,
766 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
767 g_error_free (error);
772 if (worker->read_fd_list != NULL)
774 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
775 g_object_unref (worker->read_fd_list);
776 worker->read_fd_list = NULL;
780 if (G_UNLIKELY (_g_dbus_debug_message ()))
783 _g_dbus_debug_print_lock ();
784 g_print ("========================================================================\n"
785 "GDBus-debug:Message:\n"
786 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
787 worker->read_buffer_cur_size);
788 s = g_dbus_message_print (message, 2);
791 if (G_UNLIKELY (_g_dbus_debug_payload ()))
793 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
797 _g_dbus_debug_print_unlock ();
800 /* yay, got a message, go deliver it */
801 _g_dbus_worker_queue_or_deliver_received_message (worker, g_steal_pointer (&message));
803 /* start reading another message! */
804 worker->read_buffer_bytes_wanted = 0;
805 worker->read_buffer_cur_size = 0;
806 _g_dbus_worker_do_read_unlocked (worker);
811 /* didn't get all the bytes we requested - so repeat the request... */
812 _g_dbus_worker_do_read_unlocked (worker);
816 g_mutex_unlock (&worker->read_lock);
818 /* check if there is any pending close */
819 schedule_pending_close (worker);
821 /* gives up the reference acquired when calling g_input_stream_read_async() */
822 _g_dbus_worker_unref (worker);
825 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
827 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
829 /* Note that we do need to keep trying to read even if close_expected is
830 * true, because only failing a read causes us to signal 'closed'.
833 /* if bytes_wanted is zero, it means start reading a message */
834 if (worker->read_buffer_bytes_wanted == 0)
836 worker->read_buffer_cur_size = 0;
837 worker->read_buffer_bytes_wanted = 16;
840 /* ensure we have a (big enough) buffer */
841 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
843 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
844 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
845 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
848 if (worker->socket == NULL)
849 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
850 worker->read_buffer + worker->read_buffer_cur_size,
851 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
854 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
855 _g_dbus_worker_ref (worker));
858 worker->read_ancillary_messages = NULL;
859 worker->read_num_ancillary_messages = 0;
860 _g_socket_read_with_control_messages (worker->socket,
861 worker->read_buffer + worker->read_buffer_cur_size,
862 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
863 &worker->read_ancillary_messages,
864 &worker->read_num_ancillary_messages,
867 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
868 _g_dbus_worker_ref (worker));
872 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
874 _g_dbus_worker_do_initial_read (gpointer data)
876 GDBusWorker *worker = data;
877 g_mutex_lock (&worker->read_lock);
878 _g_dbus_worker_do_read_unlocked (worker);
879 g_mutex_unlock (&worker->read_lock);
883 /* ---------------------------------------------------------------------------------------------------- */
885 struct _MessageToWriteData
888 GDBusMessage *message;
897 message_to_write_data_free (MessageToWriteData *data)
899 _g_dbus_worker_unref (data->worker);
901 g_object_unref (data->message);
903 g_slice_free (MessageToWriteData, data);
906 /* ---------------------------------------------------------------------------------------------------- */
908 static void write_message_continue_writing (MessageToWriteData *data);
910 /* called in private thread shared by all GDBusConnection instances
912 * write-lock is not held on entry
913 * output_pending is PENDING_WRITE on entry
916 write_message_async_cb (GObject *source_object,
920 MessageToWriteData *data = user_data;
922 gssize bytes_written;
925 /* Note: we can't access data->task after calling g_task_return_* () because the
926 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
931 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
934 if (bytes_written == -1)
936 g_task_return_error (task, error);
937 g_object_unref (task);
940 g_assert (bytes_written > 0); /* zero is never returned */
942 write_message_print_transport_debug (bytes_written, data);
944 data->total_written += bytes_written;
945 g_assert (data->total_written <= data->blob_size);
946 if (data->total_written == data->blob_size)
948 g_task_return_boolean (task, TRUE);
949 g_object_unref (task);
953 write_message_continue_writing (data);
959 /* called in private thread shared by all GDBusConnection instances
961 * write-lock is not held on entry
962 * output_pending is PENDING_WRITE on entry
966 on_socket_ready (GSocket *socket,
967 GIOCondition condition,
970 MessageToWriteData *data = user_data;
971 write_message_continue_writing (data);
972 return FALSE; /* remove source */
976 /* called in private thread shared by all GDBusConnection instances
978 * write-lock is not held on entry
979 * output_pending is PENDING_WRITE on entry
982 write_message_continue_writing (MessageToWriteData *data)
984 GOutputStream *ostream;
987 GUnixFDList *fd_list;
991 /* Note: we can't access data->task after calling g_task_return_* () because the
992 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
997 ostream = g_io_stream_get_output_stream (data->worker->stream);
999 fd_list = g_dbus_message_get_unix_fd_list (data->message);
1002 g_assert (!g_output_stream_has_pending (ostream));
1003 g_assert_cmpint (data->total_written, <, data->blob_size);
1009 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
1011 GOutputVector vector;
1012 GSocketControlMessage *control_message;
1013 gssize bytes_written;
1016 vector.buffer = data->blob;
1017 vector.size = data->blob_size;
1019 control_message = NULL;
1020 if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
1022 if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
1024 g_task_return_new_error (task,
1027 "Tried sending a file descriptor but remote peer does not support this capability");
1028 g_object_unref (task);
1031 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1035 bytes_written = g_socket_send_message (data->worker->socket,
1039 control_message != NULL ? &control_message : NULL,
1040 control_message != NULL ? 1 : 0,
1042 data->worker->cancellable,
1044 if (control_message != NULL)
1045 g_object_unref (control_message);
1047 if (bytes_written == -1)
1049 /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1050 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1053 source = g_socket_create_source (data->worker->socket,
1054 G_IO_OUT | G_IO_HUP | G_IO_ERR,
1055 data->worker->cancellable);
1056 g_source_set_callback (source,
1057 (GSourceFunc) on_socket_ready,
1059 NULL); /* GDestroyNotify */
1060 g_source_attach (source, g_main_context_get_thread_default ());
1061 g_source_unref (source);
1062 g_error_free (error);
1065 g_task_return_error (task, error);
1066 g_object_unref (task);
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_task_return_boolean (task, TRUE);
1078 g_object_unref (task);
1082 write_message_continue_writing (data);
1088 if (data->total_written == 0 && fd_list != NULL)
1090 /* We were trying to write byte 0 of the message, which needs
1091 * the fd list to be attached to it, but this connection doesn't
1092 * support doing that. */
1093 g_task_return_new_error (task,
1096 "Tried sending a file descriptor on unsupported stream of type %s",
1097 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1098 g_object_unref (task);
1103 g_output_stream_write_async (ostream,
1104 (const gchar *) data->blob + data->total_written,
1105 data->blob_size - data->total_written,
1107 data->worker->cancellable,
1108 write_message_async_cb,
1117 /* called in private thread shared by all GDBusConnection instances
1119 * write-lock is not held on entry
1120 * output_pending is PENDING_WRITE on entry
1123 write_message_async (GDBusWorker *worker,
1124 MessageToWriteData *data,
1125 GAsyncReadyCallback callback,
1128 data->task = g_task_new (NULL, NULL, callback, user_data);
1129 g_task_set_source_tag (data->task, write_message_async);
1130 g_task_set_name (data->task, "[gio] D-Bus write message");
1131 data->total_written = 0;
1132 write_message_continue_writing (data);
1135 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1137 write_message_finish (GAsyncResult *res,
1140 g_return_val_if_fail (g_task_is_valid (res, NULL), FALSE);
1142 return g_task_propagate_boolean (G_TASK (res), error);
1144 /* ---------------------------------------------------------------------------------------------------- */
1146 static void continue_writing (GDBusWorker *worker);
1150 GDBusWorker *worker;
1155 flush_data_list_complete (const GList *flushers,
1156 const GError *error)
1160 for (l = flushers; l != NULL; l = l->next)
1162 FlushData *f = l->data;
1164 f->error = error != NULL ? g_error_copy (error) : NULL;
1166 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 /* Make sure we tell folks that we don't have additional
1206 g_mutex_lock (&data->worker->write_lock);
1207 data->worker->write_num_messages_flushed = data->worker->write_num_messages_written;
1208 g_assert (data->worker->output_pending == PENDING_FLUSH);
1209 data->worker->output_pending = PENDING_NONE;
1210 g_mutex_unlock (&data->worker->write_lock);
1212 g_assert (data->flushers != NULL);
1213 flush_data_list_complete (data->flushers, error);
1214 g_list_free (data->flushers);
1216 g_error_free (error);
1218 /* OK, cool, finally kick off the next write */
1219 continue_writing (data->worker);
1221 _g_dbus_worker_unref (data->worker);
1225 /* called in private thread shared by all GDBusConnection instances
1227 * write-lock is not held on entry
1228 * output_pending is PENDING_FLUSH on entry
1231 start_flush (FlushAsyncData *data)
1233 g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1235 data->worker->cancellable,
1240 /* called in private thread shared by all GDBusConnection instances
1242 * write-lock is held on entry
1243 * output_pending is PENDING_NONE on entry
1246 message_written_unlocked (GDBusWorker *worker,
1247 MessageToWriteData *message_data)
1249 if (G_UNLIKELY (_g_dbus_debug_message ()))
1252 _g_dbus_debug_print_lock ();
1253 g_print ("========================================================================\n"
1254 "GDBus-debug:Message:\n"
1255 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1256 message_data->blob_size);
1257 s = g_dbus_message_print (message_data->message, 2);
1260 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1262 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1263 g_print ("%s\n", s);
1266 _g_dbus_debug_print_unlock ();
1269 worker->write_num_messages_written += 1;
1272 /* called in private thread shared by all GDBusConnection instances
1274 * write-lock is held on entry
1275 * output_pending is PENDING_NONE on entry
1277 * Returns: non-%NULL, setting @output_pending, if we need to flush now
1279 static FlushAsyncData *
1280 prepare_flush_unlocked (GDBusWorker *worker)
1287 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1289 FlushData *f = l->data;
1292 if (f->number_to_wait_for == worker->write_num_messages_written)
1294 flushers = g_list_append (flushers, f);
1295 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1298 if (flushers != NULL)
1300 g_assert (worker->output_pending == PENDING_NONE);
1301 worker->output_pending = PENDING_FLUSH;
1304 if (flushers != NULL)
1306 FlushAsyncData *data;
1308 data = g_new0 (FlushAsyncData, 1);
1309 data->worker = _g_dbus_worker_ref (worker);
1310 data->flushers = flushers;
1317 /* called in private thread shared by all GDBusConnection instances
1319 * write-lock is not held on entry
1320 * output_pending is PENDING_WRITE on entry
1323 write_message_cb (GObject *source_object,
1327 MessageToWriteData *data = user_data;
1330 g_mutex_lock (&data->worker->write_lock);
1331 g_assert (data->worker->output_pending == PENDING_WRITE);
1332 data->worker->output_pending = PENDING_NONE;
1335 if (!write_message_finish (res, &error))
1337 g_mutex_unlock (&data->worker->write_lock);
1340 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1341 g_error_free (error);
1343 g_mutex_lock (&data->worker->write_lock);
1346 message_written_unlocked (data->worker, data);
1348 g_mutex_unlock (&data->worker->write_lock);
1350 continue_writing (data->worker);
1352 message_to_write_data_free (data);
1355 /* called in private thread shared by all GDBusConnection instances
1357 * write-lock is not held on entry
1358 * output_pending is PENDING_CLOSE on entry
1361 iostream_close_cb (GObject *source_object,
1365 GDBusWorker *worker = user_data;
1366 GError *error = NULL;
1367 GList *pending_close_attempts, *pending_flush_attempts;
1370 g_io_stream_close_finish (worker->stream, res, &error);
1372 g_mutex_lock (&worker->write_lock);
1374 pending_close_attempts = worker->pending_close_attempts;
1375 worker->pending_close_attempts = NULL;
1377 pending_flush_attempts = worker->write_pending_flushes;
1378 worker->write_pending_flushes = NULL;
1380 send_queue = worker->write_queue;
1381 worker->write_queue = g_queue_new ();
1383 g_assert (worker->output_pending == PENDING_CLOSE);
1384 worker->output_pending = PENDING_NONE;
1386 /* Ensure threads waiting for pending flushes to finish will be unblocked. */
1387 worker->write_num_messages_flushed =
1388 worker->write_num_messages_written + g_list_length(pending_flush_attempts);
1390 g_mutex_unlock (&worker->write_lock);
1392 while (pending_close_attempts != NULL)
1394 CloseData *close_data = pending_close_attempts->data;
1396 pending_close_attempts = g_list_delete_link (pending_close_attempts,
1397 pending_close_attempts);
1399 if (close_data->task != NULL)
1402 g_task_return_error (close_data->task, g_error_copy (error));
1404 g_task_return_boolean (close_data->task, TRUE);
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 GInputStream *input = g_io_stream_get_input_stream (worker->stream);
1449 if (!g_input_stream_has_pending (input))
1451 worker->close_expected = TRUE;
1452 worker->output_pending = PENDING_CLOSE;
1454 g_io_stream_close_async (worker->stream, G_PRIORITY_DEFAULT,
1455 NULL, iostream_close_cb,
1456 _g_dbus_worker_ref (worker));
1461 flush_async_data = prepare_flush_unlocked (worker);
1463 if (flush_async_data == NULL)
1465 data = g_queue_pop_head (worker->write_queue);
1468 worker->output_pending = PENDING_WRITE;
1472 g_mutex_unlock (&worker->write_lock);
1474 /* Note that write_lock is only used for protecting the @write_queue
1475 * and @output_pending fields of the GDBusWorker struct ... which we
1476 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1478 * Therefore, it's fine to drop it here when calling back into user
1479 * code and then writing the message out onto the GIOStream since this
1480 * function only runs on the worker thread.
1483 if (flush_async_data != NULL)
1485 start_flush (flush_async_data);
1486 g_assert (data == NULL);
1488 else if (data != NULL)
1490 GDBusMessage *old_message;
1492 gsize new_blob_size;
1495 old_message = data->message;
1496 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1497 if (data->message == old_message)
1499 /* filters had no effect - do nothing */
1501 else if (data->message == NULL)
1503 /* filters dropped message */
1504 g_mutex_lock (&worker->write_lock);
1505 worker->output_pending = PENDING_NONE;
1506 g_mutex_unlock (&worker->write_lock);
1507 message_to_write_data_free (data);
1512 /* filters altered the message -> re-encode */
1514 new_blob = g_dbus_message_to_blob (data->message,
1516 worker->capabilities,
1518 if (new_blob == NULL)
1520 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1521 * the old message instead
1523 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1524 g_dbus_message_get_serial (data->message),
1526 g_error_free (error);
1530 g_free (data->blob);
1531 data->blob = (gchar *) new_blob;
1532 data->blob_size = new_blob_size;
1536 write_message_async (worker,
1543 /* called in private thread shared by all GDBusConnection instances
1545 * write-lock is not held on entry
1546 * output_pending may be anything
1549 continue_writing_in_idle_cb (gpointer user_data)
1551 GDBusWorker *worker = user_data;
1553 /* Because this is the worker thread, we can read this struct member
1554 * without holding the lock: no other thread ever modifies it.
1556 if (worker->output_pending == PENDING_NONE)
1557 continue_writing (worker);
1563 * @write_data: (transfer full) (nullable):
1564 * @flush_data: (transfer full) (nullable):
1565 * @close_data: (transfer full) (nullable):
1567 * Can be called from any thread
1569 * write_lock is held on entry
1570 * output_pending may be anything
1573 schedule_writing_unlocked (GDBusWorker *worker,
1574 MessageToWriteData *write_data,
1575 FlushData *flush_data,
1576 CloseData *close_data)
1578 if (write_data != NULL)
1579 g_queue_push_tail (worker->write_queue, write_data);
1581 if (flush_data != NULL)
1582 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, flush_data);
1584 if (close_data != NULL)
1585 worker->pending_close_attempts = g_list_prepend (worker->pending_close_attempts,
1588 /* If we had output pending, the next bit of output will happen
1589 * automatically when it finishes, so we only need to do this
1590 * if nothing was pending.
1592 * The idle callback will re-check that output_pending is still
1593 * PENDING_NONE, to guard against output starting before the idle.
1595 if (worker->output_pending == PENDING_NONE)
1597 GSource *idle_source;
1598 idle_source = g_idle_source_new ();
1599 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1600 g_source_set_callback (idle_source,
1601 continue_writing_in_idle_cb,
1602 _g_dbus_worker_ref (worker),
1603 (GDestroyNotify) _g_dbus_worker_unref);
1604 g_source_set_name (idle_source, "[gio] continue_writing_in_idle_cb");
1605 g_source_attach (idle_source, worker->shared_thread_data->context);
1606 g_source_unref (idle_source);
1611 schedule_pending_close (GDBusWorker *worker)
1613 g_mutex_lock (&worker->write_lock);
1614 if (worker->pending_close_attempts)
1615 schedule_writing_unlocked (worker, NULL, NULL, NULL);
1616 g_mutex_unlock (&worker->write_lock);
1619 /* ---------------------------------------------------------------------------------------------------- */
1621 /* can be called from any thread - steals blob
1623 * write_lock is not held on entry
1624 * output_pending may be anything
1627 _g_dbus_worker_send_message (GDBusWorker *worker,
1628 GDBusMessage *message,
1632 MessageToWriteData *data;
1634 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1635 g_return_if_fail (blob != NULL);
1636 g_return_if_fail (blob_len > 16);
1638 data = g_slice_new0 (MessageToWriteData);
1639 data->worker = _g_dbus_worker_ref (worker);
1640 data->message = g_object_ref (message);
1641 data->blob = blob; /* steal! */
1642 data->blob_size = blob_len;
1644 g_mutex_lock (&worker->write_lock);
1645 schedule_writing_unlocked (worker, data, NULL, NULL);
1646 g_mutex_unlock (&worker->write_lock);
1649 /* ---------------------------------------------------------------------------------------------------- */
1652 _g_dbus_worker_new (GIOStream *stream,
1653 GDBusCapabilityFlags capabilities,
1654 gboolean initially_frozen,
1655 GDBusWorkerMessageReceivedCallback message_received_callback,
1656 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1657 GDBusWorkerDisconnectedCallback disconnected_callback,
1660 GDBusWorker *worker;
1661 GSource *idle_source;
1663 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1664 g_return_val_if_fail (message_received_callback != NULL, NULL);
1665 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1666 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1668 worker = g_new0 (GDBusWorker, 1);
1669 worker->ref_count = 1;
1671 g_mutex_init (&worker->read_lock);
1672 worker->message_received_callback = message_received_callback;
1673 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1674 worker->disconnected_callback = disconnected_callback;
1675 worker->user_data = user_data;
1676 worker->stream = g_object_ref (stream);
1677 worker->capabilities = capabilities;
1678 worker->cancellable = g_cancellable_new ();
1679 worker->output_pending = PENDING_NONE;
1681 worker->frozen = initially_frozen;
1682 worker->received_messages_while_frozen = g_queue_new ();
1684 g_mutex_init (&worker->write_lock);
1685 worker->write_queue = g_queue_new ();
1687 if (G_IS_SOCKET_CONNECTION (worker->stream))
1688 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1690 worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1693 idle_source = g_idle_source_new ();
1694 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1695 g_source_set_callback (idle_source,
1696 _g_dbus_worker_do_initial_read,
1697 _g_dbus_worker_ref (worker),
1698 (GDestroyNotify) _g_dbus_worker_unref);
1699 g_source_set_name (idle_source, "[gio] _g_dbus_worker_do_initial_read");
1700 g_source_attach (idle_source, worker->shared_thread_data->context);
1701 g_source_unref (idle_source);
1706 /* ---------------------------------------------------------------------------------------------------- */
1708 /* can be called from any thread
1710 * write_lock is not held on entry
1711 * output_pending may be anything
1714 _g_dbus_worker_close (GDBusWorker *worker,
1717 CloseData *close_data;
1719 close_data = g_slice_new0 (CloseData);
1720 close_data->worker = _g_dbus_worker_ref (worker);
1721 close_data->task = (task == NULL ? NULL : g_object_ref (task));
1723 /* Don't set worker->close_expected here - we're in the wrong thread.
1724 * It'll be set before the actual close happens.
1726 g_cancellable_cancel (worker->cancellable);
1727 g_mutex_lock (&worker->write_lock);
1728 schedule_writing_unlocked (worker, NULL, NULL, close_data);
1729 g_mutex_unlock (&worker->write_lock);
1732 /* This can be called from any thread - frees worker. Note that
1733 * callbacks might still happen if called from another thread than the
1734 * worker - use your own synchronization primitive in the callbacks.
1736 * write_lock is not held on entry
1737 * output_pending may be anything
1740 _g_dbus_worker_stop (GDBusWorker *worker)
1742 g_atomic_int_set (&worker->stopped, TRUE);
1744 /* Cancel any pending operations and schedule a close of the underlying I/O
1745 * stream in the worker thread
1747 _g_dbus_worker_close (worker, NULL);
1749 /* _g_dbus_worker_close holds a ref until after an idle in the worker
1750 * thread has run, so we no longer need to unref in an idle like in
1753 _g_dbus_worker_unref (worker);
1756 /* ---------------------------------------------------------------------------------------------------- */
1758 /* can be called from any thread (except the worker thread) - blocks
1759 * calling thread until all queued outgoing messages are written and
1760 * the transport has been flushed
1762 * write_lock is not held on entry
1763 * output_pending may be anything
1766 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1767 GCancellable *cancellable,
1772 guint64 pending_writes;
1777 g_mutex_lock (&worker->write_lock);
1779 /* if the queue is empty, no write is in-flight and we haven't written
1780 * anything since the last flush, then there's nothing to wait for
1782 pending_writes = g_queue_get_length (worker->write_queue);
1784 /* if a write is in-flight, we shouldn't be satisfied until the first
1785 * flush operation that follows it
1787 if (worker->output_pending == PENDING_WRITE)
1788 pending_writes += 1;
1790 if (pending_writes > 0 ||
1791 worker->write_num_messages_written != worker->write_num_messages_flushed)
1793 data = g_new0 (FlushData, 1);
1794 g_mutex_init (&data->mutex);
1795 g_cond_init (&data->cond);
1796 data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
1797 data->finished = FALSE;
1798 g_mutex_lock (&data->mutex);
1800 schedule_writing_unlocked (worker, NULL, data, NULL);
1802 g_mutex_unlock (&worker->write_lock);
1806 /* Wait for flush operations to finish. */
1807 while (!data->finished)
1809 g_cond_wait (&data->cond, &data->mutex);
1812 g_mutex_unlock (&data->mutex);
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)
1838 #define G_DBUS_DEBUG_PROXY (1<<10)
1840 static gint _gdbus_debug_flags = 0;
1843 _g_dbus_debug_authentication (void)
1845 _g_dbus_initialize ();
1846 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1850 _g_dbus_debug_transport (void)
1852 _g_dbus_initialize ();
1853 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1857 _g_dbus_debug_message (void)
1859 _g_dbus_initialize ();
1860 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1864 _g_dbus_debug_payload (void)
1866 _g_dbus_initialize ();
1867 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1871 _g_dbus_debug_call (void)
1873 _g_dbus_initialize ();
1874 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1878 _g_dbus_debug_signal (void)
1880 _g_dbus_initialize ();
1881 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1885 _g_dbus_debug_incoming (void)
1887 _g_dbus_initialize ();
1888 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1892 _g_dbus_debug_return (void)
1894 _g_dbus_initialize ();
1895 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1899 _g_dbus_debug_emission (void)
1901 _g_dbus_initialize ();
1902 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1906 _g_dbus_debug_address (void)
1908 _g_dbus_initialize ();
1909 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1913 _g_dbus_debug_proxy (void)
1915 _g_dbus_initialize ();
1916 return (_gdbus_debug_flags & G_DBUS_DEBUG_PROXY) != 0;
1919 G_LOCK_DEFINE_STATIC (print_lock);
1922 _g_dbus_debug_print_lock (void)
1924 G_LOCK (print_lock);
1928 _g_dbus_debug_print_unlock (void)
1930 G_UNLOCK (print_lock);
1934 * _g_dbus_initialize:
1936 * Does various one-time init things such as
1938 * - registering the G_DBUS_ERROR error domain
1939 * - parses the G_DBUS_DEBUG environment variable
1942 _g_dbus_initialize (void)
1944 static volatile gsize initialized = 0;
1946 if (g_once_init_enter (&initialized))
1948 volatile GQuark g_dbus_error_domain;
1951 g_dbus_error_domain = G_DBUS_ERROR;
1952 (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
1954 debug = g_getenv ("G_DBUS_DEBUG");
1957 const GDebugKey keys[] = {
1958 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1959 { "transport", G_DBUS_DEBUG_TRANSPORT },
1960 { "message", G_DBUS_DEBUG_MESSAGE },
1961 { "payload", G_DBUS_DEBUG_PAYLOAD },
1962 { "call", G_DBUS_DEBUG_CALL },
1963 { "signal", G_DBUS_DEBUG_SIGNAL },
1964 { "incoming", G_DBUS_DEBUG_INCOMING },
1965 { "return", G_DBUS_DEBUG_RETURN },
1966 { "emission", G_DBUS_DEBUG_EMISSION },
1967 { "address", G_DBUS_DEBUG_ADDRESS },
1968 { "proxy", G_DBUS_DEBUG_PROXY }
1971 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1972 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1973 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1976 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
1977 ensure_required_types ();
1979 g_once_init_leave (&initialized, 1);
1983 /* ---------------------------------------------------------------------------------------------------- */
1986 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1988 const GVariantType *arg_types[256];
1992 for (n = 0; args[n] != NULL; n++)
1994 /* DBus places a hard limit of 255 on signature length.
1995 * therefore number of args must be less than 256.
1999 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
2001 if G_UNLIKELY (arg_types[n] == NULL)
2007 return g_variant_type_new_tuple (arg_types, n);
2010 /* ---------------------------------------------------------------------------------------------------- */
2014 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
2017 _g_dbus_win32_get_user_sid (void)
2021 DWORD token_information_len;
2028 h = INVALID_HANDLE_VALUE;
2030 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
2032 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
2036 /* Get length of buffer */
2037 token_information_len = 0;
2038 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
2040 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
2042 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2046 user = g_malloc (token_information_len);
2047 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
2049 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2053 psid = user->User.Sid;
2054 if (!IsValidSid (psid))
2056 g_warning ("Invalid SID");
2060 if (!ConvertSidToStringSidA (psid, &sid))
2062 g_warning ("Invalid SID");
2066 ret = g_strdup (sid);
2071 if (h != INVALID_HANDLE_VALUE)
2077 #define DBUS_DAEMON_ADDRESS_INFO "DBusDaemonAddressInfo"
2078 #define DBUS_DAEMON_MUTEX "DBusDaemonMutex"
2079 #define UNIQUE_DBUS_INIT_MUTEX "UniqueDBusInitMutex"
2080 #define DBUS_AUTOLAUNCH_MUTEX "DBusAutolaunchMutex"
2083 release_mutex (HANDLE mutex)
2085 ReleaseMutex (mutex);
2086 CloseHandle (mutex);
2090 acquire_mutex (const char *mutexname)
2095 mutex = CreateMutexA (NULL, FALSE, mutexname);
2099 res = WaitForSingleObject (mutex, INFINITE);
2102 case WAIT_ABANDONED:
2103 release_mutex (mutex);
2114 is_mutex_owned (const char *mutexname)
2117 gboolean res = FALSE;
2119 mutex = CreateMutexA (NULL, FALSE, mutexname);
2120 if (WaitForSingleObject (mutex, 10) == WAIT_TIMEOUT)
2123 ReleaseMutex (mutex);
2124 CloseHandle (mutex);
2130 read_shm (const char *shm_name)
2139 for (i = 0; i < 20; i++)
2141 shared_mem = OpenFileMappingA (FILE_MAP_READ, FALSE, shm_name);
2142 if (shared_mem != 0)
2147 if (shared_mem != 0)
2149 shared_data = MapViewOfFile (shared_mem, FILE_MAP_READ, 0, 0, 0);
2150 /* It looks that a race is possible here:
2151 * if the dbus process already created mapping but didn't fill it
2152 * the code below may read incorrect address.
2153 * Also this is a bit complicated by the fact that
2154 * any change in the "synchronization contract" between processes
2155 * should be accompanied with renaming all of used win32 named objects:
2156 * otherwise libgio-2.0-0.dll of different versions shipped with
2157 * different apps may break each other due to protocol difference.
2159 if (shared_data != NULL)
2161 res = g_strdup (shared_data);
2162 UnmapViewOfFile (shared_data);
2164 CloseHandle (shared_mem);
2171 set_shm (const char *shm_name, const char *value)
2176 shared_mem = CreateFileMappingA (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2177 0, strlen (value) + 1, shm_name);
2178 if (shared_mem == 0)
2181 shared_data = MapViewOfFile (shared_mem, FILE_MAP_WRITE, 0, 0, 0 );
2182 if (shared_data == NULL)
2185 strcpy (shared_data, value);
2187 UnmapViewOfFile (shared_data);
2192 /* These keep state between publish_session_bus and unpublish_session_bus */
2193 static HANDLE published_daemon_mutex;
2194 static HANDLE published_shared_mem;
2197 publish_session_bus (const char *address)
2201 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
2203 published_daemon_mutex = CreateMutexA (NULL, FALSE, DBUS_DAEMON_MUTEX);
2204 if (WaitForSingleObject (published_daemon_mutex, 10 ) != WAIT_OBJECT_0)
2206 release_mutex (init_mutex);
2207 CloseHandle (published_daemon_mutex);
2208 published_daemon_mutex = NULL;
2212 published_shared_mem = set_shm (DBUS_DAEMON_ADDRESS_INFO, address);
2213 if (!published_shared_mem)
2215 release_mutex (init_mutex);
2216 CloseHandle (published_daemon_mutex);
2217 published_daemon_mutex = NULL;
2221 release_mutex (init_mutex);
2226 unpublish_session_bus (void)
2230 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
2232 CloseHandle (published_shared_mem);
2233 published_shared_mem = NULL;
2235 release_mutex (published_daemon_mutex);
2236 published_daemon_mutex = NULL;
2238 release_mutex (init_mutex);
2242 wait_console_window (void)
2244 FILE *console = fopen ("CONOUT$", "w");
2246 SetConsoleTitleW (L"gdbus-daemon output. Type any character to close this window.");
2247 fprintf (console, _("(Type any character to close this window)\n"));
2253 open_console_window (void)
2255 if (((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE ||
2256 (HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE) && AllocConsole ())
2258 if ((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE)
2259 freopen ("CONOUT$", "w", stdout);
2261 if ((HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE)
2262 freopen ("CONOUT$", "w", stderr);
2264 SetConsoleTitleW (L"gdbus-daemon debug output.");
2266 atexit (wait_console_window);
2271 idle_timeout_cb (GDBusDaemon *daemon, gpointer user_data)
2273 GMainLoop *loop = user_data;
2274 g_main_loop_quit (loop);
2277 /* Satisfies STARTF_FORCEONFEEDBACK */
2279 turn_off_the_starting_cursor (void)
2284 PostQuitMessage (0);
2286 while ((bRet = GetMessage (&msg, 0, 0, 0)) != 0)
2291 TranslateMessage (&msg);
2292 DispatchMessage (&msg);
2296 __declspec(dllexport) void __stdcall
2297 g_win32_run_session_bus (void* hwnd, void* hinst, const char* cmdline, int cmdshow)
2299 GDBusDaemon *daemon;
2301 const char *address;
2302 GError *error = NULL;
2304 turn_off_the_starting_cursor ();
2306 if (g_getenv ("GDBUS_DAEMON_DEBUG") != NULL)
2307 open_console_window ();
2309 address = "nonce-tcp:";
2310 daemon = _g_dbus_daemon_new (address, NULL, &error);
2313 g_printerr ("Can't init bus: %s\n", error->message);
2314 g_error_free (error);
2318 loop = g_main_loop_new (NULL, FALSE);
2320 /* There is a subtle detail with "idle-timeout" signal of dbus daemon:
2321 * It is fired on idle after last client disconnection,
2322 * but (at least with glib 2.59.1) it is NEVER fired
2323 * if no clients connect to daemon at all.
2324 * This may lead to infinite run of this daemon process.
2326 g_signal_connect (daemon, "idle-timeout", G_CALLBACK (idle_timeout_cb), loop);
2328 if (publish_session_bus (_g_dbus_daemon_get_address (daemon)))
2330 g_main_loop_run (loop);
2332 unpublish_session_bus ();
2335 g_main_loop_unref (loop);
2336 g_object_unref (daemon);
2339 static gboolean autolaunch_binary_absent = FALSE;
2342 _g_dbus_win32_get_session_address_dbus_launch (GError **error)
2344 HANDLE autolaunch_mutex, init_mutex;
2345 char *address = NULL;
2347 autolaunch_mutex = acquire_mutex (DBUS_AUTOLAUNCH_MUTEX);
2349 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
2351 if (is_mutex_owned (DBUS_DAEMON_MUTEX))
2352 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
2354 release_mutex (init_mutex);
2356 if (address == NULL && !autolaunch_binary_absent)
2358 wchar_t gio_path[MAX_PATH + 2] = { 0 };
2359 int gio_path_len = GetModuleFileNameW (_g_io_win32_get_module (), gio_path, MAX_PATH + 1);
2361 /* The <= MAX_PATH check prevents truncated path usage */
2362 if (gio_path_len > 0 && gio_path_len <= MAX_PATH)
2364 PROCESS_INFORMATION pi = { 0 };
2365 STARTUPINFOW si = { 0 };
2367 wchar_t exe_path[MAX_PATH + 100] = { 0 };
2368 /* calculate index of first char of dll file name inside full path */
2369 int gio_name_index = gio_path_len;
2370 for (; gio_name_index > 0; --gio_name_index)
2372 wchar_t prev_char = gio_path[gio_name_index - 1];
2373 if (prev_char == L'\\' || prev_char == L'/')
2376 gio_path[gio_name_index] = L'\0';
2377 wcscpy (exe_path, gio_path);
2378 wcscat (exe_path, L"\\gdbus.exe");
2380 if (GetFileAttributesW (exe_path) == INVALID_FILE_ATTRIBUTES)
2382 /* warning won't be raised another time
2383 * since autolaunch_binary_absent would be already set.
2385 autolaunch_binary_absent = TRUE;
2386 g_warning ("win32 session dbus binary not found: %S", exe_path );
2390 wchar_t args[MAX_PATH*2 + 100] = { 0 };
2391 wcscpy (args, L"\"");
2392 wcscat (args, exe_path);
2393 wcscat (args, L"\" ");
2394 #define _L_PREFIX_FOR_EXPANDED(arg) L##arg
2395 #define _L_PREFIX(arg) _L_PREFIX_FOR_EXPANDED (arg)
2396 wcscat (args, _L_PREFIX (_GDBUS_ARG_WIN32_RUN_SESSION_BUS));
2398 #undef _L_PREFIX_FOR_EXPANDED
2400 res = CreateProcessW (exe_path, args,
2402 NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | DETACHED_PROCESS,
2408 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
2409 if (address == NULL)
2410 g_warning ("%S dbus binary failed to launch bus, maybe incompatible version", exe_path );
2415 release_mutex (autolaunch_mutex);
2417 if (address == NULL)
2421 _("Session dbus not running, and autolaunch failed"));
2428 /* ---------------------------------------------------------------------------------------------------- */
2431 _g_dbus_get_machine_id (GError **error)
2434 HW_PROFILE_INFOA info;
2435 char *src, *dest, *res;
2438 if (!GetCurrentHwProfileA (&info))
2440 char *message = g_win32_error_message (GetLastError ());
2444 _("Unable to get Hardware profile: %s"), message);
2449 /* Form: {12340001-4980-1920-6788-123456789012} */
2450 src = &info.szHwProfileGuid[0];
2452 res = g_malloc (32+1);
2456 for (i = 0; i < 8; i++)
2459 for (i = 0; i < 4; i++)
2462 for (i = 0; i < 4; i++)
2465 for (i = 0; i < 4; i++)
2468 for (i = 0; i < 12; i++)
2475 GError *first_error;
2476 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2479 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2483 !g_file_get_contents ("/etc/machine-id",
2488 g_propagate_prefixed_error (error, first_error,
2489 _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2493 /* ignore the error from the first try, if any */
2494 g_clear_error (&first_error);
2495 /* TODO: validate value */
2502 /* ---------------------------------------------------------------------------------------------------- */
2505 _g_dbus_enum_to_string (GType enum_type, gint value)
2509 GEnumValue *enum_value;
2511 klass = g_type_class_ref (enum_type);
2512 enum_value = g_enum_get_value (klass, value);
2513 if (enum_value != NULL)
2514 ret = g_strdup (enum_value->value_nick);
2516 ret = g_strdup_printf ("unknown (value %d)", value);
2517 g_type_class_unref (klass);
2521 /* ---------------------------------------------------------------------------------------------------- */
2524 write_message_print_transport_debug (gssize bytes_written,
2525 MessageToWriteData *data)
2527 if (G_LIKELY (!_g_dbus_debug_transport ()))
2530 _g_dbus_debug_print_lock ();
2531 g_print ("========================================================================\n"
2532 "GDBus-debug:Transport:\n"
2533 " >>>> WROTE %" G_GSSIZE_FORMAT " bytes of message with serial %d and\n"
2534 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
2536 g_dbus_message_get_serial (data->message),
2538 data->total_written,
2539 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
2540 _g_dbus_debug_print_unlock ();
2545 /* ---------------------------------------------------------------------------------------------------- */
2548 read_message_print_transport_debug (gssize bytes_read,
2549 GDBusWorker *worker)
2553 gint32 message_length;
2555 if (G_LIKELY (!_g_dbus_debug_transport ()))
2558 size = bytes_read + worker->read_buffer_cur_size;
2562 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2565 switch (worker->read_buffer[0])
2569 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2573 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2576 /* an error will be set elsewhere if this happens */
2581 _g_dbus_debug_print_lock ();
2582 g_print ("========================================================================\n"
2583 "GDBus-debug:Transport:\n"
2584 " <<<< READ %" G_GSSIZE_FORMAT " bytes of message with serial %d and\n"
2585 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
2589 worker->read_buffer_cur_size,
2590 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
2591 _g_dbus_debug_print_unlock ();
2596 /* ---------------------------------------------------------------------------------------------------- */
2599 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2600 GValue *return_accu,
2601 const GValue *handler_return,
2604 gboolean continue_emission;
2605 gboolean signal_return;
2607 signal_return = g_value_get_boolean (handler_return);
2608 g_value_set_boolean (return_accu, signal_return);
2609 continue_emission = signal_return;
2611 return continue_emission;
2614 /* ---------------------------------------------------------------------------------------------------- */
2617 append_nibble (GString *s, gint val)
2619 g_string_append_c (s, val >= 10 ? ('a' + val - 10) : ('0' + val));
2622 /* ---------------------------------------------------------------------------------------------------- */
2625 _g_dbus_hexencode (const gchar *str,
2631 s = g_string_new (NULL);
2632 for (n = 0; n < str_len; n++)
2638 val = ((const guchar *) str)[n];
2639 upper_nibble = val >> 4;
2640 lower_nibble = val & 0x0f;
2642 append_nibble (s, upper_nibble);
2643 append_nibble (s, lower_nibble);
2646 return g_string_free (s, FALSE);