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;
124 GCancellable *cancellable;
129 GSimpleAsyncResult *simple;
131 gboolean from_mainloop;
135 read_kdbus_data_free (ReadKdbusData *data)
137 //g_object_unref (data->kdbus); TODO
138 if (data->cancellable != NULL)
139 g_object_unref (data->cancellable);
140 g_object_unref (data->simple);
145 read_with_control_data_free (ReadWithControlData *data)
147 g_object_unref (data->socket);
148 if (data->cancellable != NULL)
149 g_object_unref (data->cancellable);
150 g_object_unref (data->simple);
155 _g_kdbus_read_ready (GKdbus *kdbus,
156 GIOCondition condition,
159 ReadKdbusData *data = user_data;
165 result = g_kdbus_receive (data->kdbus,
170 g_simple_async_result_set_op_res_gssize (data->simple, result);
174 g_assert (error != NULL);
175 g_simple_async_result_take_error (data->simple, error);
178 if (data->from_mainloop)
179 g_simple_async_result_complete (data->simple);
181 g_simple_async_result_complete_in_idle (data->simple);
187 _g_socket_read_with_control_messages_ready (GSocket *socket,
188 GIOCondition condition,
191 ReadWithControlData *data = user_data;
197 vector.buffer = data->buffer;
198 vector.size = data->count;
199 result = g_socket_receive_message (data->socket,
210 g_simple_async_result_set_op_res_gssize (data->simple, result);
214 g_assert (error != NULL);
215 g_simple_async_result_take_error (data->simple, error);
218 if (data->from_mainloop)
219 g_simple_async_result_complete (data->simple);
221 g_simple_async_result_complete_in_idle (data->simple);
227 _g_kdbus_read (GKdbus *kdbus,
230 GCancellable *cancellable,
231 GAsyncReadyCallback callback,
236 data = g_new0 (ReadKdbusData, 1);
237 data->kdbus = kdbus; /*g_object_ref (socket);*/
238 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
239 data->buffer = buffer;
242 data->simple = g_simple_async_result_new (G_OBJECT (kdbus),
246 g_simple_async_result_set_check_cancellable (data->simple, cancellable);
248 if (!g_kdbus_condition_check (kdbus, G_IO_IN))
251 data->from_mainloop = TRUE;
252 source = g_kdbus_create_source (data->kdbus,
253 G_IO_IN | G_IO_HUP | G_IO_ERR,
255 g_source_set_callback (source,
256 (GSourceFunc) _g_kdbus_read_ready,
258 (GDestroyNotify) read_kdbus_data_free);
259 g_source_attach (source, g_main_context_get_thread_default ());
260 g_source_unref (source);
264 _g_kdbus_read_ready (data->kdbus, G_IO_IN, data);
265 read_kdbus_data_free (data);
270 _g_socket_read_with_control_messages (GSocket *socket,
273 GSocketControlMessage ***messages,
276 GCancellable *cancellable,
277 GAsyncReadyCallback callback,
280 ReadWithControlData *data;
282 data = g_new0 (ReadWithControlData, 1);
283 data->socket = g_object_ref (socket);
284 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
285 data->buffer = buffer;
287 data->messages = messages;
288 data->num_messages = num_messages;
290 data->simple = g_simple_async_result_new (G_OBJECT (socket),
293 _g_socket_read_with_control_messages);
294 g_simple_async_result_set_check_cancellable (data->simple, cancellable);
296 if (!g_socket_condition_check (socket, G_IO_IN))
299 data->from_mainloop = TRUE;
300 source = g_socket_create_source (data->socket,
301 G_IO_IN | G_IO_HUP | G_IO_ERR,
303 g_source_set_callback (source,
304 (GSourceFunc) _g_socket_read_with_control_messages_ready,
306 (GDestroyNotify) read_with_control_data_free);
307 g_source_attach (source, g_main_context_get_thread_default ());
308 g_source_unref (source);
312 _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
313 read_with_control_data_free (data);
318 _g_kdbus_read_finish (GKdbus *kdbus,
319 GAsyncResult *result,
322 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
324 g_return_val_if_fail (G_IS_KDBUS (kdbus), -1);
325 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_kdbus_read);
327 if (g_simple_async_result_propagate_error (simple, error))
330 return g_simple_async_result_get_op_res_gssize (simple);
334 _g_socket_read_with_control_messages_finish (GSocket *socket,
335 GAsyncResult *result,
338 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
340 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
341 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
343 if (g_simple_async_result_propagate_error (simple, error))
346 return g_simple_async_result_get_op_res_gssize (simple);
349 /* ---------------------------------------------------------------------------------------------------- */
351 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
353 static GPtrArray *ensured_classes = NULL;
356 ensure_type (GType gtype)
358 g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
362 release_required_types (void)
364 g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
365 g_ptr_array_unref (ensured_classes);
366 ensured_classes = NULL;
370 ensure_required_types (void)
372 g_assert (ensured_classes == NULL);
373 ensured_classes = g_ptr_array_new ();
374 ensure_type (G_TYPE_SIMPLE_ASYNC_RESULT);
375 ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
377 /* ---------------------------------------------------------------------------------------------------- */
381 volatile gint refcount;
383 GMainContext *context;
388 gdbus_shared_thread_func (gpointer user_data)
390 SharedThreadData *data = user_data;
392 g_main_context_push_thread_default (data->context);
393 g_main_loop_run (data->loop);
394 g_main_context_pop_thread_default (data->context);
396 release_required_types ();
401 /* ---------------------------------------------------------------------------------------------------- */
403 static SharedThreadData *
404 _g_dbus_shared_thread_ref (void)
406 static gsize shared_thread_data = 0;
407 SharedThreadData *ret;
409 if (g_once_init_enter (&shared_thread_data))
411 SharedThreadData *data;
413 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
414 ensure_required_types ();
416 data = g_new0 (SharedThreadData, 1);
419 data->context = g_main_context_new ();
420 data->loop = g_main_loop_new (data->context, FALSE);
421 data->thread = g_thread_new ("gdbus",
422 gdbus_shared_thread_func,
424 /* We can cast between gsize and gpointer safely */
425 g_once_init_leave (&shared_thread_data, (gsize) data);
428 ret = (SharedThreadData*) shared_thread_data;
429 g_atomic_int_inc (&ret->refcount);
434 _g_dbus_shared_thread_unref (SharedThreadData *data)
436 /* TODO: actually destroy the shared thread here */
438 g_assert (data != NULL);
439 if (g_atomic_int_dec_and_test (&data->refcount))
441 g_main_loop_quit (data->loop);
442 //g_thread_join (data->thread);
443 g_main_loop_unref (data->loop);
444 g_main_context_unref (data->context);
449 /* ---------------------------------------------------------------------------------------------------- */
460 volatile gint ref_count;
462 SharedThreadData *shared_thread_data;
464 /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
465 volatile gint stopped;
467 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
468 * only affects messages received from the other peer (since GDBusServer is the
469 * only user) - we might want it to affect messages sent to the other peer too?
472 GDBusCapabilityFlags capabilities;
473 GQueue *received_messages_while_frozen;
476 GCancellable *cancellable;
477 GDBusWorkerMessageReceivedCallback message_received_callback;
478 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
479 GDBusWorkerDisconnectedCallback disconnected_callback;
482 /* if GSocket and GKdbus are NULL, stream is GSocketConnection */
486 /* used for reading */
489 gsize read_buffer_allocated_size;
490 gsize read_buffer_cur_size;
491 gsize read_buffer_bytes_wanted;
492 GUnixFDList *read_fd_list;
493 GSocketControlMessage **read_ancillary_messages;
494 gint read_num_ancillary_messages;
496 /* Whether an async write, flush or close, or none of those, is pending.
497 * Only the worker thread may change its value, and only with the write_lock.
498 * Other threads may read its value when holding the write_lock.
499 * The worker thread may read its value at any time.
501 OutputPending output_pending;
502 /* used for writing */
504 /* queue of MessageToWriteData, protected by write_lock */
506 /* protected by write_lock */
507 guint64 write_num_messages_written;
508 /* number of messages we'd written out last time we flushed;
509 * protected by write_lock
511 guint64 write_num_messages_flushed;
512 /* list of FlushData, protected by write_lock */
513 GList *write_pending_flushes;
514 /* list of CloseData, protected by write_lock */
515 GList *pending_close_attempts;
516 /* no lock - only used from the worker thread */
517 gboolean close_expected;
520 static void _g_dbus_worker_unref (GDBusWorker *worker);
522 /* ---------------------------------------------------------------------------------------------------- */
528 guint64 number_to_wait_for;
532 struct _MessageToWriteData ;
533 typedef struct _MessageToWriteData MessageToWriteData;
535 static void message_to_write_data_free (MessageToWriteData *data);
537 static void read_message_print_transport_debug (gssize bytes_read,
538 GDBusWorker *worker);
540 static void write_message_print_transport_debug (gssize bytes_written,
541 MessageToWriteData *data);
545 GCancellable *cancellable;
546 GSimpleAsyncResult *result;
549 static void close_data_free (CloseData *close_data)
551 if (close_data->cancellable != NULL)
552 g_object_unref (close_data->cancellable);
554 if (close_data->result != NULL)
555 g_object_unref (close_data->result);
557 _g_dbus_worker_unref (close_data->worker);
558 g_slice_free (CloseData, close_data);
561 /* ---------------------------------------------------------------------------------------------------- */
564 _g_dbus_worker_ref (GDBusWorker *worker)
566 g_atomic_int_inc (&worker->ref_count);
571 _g_dbus_worker_unref (GDBusWorker *worker)
573 if (g_atomic_int_dec_and_test (&worker->ref_count))
575 g_assert (worker->write_pending_flushes == NULL);
577 _g_dbus_shared_thread_unref (worker->shared_thread_data);
579 g_object_unref (worker->stream);
581 g_mutex_clear (&worker->read_lock);
582 g_object_unref (worker->cancellable);
583 if (worker->read_fd_list != NULL)
584 g_object_unref (worker->read_fd_list);
586 g_queue_free_full (worker->received_messages_while_frozen, (GDestroyNotify) g_object_unref);
587 g_mutex_clear (&worker->write_lock);
588 g_queue_free_full (worker->write_queue, (GDestroyNotify) message_to_write_data_free);
589 g_free (worker->read_buffer);
596 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
597 gboolean remote_peer_vanished,
600 if (!g_atomic_int_get (&worker->stopped))
601 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
605 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
606 GDBusMessage *message)
608 if (!g_atomic_int_get (&worker->stopped))
609 worker->message_received_callback (worker, message, worker->user_data);
612 static GDBusMessage *
613 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
614 GDBusMessage *message)
617 if (!g_atomic_int_get (&worker->stopped))
618 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
624 /* can only be called from private thread with read-lock held - takes ownership of @message */
626 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
627 GDBusMessage *message)
629 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
632 g_queue_push_tail (worker->received_messages_while_frozen, message);
636 /* not frozen, nor anything in queue */
637 _g_dbus_worker_emit_message_received (worker, message);
638 g_object_unref (message);
642 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
644 unfreeze_in_idle_cb (gpointer user_data)
646 GDBusWorker *worker = user_data;
647 GDBusMessage *message;
649 g_mutex_lock (&worker->read_lock);
652 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
654 _g_dbus_worker_emit_message_received (worker, message);
655 g_object_unref (message);
657 worker->frozen = FALSE;
661 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
663 g_mutex_unlock (&worker->read_lock);
667 /* can be called from any thread */
669 _g_dbus_worker_unfreeze (GDBusWorker *worker)
671 GSource *idle_source;
672 idle_source = g_idle_source_new ();
673 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
674 g_source_set_callback (idle_source,
676 _g_dbus_worker_ref (worker),
677 (GDestroyNotify) _g_dbus_worker_unref);
678 g_source_attach (idle_source, worker->shared_thread_data->context);
679 g_source_unref (idle_source);
682 /* ---------------------------------------------------------------------------------------------------- */
684 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
686 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
688 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
692 GDBusWorker *worker = user_data;
696 g_mutex_lock (&worker->read_lock);
698 /* If already stopped, don't even process the reply */
699 if (g_atomic_int_get (&worker->stopped))
703 if (G_IS_KDBUS_CONNECTION (worker->stream))
705 bytes_read = _g_kdbus_read_finish (worker->kdbus,
708 } else if (worker->socket == NULL)
709 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
713 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
716 if (worker->read_num_ancillary_messages > 0)
719 for (n = 0; n < worker->read_num_ancillary_messages; n++)
721 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
727 else if (G_IS_UNIX_FD_MESSAGE (control_message))
729 GUnixFDMessage *fd_message;
733 fd_message = G_UNIX_FD_MESSAGE (control_message);
734 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
735 if (worker->read_fd_list == NULL)
737 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
742 for (n = 0; n < num_fds; n++)
744 /* TODO: really want a append_steal() */
745 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
746 (void) g_close (fds[n], NULL);
751 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
763 "Unexpected ancillary message of type %s received from peer",
764 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
765 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
766 g_error_free (error);
767 g_object_unref (control_message);
769 while (n < worker->read_num_ancillary_messages)
770 g_object_unref (worker->read_ancillary_messages[n++]);
771 g_free (worker->read_ancillary_messages);
775 g_object_unref (control_message);
777 g_free (worker->read_ancillary_messages);
780 if (bytes_read == -1)
782 if (G_UNLIKELY (_g_dbus_debug_transport ()))
784 _g_dbus_debug_print_lock ();
785 g_print ("========================================================================\n"
786 "GDBus-debug:Transport:\n"
787 " ---- READ ERROR on stream of type %s:\n"
789 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))),
790 g_quark_to_string (error->domain), error->code,
792 _g_dbus_debug_print_unlock ();
795 /* Every async read that uses this callback uses worker->cancellable
796 * as its GCancellable. worker->cancellable gets cancelled if and only
797 * if the GDBusConnection tells us to close (either via
798 * _g_dbus_worker_stop, which is called on last-unref, or directly),
799 * so a cancelled read must mean our connection was closed locally.
801 * If we're closing, other errors are possible - notably,
802 * G_IO_ERROR_CLOSED can be seen if we close the stream with an async
803 * read in-flight. It seems sensible to treat all read errors during
804 * closing as an expected thing that doesn't trip exit-on-close.
806 * Because close_expected can't be set until we get into the worker
807 * thread, but the cancellable is signalled sooner (from another
808 * thread), we do still need to check the error.
810 if (worker->close_expected ||
811 g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
812 _g_dbus_worker_emit_disconnected (worker, FALSE, NULL);
814 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
816 g_error_free (error);
821 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
823 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
824 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
825 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
826 G_IO_IN | G_IO_OUT | G_IO_HUP),
831 /* TODO: hmm, hmm... */
837 "Underlying GIOStream returned 0 bytes on an async read");
838 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
839 g_error_free (error);
843 read_message_print_transport_debug (bytes_read, worker);
845 worker->read_buffer_cur_size += bytes_read;
846 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
848 /* OK, got what we asked for! */
849 if (worker->read_buffer_bytes_wanted == 16)
852 /* OK, got the header - determine how many more bytes are needed */
854 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
857 if (message_len == -1)
859 g_warning ("_g_dbus_worker_do_read_cb: error determining bytes needed: %s", error->message);
860 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
861 g_error_free (error);
865 worker->read_buffer_bytes_wanted = message_len;
866 _g_dbus_worker_do_read_unlocked (worker);
870 GDBusMessage *message;
873 /* TODO: use connection->priv->auth to decode the message */
875 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
876 worker->read_buffer_cur_size,
877 worker->capabilities,
882 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
883 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
885 "The payload is as follows:\n"
887 worker->read_buffer_cur_size,
891 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
892 g_error_free (error);
897 if (worker->read_fd_list != NULL)
899 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
900 g_object_unref (worker->read_fd_list);
901 worker->read_fd_list = NULL;
905 if (G_UNLIKELY (_g_dbus_debug_message ()))
908 _g_dbus_debug_print_lock ();
909 g_print ("========================================================================\n"
910 "GDBus-debug:Message:\n"
911 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
912 worker->read_buffer_cur_size);
913 s = g_dbus_message_print (message, 2);
916 if (G_UNLIKELY (_g_dbus_debug_payload ()))
918 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
922 _g_dbus_debug_print_unlock ();
925 /* yay, got a message, go deliver it */
926 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
928 /* start reading another message! */
929 worker->read_buffer_bytes_wanted = 0;
930 worker->read_buffer_cur_size = 0;
931 _g_dbus_worker_do_read_unlocked (worker);
936 /* didn't get all the bytes we requested - so repeat the request... */
937 _g_dbus_worker_do_read_unlocked (worker);
941 g_mutex_unlock (&worker->read_lock);
943 /* gives up the reference acquired when calling g_input_stream_read_async() */
944 _g_dbus_worker_unref (worker);
947 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
949 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
951 /* Note that we do need to keep trying to read even if close_expected is
952 * true, because only failing a read causes us to signal 'closed'.
955 /* if bytes_wanted is zero, it means start reading a message */
956 if (worker->read_buffer_bytes_wanted == 0)
958 worker->read_buffer_cur_size = 0;
959 worker->read_buffer_bytes_wanted = 16;
962 /* ensure we have a (big enough) buffer */
963 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
965 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
966 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
967 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
970 if (G_IS_KDBUS_CONNECTION (worker->stream))
976 _g_kdbus_read(worker->kdbus,
978 worker->read_buffer_bytes_wanted,
980 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
981 _g_dbus_worker_ref (worker));
984 } else if (worker->socket == NULL)
985 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
986 worker->read_buffer + worker->read_buffer_cur_size,
987 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
990 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
991 _g_dbus_worker_ref (worker));
994 worker->read_ancillary_messages = NULL;
995 worker->read_num_ancillary_messages = 0;
996 _g_socket_read_with_control_messages (worker->socket,
997 worker->read_buffer + worker->read_buffer_cur_size,
998 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
999 &worker->read_ancillary_messages,
1000 &worker->read_num_ancillary_messages,
1002 worker->cancellable,
1003 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
1004 _g_dbus_worker_ref (worker));
1008 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
1010 _g_dbus_worker_do_initial_read (gpointer data)
1012 //GDBusWorker *worker = data;
1013 //g_mutex_lock (&worker->read_lock);
1014 //_g_dbus_worker_do_read_unlocked (worker);
1015 //g_mutex_unlock (&worker->read_lock);
1019 /* ---------------------------------------------------------------------------------------------------- */
1021 struct _MessageToWriteData
1023 GDBusWorker *worker;
1024 GDBusMessage *message;
1028 gsize total_written;
1029 GSimpleAsyncResult *simple;
1034 message_to_write_data_free (MessageToWriteData *data)
1036 _g_dbus_worker_unref (data->worker);
1038 g_object_unref (data->message);
1039 g_free (data->blob);
1043 /* ---------------------------------------------------------------------------------------------------- */
1045 static void write_message_continue_writing (MessageToWriteData *data);
1047 /* called in private thread shared by all GDBusConnection instances
1049 * write-lock is not held on entry
1050 * output_pending is PENDING_WRITE on entry
1053 write_message_async_cb (GObject *source_object,
1057 MessageToWriteData *data = user_data;
1058 GSimpleAsyncResult *simple;
1059 gssize bytes_written;
1062 /* Note: we can't access data->simple after calling g_async_result_complete () because the
1063 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
1065 simple = data->simple;
1068 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
1071 if (bytes_written == -1)
1073 g_simple_async_result_take_error (simple, error);
1074 g_simple_async_result_complete (simple);
1075 g_object_unref (simple);
1078 g_assert (bytes_written > 0); /* zero is never returned */
1080 write_message_print_transport_debug (bytes_written, data);
1082 data->total_written += bytes_written;
1083 g_assert (data->total_written <= data->blob_size);
1084 if (data->total_written == data->blob_size)
1086 g_simple_async_result_complete (simple);
1087 g_object_unref (simple);
1091 write_message_continue_writing (data);
1097 /* called in private thread shared by all GDBusConnection instances
1099 * write-lock is not held on entry
1100 * output_pending is PENDING_WRITE on entry
1104 on_socket_ready (GSocket *socket,
1105 GIOCondition condition,
1108 MessageToWriteData *data = user_data;
1109 write_message_continue_writing (data);
1110 return FALSE; /* remove source */
1114 /* called in private thread shared by all GDBusConnection instances
1116 * write-lock is not held on entry
1117 * output_pending is PENDING_WRITE on entry
1120 write_message_continue_writing (MessageToWriteData *data)
1123 GSimpleAsyncResult *simple;
1124 simple = data->simple;
1127 if (G_IS_KDBUS_CONNECTION (data->worker->stream))
1131 data->total_written = g_kdbus_send_message(data->worker, data->worker->kdbus, data->message, data->blob, data->blob_size, &error);
1133 if (data->total_written == data->blob_size)
1135 g_simple_async_result_complete (simple);
1136 g_object_unref (simple);
1142 GOutputStream *ostream;
1144 GUnixFDList *fd_list;
1147 ostream = g_io_stream_get_output_stream (data->worker->stream);
1149 fd_list = g_dbus_message_get_unix_fd_list (data->message);
1152 g_assert (!g_output_stream_has_pending (ostream));
1153 g_assert_cmpint (data->total_written, <, data->blob_size);
1159 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
1161 GOutputVector vector;
1162 GSocketControlMessage *control_message;
1163 gssize bytes_written;
1166 vector.buffer = data->blob;
1167 vector.size = data->blob_size;
1169 control_message = NULL;
1170 if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
1172 if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
1174 g_simple_async_result_set_error (simple,
1177 "Tried sending a file descriptor but remote peer does not support this capability");
1178 g_simple_async_result_complete (simple);
1179 g_object_unref (simple);
1182 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1186 bytes_written = g_socket_send_message (data->worker->socket,
1190 control_message != NULL ? &control_message : NULL,
1191 control_message != NULL ? 1 : 0,
1193 data->worker->cancellable,
1195 if (control_message != NULL)
1196 g_object_unref (control_message);
1198 if (bytes_written == -1)
1200 /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1201 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1204 source = g_socket_create_source (data->worker->socket,
1205 G_IO_OUT | G_IO_HUP | G_IO_ERR,
1206 data->worker->cancellable);
1207 g_source_set_callback (source,
1208 (GSourceFunc) on_socket_ready,
1210 NULL); /* GDestroyNotify */
1211 g_source_attach (source, g_main_context_get_thread_default ());
1212 g_source_unref (source);
1213 g_error_free (error);
1216 g_simple_async_result_take_error (simple, error);
1217 g_simple_async_result_complete (simple);
1218 g_object_unref (simple);
1221 g_assert (bytes_written > 0); /* zero is never returned */
1223 write_message_print_transport_debug (bytes_written, data);
1225 data->total_written += bytes_written;
1226 g_assert (data->total_written <= data->blob_size);
1227 if (data->total_written == data->blob_size)
1229 g_simple_async_result_complete (simple);
1230 g_object_unref (simple);
1234 write_message_continue_writing (data);
1240 if (fd_list != NULL)
1242 g_simple_async_result_set_error (simple,
1245 "Tried sending a file descriptor on unsupported stream of type %s",
1246 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1247 g_simple_async_result_complete (simple);
1248 g_object_unref (simple);
1253 g_output_stream_write_async (ostream,
1254 (const gchar *) data->blob + data->total_written,
1255 data->blob_size - data->total_written,
1257 data->worker->cancellable,
1258 write_message_async_cb,
1268 /* called in private thread shared by all GDBusConnection instances
1270 * write-lock is not held on entry
1271 * output_pending is PENDING_WRITE on entry
1274 write_message_async (GDBusWorker *worker,
1275 MessageToWriteData *data,
1276 GAsyncReadyCallback callback,
1279 data->simple = g_simple_async_result_new (NULL,
1282 write_message_async);
1283 data->total_written = 0;
1284 write_message_continue_writing (data);
1287 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1289 write_message_finish (GAsyncResult *res,
1292 g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1293 if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1298 /* ---------------------------------------------------------------------------------------------------- */
1300 static void continue_writing (GDBusWorker *worker);
1304 GDBusWorker *worker;
1309 flush_data_list_complete (const GList *flushers,
1310 const GError *error)
1314 for (l = flushers; l != NULL; l = l->next)
1316 FlushData *f = l->data;
1318 f->error = error != NULL ? g_error_copy (error) : NULL;
1320 g_mutex_lock (&f->mutex);
1321 g_cond_signal (&f->cond);
1322 g_mutex_unlock (&f->mutex);
1326 /* called in private thread shared by all GDBusConnection instances
1328 * write-lock is not held on entry
1329 * output_pending is PENDING_FLUSH on entry
1332 ostream_flush_cb (GObject *source_object,
1336 FlushAsyncData *data = user_data;
1340 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1346 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1348 _g_dbus_debug_print_lock ();
1349 g_print ("========================================================================\n"
1350 "GDBus-debug:Transport:\n"
1351 " ---- FLUSHED stream of type %s\n",
1352 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1353 _g_dbus_debug_print_unlock ();
1357 g_assert (data->flushers != NULL);
1358 flush_data_list_complete (data->flushers, error);
1359 g_list_free (data->flushers);
1362 g_error_free (error);
1364 /* Make sure we tell folks that we don't have additional
1366 g_mutex_lock (&data->worker->write_lock);
1367 data->worker->write_num_messages_flushed = data->worker->write_num_messages_written;
1368 g_assert (data->worker->output_pending == PENDING_FLUSH);
1369 data->worker->output_pending = PENDING_NONE;
1370 g_mutex_unlock (&data->worker->write_lock);
1372 /* OK, cool, finally kick off the next write */
1373 continue_writing (data->worker);
1375 _g_dbus_worker_unref (data->worker);
1379 /* called in private thread shared by all GDBusConnection instances
1381 * write-lock is not held on entry
1382 * output_pending is PENDING_FLUSH on entry
1385 start_flush (FlushAsyncData *data)
1387 g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1389 data->worker->cancellable,
1394 /* called in private thread shared by all GDBusConnection instances
1396 * write-lock is held on entry
1397 * output_pending is PENDING_NONE on entry
1400 message_written_unlocked (GDBusWorker *worker,
1401 MessageToWriteData *message_data)
1403 if (G_UNLIKELY (_g_dbus_debug_message ()))
1406 _g_dbus_debug_print_lock ();
1407 g_print ("========================================================================\n"
1408 "GDBus-debug:Message:\n"
1409 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1410 message_data->blob_size);
1411 s = g_dbus_message_print (message_data->message, 2);
1414 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1416 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1417 g_print ("%s\n", s);
1420 _g_dbus_debug_print_unlock ();
1423 worker->write_num_messages_written += 1;
1426 /* called in private thread shared by all GDBusConnection instances
1428 * write-lock is held on entry
1429 * output_pending is PENDING_NONE on entry
1431 * Returns: non-%NULL, setting @output_pending, if we need to flush now
1433 static FlushAsyncData *
1434 prepare_flush_unlocked (GDBusWorker *worker)
1441 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1443 FlushData *f = l->data;
1446 if (f->number_to_wait_for == worker->write_num_messages_written)
1448 flushers = g_list_append (flushers, f);
1449 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1452 if (flushers != NULL)
1454 g_assert (worker->output_pending == PENDING_NONE);
1455 worker->output_pending = PENDING_FLUSH;
1458 if (flushers != NULL)
1460 FlushAsyncData *data;
1462 data = g_new0 (FlushAsyncData, 1);
1463 data->worker = _g_dbus_worker_ref (worker);
1464 data->flushers = flushers;
1471 /* called in private thread shared by all GDBusConnection instances
1473 * write-lock is not held on entry
1474 * output_pending is PENDING_WRITE on entry
1477 write_message_cb (GObject *source_object,
1481 MessageToWriteData *data = user_data;
1484 g_mutex_lock (&data->worker->write_lock);
1485 g_assert (data->worker->output_pending == PENDING_WRITE);
1486 data->worker->output_pending = PENDING_NONE;
1489 if (!write_message_finish (res, &error))
1491 g_mutex_unlock (&data->worker->write_lock);
1494 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1495 g_error_free (error);
1497 g_mutex_lock (&data->worker->write_lock);
1500 message_written_unlocked (data->worker, data);
1502 g_mutex_unlock (&data->worker->write_lock);
1504 continue_writing (data->worker);
1506 message_to_write_data_free (data);
1509 /* called in private thread shared by all GDBusConnection instances
1511 * write-lock is not held on entry
1512 * output_pending is PENDING_CLOSE on entry
1515 iostream_close_cb (GObject *source_object,
1519 GDBusWorker *worker = user_data;
1520 GError *error = NULL;
1521 GList *pending_close_attempts, *pending_flush_attempts;
1524 g_io_stream_close_finish (worker->stream, res, &error);
1526 g_mutex_lock (&worker->write_lock);
1528 pending_close_attempts = worker->pending_close_attempts;
1529 worker->pending_close_attempts = NULL;
1531 pending_flush_attempts = worker->write_pending_flushes;
1532 worker->write_pending_flushes = NULL;
1534 send_queue = worker->write_queue;
1535 worker->write_queue = g_queue_new ();
1537 g_assert (worker->output_pending == PENDING_CLOSE);
1538 worker->output_pending = PENDING_NONE;
1540 g_mutex_unlock (&worker->write_lock);
1542 while (pending_close_attempts != NULL)
1544 CloseData *close_data = pending_close_attempts->data;
1546 pending_close_attempts = g_list_delete_link (pending_close_attempts,
1547 pending_close_attempts);
1549 if (close_data->result != NULL)
1552 g_simple_async_result_set_from_error (close_data->result, error);
1554 /* this must be in an idle because the result is likely to be
1555 * intended for another thread
1557 g_simple_async_result_complete_in_idle (close_data->result);
1560 close_data_free (close_data);
1563 g_clear_error (&error);
1565 /* all messages queued for sending are discarded */
1566 g_queue_free_full (send_queue, (GDestroyNotify) message_to_write_data_free);
1567 /* all queued flushes fail */
1568 error = g_error_new (G_IO_ERROR, G_IO_ERROR_CANCELLED,
1569 _("Operation was cancelled"));
1570 flush_data_list_complete (pending_flush_attempts, error);
1571 g_list_free (pending_flush_attempts);
1572 g_clear_error (&error);
1574 _g_dbus_worker_unref (worker);
1577 /* called in private thread shared by all GDBusConnection instances
1579 * write-lock is not held on entry
1580 * output_pending must be PENDING_NONE on entry
1583 continue_writing (GDBusWorker *worker)
1585 MessageToWriteData *data;
1586 FlushAsyncData *flush_async_data;
1589 /* we mustn't try to write two things at once */
1590 g_assert (worker->output_pending == PENDING_NONE);
1592 g_mutex_lock (&worker->write_lock);
1595 flush_async_data = NULL;
1597 /* if we want to close the connection, that takes precedence */
1598 if (worker->pending_close_attempts != NULL)
1600 worker->close_expected = TRUE;
1601 worker->output_pending = PENDING_CLOSE;
1603 g_io_stream_close_async (worker->stream, G_PRIORITY_DEFAULT,
1604 NULL, iostream_close_cb,
1605 _g_dbus_worker_ref (worker));
1609 flush_async_data = prepare_flush_unlocked (worker);
1611 if (flush_async_data == NULL)
1613 data = g_queue_pop_head (worker->write_queue);
1616 worker->output_pending = PENDING_WRITE;
1620 g_mutex_unlock (&worker->write_lock);
1622 /* Note that write_lock is only used for protecting the @write_queue
1623 * and @output_pending fields of the GDBusWorker struct ... which we
1624 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1626 * Therefore, it's fine to drop it here when calling back into user
1627 * code and then writing the message out onto the GIOStream since this
1628 * function only runs on the worker thread.
1631 if (flush_async_data != NULL)
1633 start_flush (flush_async_data);
1634 g_assert (data == NULL);
1636 else if (data != NULL)
1638 GDBusMessage *old_message;
1640 gsize new_blob_size;
1643 old_message = data->message;
1644 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1645 if (data->message == old_message)
1647 /* filters had no effect - do nothing */
1649 else if (data->message == NULL)
1651 /* filters dropped message */
1652 g_mutex_lock (&worker->write_lock);
1653 worker->output_pending = PENDING_NONE;
1654 g_mutex_unlock (&worker->write_lock);
1655 message_to_write_data_free (data);
1660 /* filters altered the message -> reencode */
1662 new_blob = g_dbus_message_to_blob (data->message,
1664 worker->capabilities,
1666 if (new_blob == NULL)
1668 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1669 * the old message instead
1671 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1672 g_dbus_message_get_serial (data->message),
1674 g_error_free (error);
1678 g_free (data->blob);
1679 data->blob = (gchar *) new_blob;
1680 data->blob_size = new_blob_size;
1684 write_message_async (worker,
1691 /* called in private thread shared by all GDBusConnection instances
1693 * write-lock is not held on entry
1694 * output_pending may be anything
1697 continue_writing_in_idle_cb (gpointer user_data)
1699 GDBusWorker *worker = user_data;
1701 /* Because this is the worker thread, we can read this struct member
1702 * without holding the lock: no other thread ever modifies it.
1704 if (worker->output_pending == PENDING_NONE)
1705 continue_writing (worker);
1711 * @write_data: (transfer full) (allow-none):
1712 * @flush_data: (transfer full) (allow-none):
1713 * @close_data: (transfer full) (allow-none):
1715 * Can be called from any thread
1717 * write_lock is held on entry
1718 * output_pending may be anything
1721 schedule_writing_unlocked (GDBusWorker *worker,
1722 MessageToWriteData *write_data,
1723 FlushData *flush_data,
1724 CloseData *close_data)
1726 if (write_data != NULL)
1727 g_queue_push_tail (worker->write_queue, write_data);
1729 if (flush_data != NULL)
1730 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, flush_data);
1732 if (close_data != NULL)
1733 worker->pending_close_attempts = g_list_prepend (worker->pending_close_attempts,
1736 /* If we had output pending, the next bit of output will happen
1737 * automatically when it finishes, so we only need to do this
1738 * if nothing was pending.
1740 * The idle callback will re-check that output_pending is still
1741 * PENDING_NONE, to guard against output starting before the idle.
1743 if (worker->output_pending == PENDING_NONE)
1745 GSource *idle_source;
1746 idle_source = g_idle_source_new ();
1747 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1748 g_source_set_callback (idle_source,
1749 continue_writing_in_idle_cb,
1750 _g_dbus_worker_ref (worker),
1751 (GDestroyNotify) _g_dbus_worker_unref);
1752 g_source_attach (idle_source, worker->shared_thread_data->context);
1753 g_source_unref (idle_source);
1757 /* ---------------------------------------------------------------------------------------------------- */
1759 /* can be called from any thread - steals blob
1761 * write_lock is not held on entry
1762 * output_pending may be anything
1765 _g_dbus_worker_send_message (GDBusWorker *worker,
1766 GDBusMessage *message,
1770 MessageToWriteData *data;
1772 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1773 g_return_if_fail (blob != NULL);
1774 g_return_if_fail (blob_len > 16);
1776 data = g_new0 (MessageToWriteData, 1);
1777 data->worker = _g_dbus_worker_ref (worker);
1778 data->message = g_object_ref (message);
1779 data->blob = blob; /* steal! */
1780 data->blob_size = blob_len;
1782 g_mutex_lock (&worker->write_lock);
1783 schedule_writing_unlocked (worker, data, NULL, NULL);
1784 g_mutex_unlock (&worker->write_lock);
1787 /* ---------------------------------------------------------------------------------------------------- */
1788 GKdbus* g_dbus_worker_get_kdbus (GDBusWorker *worker)
1790 return worker->kdbus;
1794 _g_dbus_worker_new (GIOStream *stream,
1795 GDBusCapabilityFlags capabilities,
1796 gboolean initially_frozen,
1797 GDBusWorkerMessageReceivedCallback message_received_callback,
1798 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1799 GDBusWorkerDisconnectedCallback disconnected_callback,
1802 GDBusWorker *worker;
1803 GSource *idle_source;
1805 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1806 g_return_val_if_fail (message_received_callback != NULL, NULL);
1807 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1808 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1810 worker = g_new0 (GDBusWorker, 1);
1811 worker->ref_count = 1;
1813 g_mutex_init (&worker->read_lock);
1814 worker->message_received_callback = message_received_callback;
1815 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1816 worker->disconnected_callback = disconnected_callback;
1817 worker->user_data = user_data;
1818 worker->stream = g_object_ref (stream);
1819 worker->capabilities = capabilities;
1820 worker->cancellable = g_cancellable_new ();
1821 worker->output_pending = PENDING_NONE;
1823 worker->frozen = initially_frozen;
1824 worker->received_messages_while_frozen = g_queue_new ();
1826 g_mutex_init (&worker->write_lock);
1827 worker->write_queue = g_queue_new ();
1829 if (G_IS_SOCKET_CONNECTION (worker->stream))
1830 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1832 if (G_IS_KDBUS_CONNECTION (worker->stream))
1833 worker->kdbus = g_kdbus_connection_get_kdbus (G_KDBUS_CONNECTION (worker->stream));
1835 worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1838 idle_source = g_idle_source_new ();
1839 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1840 g_source_set_callback (idle_source,
1841 _g_dbus_worker_do_initial_read,
1842 _g_dbus_worker_ref (worker),
1843 (GDestroyNotify) _g_dbus_worker_unref);
1844 g_source_attach (idle_source, worker->shared_thread_data->context);
1845 g_source_unref (idle_source);
1850 /* ---------------------------------------------------------------------------------------------------- */
1852 /* can be called from any thread
1854 * write_lock is not held on entry
1855 * output_pending may be anything
1858 _g_dbus_worker_close (GDBusWorker *worker,
1859 GCancellable *cancellable,
1860 GSimpleAsyncResult *result)
1862 CloseData *close_data;
1864 close_data = g_slice_new0 (CloseData);
1865 close_data->worker = _g_dbus_worker_ref (worker);
1866 close_data->cancellable =
1867 (cancellable == NULL ? NULL : g_object_ref (cancellable));
1868 close_data->result = (result == NULL ? NULL : g_object_ref (result));
1870 /* Don't set worker->close_expected here - we're in the wrong thread.
1871 * It'll be set before the actual close happens.
1873 g_cancellable_cancel (worker->cancellable);
1874 g_mutex_lock (&worker->write_lock);
1875 schedule_writing_unlocked (worker, NULL, NULL, close_data);
1876 g_mutex_unlock (&worker->write_lock);
1879 /* This can be called from any thread - frees worker. Note that
1880 * callbacks might still happen if called from another thread than the
1881 * worker - use your own synchronization primitive in the callbacks.
1883 * write_lock is not held on entry
1884 * output_pending may be anything
1887 _g_dbus_worker_stop (GDBusWorker *worker)
1889 g_atomic_int_set (&worker->stopped, TRUE);
1891 /* Cancel any pending operations and schedule a close of the underlying I/O
1892 * stream in the worker thread
1894 _g_dbus_worker_close (worker, NULL, NULL);
1896 /* _g_dbus_worker_close holds a ref until after an idle in the worker
1897 * thread has run, so we no longer need to unref in an idle like in
1900 _g_dbus_worker_unref (worker);
1903 /* ---------------------------------------------------------------------------------------------------- */
1905 /* can be called from any thread (except the worker thread) - blocks
1906 * calling thread until all queued outgoing messages are written and
1907 * the transport has been flushed
1909 * write_lock is not held on entry
1910 * output_pending may be anything
1913 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1914 GCancellable *cancellable,
1919 guint64 pending_writes;
1924 g_mutex_lock (&worker->write_lock);
1926 /* if the queue is empty, no write is in-flight and we haven't written
1927 * anything since the last flush, then there's nothing to wait for
1929 pending_writes = g_queue_get_length (worker->write_queue);
1931 /* if a write is in-flight, we shouldn't be satisfied until the first
1932 * flush operation that follows it
1934 if (worker->output_pending == PENDING_WRITE)
1935 pending_writes += 1;
1937 if (pending_writes > 0 ||
1938 worker->write_num_messages_written != worker->write_num_messages_flushed)
1940 data = g_new0 (FlushData, 1);
1941 g_mutex_init (&data->mutex);
1942 g_cond_init (&data->cond);
1943 data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
1944 g_mutex_lock (&data->mutex);
1946 schedule_writing_unlocked (worker, NULL, data, NULL);
1948 g_mutex_unlock (&worker->write_lock);
1952 g_cond_wait (&data->cond, &data->mutex);
1953 g_mutex_unlock (&data->mutex);
1955 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1956 g_cond_clear (&data->cond);
1957 g_mutex_clear (&data->mutex);
1958 if (data->error != NULL)
1961 g_propagate_error (error, data->error);
1969 /* ---------------------------------------------------------------------------------------------------- */
1971 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1972 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1973 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1974 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1975 #define G_DBUS_DEBUG_CALL (1<<4)
1976 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1977 #define G_DBUS_DEBUG_INCOMING (1<<6)
1978 #define G_DBUS_DEBUG_RETURN (1<<7)
1979 #define G_DBUS_DEBUG_EMISSION (1<<8)
1980 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1982 static gint _gdbus_debug_flags = 0;
1985 _g_dbus_debug_authentication (void)
1987 _g_dbus_initialize ();
1988 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1992 _g_dbus_debug_transport (void)
1994 _g_dbus_initialize ();
1995 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1999 _g_dbus_debug_message (void)
2001 _g_dbus_initialize ();
2002 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
2006 _g_dbus_debug_payload (void)
2008 _g_dbus_initialize ();
2009 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
2013 _g_dbus_debug_call (void)
2015 _g_dbus_initialize ();
2016 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
2020 _g_dbus_debug_signal (void)
2022 _g_dbus_initialize ();
2023 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
2027 _g_dbus_debug_incoming (void)
2029 _g_dbus_initialize ();
2030 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
2034 _g_dbus_debug_return (void)
2036 _g_dbus_initialize ();
2037 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
2041 _g_dbus_debug_emission (void)
2043 _g_dbus_initialize ();
2044 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
2048 _g_dbus_debug_address (void)
2050 _g_dbus_initialize ();
2051 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
2054 G_LOCK_DEFINE_STATIC (print_lock);
2057 _g_dbus_debug_print_lock (void)
2059 G_LOCK (print_lock);
2063 _g_dbus_debug_print_unlock (void)
2065 G_UNLOCK (print_lock);
2069 * _g_dbus_initialize:
2071 * Does various one-time init things such as
2073 * - registering the G_DBUS_ERROR error domain
2074 * - parses the G_DBUS_DEBUG environment variable
2077 _g_dbus_initialize (void)
2079 static volatile gsize initialized = 0;
2081 if (g_once_init_enter (&initialized))
2083 volatile GQuark g_dbus_error_domain;
2086 g_dbus_error_domain = G_DBUS_ERROR;
2087 (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
2089 debug = g_getenv ("G_DBUS_DEBUG");
2092 const GDebugKey keys[] = {
2093 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
2094 { "transport", G_DBUS_DEBUG_TRANSPORT },
2095 { "message", G_DBUS_DEBUG_MESSAGE },
2096 { "payload", G_DBUS_DEBUG_PAYLOAD },
2097 { "call", G_DBUS_DEBUG_CALL },
2098 { "signal", G_DBUS_DEBUG_SIGNAL },
2099 { "incoming", G_DBUS_DEBUG_INCOMING },
2100 { "return", G_DBUS_DEBUG_RETURN },
2101 { "emission", G_DBUS_DEBUG_EMISSION },
2102 { "address", G_DBUS_DEBUG_ADDRESS }
2105 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
2106 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
2107 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
2110 g_once_init_leave (&initialized, 1);
2114 /* ---------------------------------------------------------------------------------------------------- */
2117 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
2119 const GVariantType *arg_types[256];
2123 for (n = 0; args[n] != NULL; n++)
2125 /* DBus places a hard limit of 255 on signature length.
2126 * therefore number of args must be less than 256.
2130 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
2132 if G_UNLIKELY (arg_types[n] == NULL)
2138 return g_variant_type_new_tuple (arg_types, n);
2141 /* ---------------------------------------------------------------------------------------------------- */
2145 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
2148 _g_dbus_win32_get_user_sid (void)
2152 DWORD token_information_len;
2159 h = INVALID_HANDLE_VALUE;
2161 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
2163 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
2167 /* Get length of buffer */
2168 token_information_len = 0;
2169 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
2171 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
2173 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2177 user = g_malloc (token_information_len);
2178 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
2180 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2184 psid = user->User.Sid;
2185 if (!IsValidSid (psid))
2187 g_warning ("Invalid SID");
2191 if (!ConvertSidToStringSidA (psid, &sid))
2193 g_warning ("Invalid SID");
2197 ret = g_strdup (sid);
2202 if (h != INVALID_HANDLE_VALUE)
2208 /* ---------------------------------------------------------------------------------------------------- */
2211 _g_dbus_get_machine_id (GError **error)
2214 HW_PROFILE_INFOA info;
2215 char *src, *dest, *res;
2218 if (!GetCurrentHwProfileA (&info))
2220 char *message = g_win32_error_message (GetLastError ());
2224 _("Unable to get Hardware profile: %s"), message);
2229 /* Form: {12340001-4980-1920-6788-123456789012} */
2230 src = &info.szHwProfileGuid[0];
2232 res = g_malloc (32+1);
2236 for (i = 0; i < 8; i++)
2239 for (i = 0; i < 4; i++)
2242 for (i = 0; i < 4; i++)
2245 for (i = 0; i < 4; i++)
2248 for (i = 0; i < 12; i++)
2255 GError *first_error;
2256 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2259 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2263 !g_file_get_contents ("/etc/machine-id",
2268 g_propagate_prefixed_error (error, first_error,
2269 _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2273 /* ignore the error from the first try, if any */
2274 g_clear_error (&first_error);
2275 /* TODO: validate value */
2282 /* ---------------------------------------------------------------------------------------------------- */
2285 _g_dbus_enum_to_string (GType enum_type, gint value)
2289 GEnumValue *enum_value;
2291 klass = g_type_class_ref (enum_type);
2292 enum_value = g_enum_get_value (klass, value);
2293 if (enum_value != NULL)
2294 ret = g_strdup (enum_value->value_nick);
2296 ret = g_strdup_printf ("unknown (value %d)", value);
2297 g_type_class_unref (klass);
2301 /* ---------------------------------------------------------------------------------------------------- */
2304 write_message_print_transport_debug (gssize bytes_written,
2305 MessageToWriteData *data)
2307 if (G_LIKELY (!_g_dbus_debug_transport ()))
2310 _g_dbus_debug_print_lock ();
2311 g_print ("========================================================================\n"
2312 "GDBus-debug:Transport:\n"
2313 " >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2314 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
2316 g_dbus_message_get_serial (data->message),
2318 data->total_written,
2319 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
2320 _g_dbus_debug_print_unlock ();
2325 /* ---------------------------------------------------------------------------------------------------- */
2328 read_message_print_transport_debug (gssize bytes_read,
2329 GDBusWorker *worker)
2333 gint32 message_length;
2335 if (G_LIKELY (!_g_dbus_debug_transport ()))
2338 size = bytes_read + worker->read_buffer_cur_size;
2342 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2345 switch (worker->read_buffer[0])
2349 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2353 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2356 /* an error will be set elsewhere if this happens */
2361 _g_dbus_debug_print_lock ();
2362 g_print ("========================================================================\n"
2363 "GDBus-debug:Transport:\n"
2364 " <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2365 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
2369 worker->read_buffer_cur_size,
2370 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
2371 _g_dbus_debug_print_unlock ();
2376 /* ---------------------------------------------------------------------------------------------------- */
2379 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2380 GValue *return_accu,
2381 const GValue *handler_return,
2384 gboolean continue_emission;
2385 gboolean signal_return;
2387 signal_return = g_value_get_boolean (handler_return);
2388 g_value_set_boolean (return_accu, signal_return);
2389 continue_emission = signal_return;
2391 return continue_emission;