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,
237 data = g_new0 (ReadKdbusData, 1);
238 data->kdbus = kdbus; /*g_object_ref (socket);*/
239 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
240 data->buffer = buffer;
243 data->simple = g_simple_async_result_new (G_OBJECT (kdbus),
247 g_simple_async_result_set_check_cancellable (data->simple, cancellable);
249 data->from_mainloop = TRUE;
250 source = g_kdbus_create_source (data->kdbus,
251 G_IO_IN | G_IO_HUP | G_IO_ERR,
253 g_source_set_callback (source,
254 (GSourceFunc) _g_kdbus_read_ready,
256 (GDestroyNotify) read_kdbus_data_free);
257 g_source_attach (source, g_main_context_get_thread_default ());
258 g_source_unref (source);
262 _g_socket_read_with_control_messages (GSocket *socket,
265 GSocketControlMessage ***messages,
268 GCancellable *cancellable,
269 GAsyncReadyCallback callback,
272 ReadWithControlData *data;
274 data = g_new0 (ReadWithControlData, 1);
275 data->socket = g_object_ref (socket);
276 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
277 data->buffer = buffer;
279 data->messages = messages;
280 data->num_messages = num_messages;
282 data->simple = g_simple_async_result_new (G_OBJECT (socket),
285 _g_socket_read_with_control_messages);
286 g_simple_async_result_set_check_cancellable (data->simple, cancellable);
288 if (!g_socket_condition_check (socket, G_IO_IN))
291 data->from_mainloop = TRUE;
292 source = g_socket_create_source (data->socket,
293 G_IO_IN | G_IO_HUP | G_IO_ERR,
295 g_source_set_callback (source,
296 (GSourceFunc) _g_socket_read_with_control_messages_ready,
298 (GDestroyNotify) read_with_control_data_free);
299 g_source_attach (source, g_main_context_get_thread_default ());
300 g_source_unref (source);
304 _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
305 read_with_control_data_free (data);
310 _g_kdbus_read_finish (GKdbus *kdbus,
311 GAsyncResult *result,
314 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
316 g_return_val_if_fail (G_IS_KDBUS (kdbus), -1);
317 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_kdbus_read);
319 if (g_simple_async_result_propagate_error (simple, error))
322 return g_simple_async_result_get_op_res_gssize (simple);
326 _g_socket_read_with_control_messages_finish (GSocket *socket,
327 GAsyncResult *result,
330 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
332 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
333 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
335 if (g_simple_async_result_propagate_error (simple, error))
338 return g_simple_async_result_get_op_res_gssize (simple);
341 /* ---------------------------------------------------------------------------------------------------- */
343 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
345 static GPtrArray *ensured_classes = NULL;
348 ensure_type (GType gtype)
350 g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
354 release_required_types (void)
356 g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
357 g_ptr_array_unref (ensured_classes);
358 ensured_classes = NULL;
362 ensure_required_types (void)
364 g_assert (ensured_classes == NULL);
365 ensured_classes = g_ptr_array_new ();
366 ensure_type (G_TYPE_SIMPLE_ASYNC_RESULT);
367 ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
369 /* ---------------------------------------------------------------------------------------------------- */
373 volatile gint refcount;
375 GMainContext *context;
380 gdbus_shared_thread_func (gpointer user_data)
382 SharedThreadData *data = user_data;
384 g_main_context_push_thread_default (data->context);
385 g_main_loop_run (data->loop);
386 g_main_context_pop_thread_default (data->context);
388 release_required_types ();
393 /* ---------------------------------------------------------------------------------------------------- */
395 static SharedThreadData *
396 _g_dbus_shared_thread_ref (void)
398 static gsize shared_thread_data = 0;
399 SharedThreadData *ret;
401 if (g_once_init_enter (&shared_thread_data))
403 SharedThreadData *data;
405 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
406 ensure_required_types ();
408 data = g_new0 (SharedThreadData, 1);
411 data->context = g_main_context_new ();
412 data->loop = g_main_loop_new (data->context, FALSE);
413 data->thread = g_thread_new ("gdbus",
414 gdbus_shared_thread_func,
416 /* We can cast between gsize and gpointer safely */
417 g_once_init_leave (&shared_thread_data, (gsize) data);
420 ret = (SharedThreadData*) shared_thread_data;
421 g_atomic_int_inc (&ret->refcount);
426 _g_dbus_shared_thread_unref (SharedThreadData *data)
428 /* TODO: actually destroy the shared thread here */
430 g_assert (data != NULL);
431 if (g_atomic_int_dec_and_test (&data->refcount))
433 g_main_loop_quit (data->loop);
434 //g_thread_join (data->thread);
435 g_main_loop_unref (data->loop);
436 g_main_context_unref (data->context);
441 /* ---------------------------------------------------------------------------------------------------- */
452 volatile gint ref_count;
454 SharedThreadData *shared_thread_data;
456 /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
457 volatile gint stopped;
459 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
460 * only affects messages received from the other peer (since GDBusServer is the
461 * only user) - we might want it to affect messages sent to the other peer too?
464 GDBusCapabilityFlags capabilities;
465 GQueue *received_messages_while_frozen;
468 GCancellable *cancellable;
469 GDBusWorkerMessageReceivedCallback message_received_callback;
470 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
471 GDBusWorkerDisconnectedCallback disconnected_callback;
474 /* if GSocket and GKdbus are NULL, stream is GSocketConnection */
478 /* used for reading */
481 gsize read_buffer_allocated_size;
482 gsize read_buffer_cur_size;
483 gsize read_buffer_bytes_wanted;
484 GUnixFDList *read_fd_list;
485 GSocketControlMessage **read_ancillary_messages;
486 gint read_num_ancillary_messages;
488 /* Whether an async write, flush or close, or none of those, is pending.
489 * Only the worker thread may change its value, and only with the write_lock.
490 * Other threads may read its value when holding the write_lock.
491 * The worker thread may read its value at any time.
493 OutputPending output_pending;
494 /* used for writing */
496 /* queue of MessageToWriteData, protected by write_lock */
498 /* protected by write_lock */
499 guint64 write_num_messages_written;
500 /* number of messages we'd written out last time we flushed;
501 * protected by write_lock
503 guint64 write_num_messages_flushed;
504 /* list of FlushData, protected by write_lock */
505 GList *write_pending_flushes;
506 /* list of CloseData, protected by write_lock */
507 GList *pending_close_attempts;
508 /* no lock - only used from the worker thread */
509 gboolean close_expected;
512 static void _g_dbus_worker_unref (GDBusWorker *worker);
514 /* ---------------------------------------------------------------------------------------------------- */
520 guint64 number_to_wait_for;
524 struct _MessageToWriteData ;
525 typedef struct _MessageToWriteData MessageToWriteData;
527 static void message_to_write_data_free (MessageToWriteData *data);
529 static void read_message_print_transport_debug (gssize bytes_read,
530 GDBusWorker *worker);
532 static void write_message_print_transport_debug (gssize bytes_written,
533 MessageToWriteData *data);
537 GCancellable *cancellable;
538 GSimpleAsyncResult *result;
541 static void close_data_free (CloseData *close_data)
543 if (close_data->cancellable != NULL)
544 g_object_unref (close_data->cancellable);
546 if (close_data->result != NULL)
547 g_object_unref (close_data->result);
549 _g_dbus_worker_unref (close_data->worker);
550 g_slice_free (CloseData, close_data);
553 /* ---------------------------------------------------------------------------------------------------- */
556 _g_dbus_worker_ref (GDBusWorker *worker)
558 g_atomic_int_inc (&worker->ref_count);
563 _g_dbus_worker_unref (GDBusWorker *worker)
565 if (g_atomic_int_dec_and_test (&worker->ref_count))
567 g_assert (worker->write_pending_flushes == NULL);
569 _g_dbus_shared_thread_unref (worker->shared_thread_data);
571 g_object_unref (worker->stream);
573 g_mutex_clear (&worker->read_lock);
574 g_object_unref (worker->cancellable);
575 if (worker->read_fd_list != NULL)
576 g_object_unref (worker->read_fd_list);
578 g_queue_free_full (worker->received_messages_while_frozen, (GDestroyNotify) g_object_unref);
579 g_mutex_clear (&worker->write_lock);
580 g_queue_free_full (worker->write_queue, (GDestroyNotify) message_to_write_data_free);
581 g_free (worker->read_buffer);
588 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
589 gboolean remote_peer_vanished,
592 if (!g_atomic_int_get (&worker->stopped))
593 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
597 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
598 GDBusMessage *message)
600 if (!g_atomic_int_get (&worker->stopped))
601 worker->message_received_callback (worker, message, worker->user_data);
604 static GDBusMessage *
605 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
606 GDBusMessage *message)
609 if (!g_atomic_int_get (&worker->stopped))
610 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
616 /* can only be called from private thread with read-lock held - takes ownership of @message */
618 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
619 GDBusMessage *message)
621 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
624 g_queue_push_tail (worker->received_messages_while_frozen, message);
628 /* not frozen, nor anything in queue */
629 _g_dbus_worker_emit_message_received (worker, message);
630 g_object_unref (message);
634 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
636 unfreeze_in_idle_cb (gpointer user_data)
638 GDBusWorker *worker = user_data;
639 GDBusMessage *message;
641 g_mutex_lock (&worker->read_lock);
644 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
646 _g_dbus_worker_emit_message_received (worker, message);
647 g_object_unref (message);
649 worker->frozen = FALSE;
653 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
655 g_mutex_unlock (&worker->read_lock);
659 /* can be called from any thread */
661 _g_dbus_worker_unfreeze (GDBusWorker *worker)
663 GSource *idle_source;
664 idle_source = g_idle_source_new ();
665 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
666 g_source_set_callback (idle_source,
668 _g_dbus_worker_ref (worker),
669 (GDestroyNotify) _g_dbus_worker_unref);
670 g_source_attach (idle_source, worker->shared_thread_data->context);
671 g_source_unref (idle_source);
674 /* ---------------------------------------------------------------------------------------------------- */
676 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
678 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
680 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
684 GDBusWorker *worker = user_data;
688 g_mutex_lock (&worker->read_lock);
690 /* If already stopped, don't even process the reply */
691 if (g_atomic_int_get (&worker->stopped))
695 if (G_IS_KDBUS_CONNECTION (worker->stream))
697 bytes_read = _g_kdbus_read_finish (worker->kdbus,
700 } else if (worker->socket == NULL)
701 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
705 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
708 if (worker->read_num_ancillary_messages > 0)
711 for (n = 0; n < worker->read_num_ancillary_messages; n++)
713 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
719 else if (G_IS_UNIX_FD_MESSAGE (control_message))
721 GUnixFDMessage *fd_message;
725 fd_message = G_UNIX_FD_MESSAGE (control_message);
726 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
727 if (worker->read_fd_list == NULL)
729 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
734 for (n = 0; n < num_fds; n++)
736 /* TODO: really want a append_steal() */
737 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
738 (void) g_close (fds[n], NULL);
743 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
755 "Unexpected ancillary message of type %s received from peer",
756 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
757 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
758 g_error_free (error);
759 g_object_unref (control_message);
761 while (n < worker->read_num_ancillary_messages)
762 g_object_unref (worker->read_ancillary_messages[n++]);
763 g_free (worker->read_ancillary_messages);
767 g_object_unref (control_message);
769 g_free (worker->read_ancillary_messages);
772 if (bytes_read == -1)
774 if (G_UNLIKELY (_g_dbus_debug_transport ()))
776 _g_dbus_debug_print_lock ();
777 g_print ("========================================================================\n"
778 "GDBus-debug:Transport:\n"
779 " ---- READ ERROR on stream of type %s:\n"
781 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))),
782 g_quark_to_string (error->domain), error->code,
784 _g_dbus_debug_print_unlock ();
787 /* Every async read that uses this callback uses worker->cancellable
788 * as its GCancellable. worker->cancellable gets cancelled if and only
789 * if the GDBusConnection tells us to close (either via
790 * _g_dbus_worker_stop, which is called on last-unref, or directly),
791 * so a cancelled read must mean our connection was closed locally.
793 * If we're closing, other errors are possible - notably,
794 * G_IO_ERROR_CLOSED can be seen if we close the stream with an async
795 * read in-flight. It seems sensible to treat all read errors during
796 * closing as an expected thing that doesn't trip exit-on-close.
798 * Because close_expected can't be set until we get into the worker
799 * thread, but the cancellable is signalled sooner (from another
800 * thread), we do still need to check the error.
802 if (worker->close_expected ||
803 g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
804 _g_dbus_worker_emit_disconnected (worker, FALSE, NULL);
806 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
808 g_error_free (error);
813 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
815 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
816 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
817 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
818 G_IO_IN | G_IO_OUT | G_IO_HUP),
823 /* TODO: hmm, hmm... */
829 "Underlying GIOStream returned 0 bytes on an async read");
830 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
831 g_error_free (error);
835 read_message_print_transport_debug (bytes_read, worker);
837 worker->read_buffer_cur_size += bytes_read;
839 /* TODO: [KDBUS] Sprawdzic pole read_buffer_bytes_wanted */
840 if (G_IS_KDBUS_CONNECTION (worker->stream))
841 worker->read_buffer_bytes_wanted = worker->read_buffer_cur_size;
843 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
845 /* OK, got what we asked for! */
846 if (worker->read_buffer_bytes_wanted == 16)
849 /* OK, got the header - determine how many more bytes are needed */
851 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
854 if (message_len == -1)
856 g_warning ("_g_dbus_worker_do_read_cb: error determining bytes needed: %s", error->message);
857 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
858 g_error_free (error);
862 worker->read_buffer_bytes_wanted = message_len;
863 _g_dbus_worker_do_read_unlocked (worker);
867 GDBusMessage *message;
870 /* TODO: use connection->priv->auth to decode the message */
872 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
873 worker->read_buffer_cur_size,
874 worker->capabilities,
879 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
880 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
882 "The payload is as follows:\n"
884 worker->read_buffer_cur_size,
888 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
889 g_error_free (error);
894 if (worker->read_fd_list != NULL)
896 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
897 g_object_unref (worker->read_fd_list);
898 worker->read_fd_list = NULL;
902 if (G_UNLIKELY (_g_dbus_debug_message ()))
905 _g_dbus_debug_print_lock ();
906 g_print ("========================================================================\n"
907 "GDBus-debug:Message:\n"
908 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
909 worker->read_buffer_cur_size);
910 s = g_dbus_message_print (message, 2);
913 if (G_UNLIKELY (_g_dbus_debug_payload ()))
915 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
919 _g_dbus_debug_print_unlock ();
922 /* yay, got a message, go deliver it */
923 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
925 /* start reading another message! */
926 worker->read_buffer_bytes_wanted = 0;
927 worker->read_buffer_cur_size = 0;
928 _g_dbus_worker_do_read_unlocked (worker);
933 /* didn't get all the bytes we requested - so repeat the request... */
934 _g_dbus_worker_do_read_unlocked (worker);
938 g_mutex_unlock (&worker->read_lock);
940 /* gives up the reference acquired when calling g_input_stream_read_async() */
941 _g_dbus_worker_unref (worker);
944 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
946 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
948 /* Note that we do need to keep trying to read even if close_expected is
949 * true, because only failing a read causes us to signal 'closed'.
952 /* if bytes_wanted is zero, it means start reading a message */
953 if (worker->read_buffer_bytes_wanted == 0)
955 worker->read_buffer_cur_size = 0;
956 worker->read_buffer_bytes_wanted = 16;
959 /* ensure we have a (big enough) buffer */
960 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
962 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
963 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
964 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
967 if (G_IS_KDBUS_CONNECTION (worker->stream))
973 _g_kdbus_read(worker->kdbus,
975 worker->read_buffer_bytes_wanted,
977 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
978 _g_dbus_worker_ref (worker));
981 } else if (worker->socket == NULL)
982 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
983 worker->read_buffer + worker->read_buffer_cur_size,
984 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
987 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
988 _g_dbus_worker_ref (worker));
991 worker->read_ancillary_messages = NULL;
992 worker->read_num_ancillary_messages = 0;
993 _g_socket_read_with_control_messages (worker->socket,
994 worker->read_buffer + worker->read_buffer_cur_size,
995 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
996 &worker->read_ancillary_messages,
997 &worker->read_num_ancillary_messages,
1000 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
1001 _g_dbus_worker_ref (worker));
1005 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
1007 _g_dbus_worker_do_initial_read (gpointer data)
1009 GDBusWorker *worker = data;
1010 g_mutex_lock (&worker->read_lock);
1011 _g_dbus_worker_do_read_unlocked (worker);
1012 g_mutex_unlock (&worker->read_lock);
1016 /* ---------------------------------------------------------------------------------------------------- */
1018 struct _MessageToWriteData
1020 GDBusWorker *worker;
1021 GDBusMessage *message;
1025 gsize total_written;
1026 GSimpleAsyncResult *simple;
1031 message_to_write_data_free (MessageToWriteData *data)
1033 _g_dbus_worker_unref (data->worker);
1035 g_object_unref (data->message);
1036 g_free (data->blob);
1040 /* ---------------------------------------------------------------------------------------------------- */
1042 static void write_message_continue_writing (MessageToWriteData *data);
1044 /* called in private thread shared by all GDBusConnection instances
1046 * write-lock is not held on entry
1047 * output_pending is PENDING_WRITE on entry
1050 write_message_async_cb (GObject *source_object,
1054 MessageToWriteData *data = user_data;
1055 GSimpleAsyncResult *simple;
1056 gssize bytes_written;
1059 /* Note: we can't access data->simple after calling g_async_result_complete () because the
1060 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
1062 simple = data->simple;
1065 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
1068 if (bytes_written == -1)
1070 g_simple_async_result_take_error (simple, error);
1071 g_simple_async_result_complete (simple);
1072 g_object_unref (simple);
1075 g_assert (bytes_written > 0); /* zero is never returned */
1077 write_message_print_transport_debug (bytes_written, data);
1079 data->total_written += bytes_written;
1080 g_assert (data->total_written <= data->blob_size);
1081 if (data->total_written == data->blob_size)
1083 g_simple_async_result_complete (simple);
1084 g_object_unref (simple);
1088 write_message_continue_writing (data);
1094 /* called in private thread shared by all GDBusConnection instances
1096 * write-lock is not held on entry
1097 * output_pending is PENDING_WRITE on entry
1101 on_socket_ready (GSocket *socket,
1102 GIOCondition condition,
1105 MessageToWriteData *data = user_data;
1106 write_message_continue_writing (data);
1107 return FALSE; /* remove source */
1111 /* called in private thread shared by all GDBusConnection instances
1113 * write-lock is not held on entry
1114 * output_pending is PENDING_WRITE on entry
1117 write_message_continue_writing (MessageToWriteData *data)
1120 GSimpleAsyncResult *simple;
1121 simple = data->simple;
1124 if (G_IS_KDBUS_CONNECTION (data->worker->stream))
1128 data->total_written = g_kdbus_send_message(data->worker, data->worker->kdbus, data->message, data->blob, data->blob_size, &error);
1130 write_message_print_transport_debug (data->total_written, data);
1131 g_simple_async_result_complete (simple);
1132 g_object_unref (simple);
1137 GOutputStream *ostream;
1139 GUnixFDList *fd_list;
1142 ostream = g_io_stream_get_output_stream (data->worker->stream);
1144 fd_list = g_dbus_message_get_unix_fd_list (data->message);
1147 g_assert (!g_output_stream_has_pending (ostream));
1148 g_assert_cmpint (data->total_written, <, data->blob_size);
1154 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
1156 GOutputVector vector;
1157 GSocketControlMessage *control_message;
1158 gssize bytes_written;
1161 vector.buffer = data->blob;
1162 vector.size = data->blob_size;
1164 control_message = NULL;
1165 if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
1167 if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
1169 g_simple_async_result_set_error (simple,
1172 "Tried sending a file descriptor but remote peer does not support this capability");
1173 g_simple_async_result_complete (simple);
1174 g_object_unref (simple);
1177 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1181 bytes_written = g_socket_send_message (data->worker->socket,
1185 control_message != NULL ? &control_message : NULL,
1186 control_message != NULL ? 1 : 0,
1188 data->worker->cancellable,
1190 if (control_message != NULL)
1191 g_object_unref (control_message);
1193 if (bytes_written == -1)
1195 /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1196 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1199 source = g_socket_create_source (data->worker->socket,
1200 G_IO_OUT | G_IO_HUP | G_IO_ERR,
1201 data->worker->cancellable);
1202 g_source_set_callback (source,
1203 (GSourceFunc) on_socket_ready,
1205 NULL); /* GDestroyNotify */
1206 g_source_attach (source, g_main_context_get_thread_default ());
1207 g_source_unref (source);
1208 g_error_free (error);
1211 g_simple_async_result_take_error (simple, error);
1212 g_simple_async_result_complete (simple);
1213 g_object_unref (simple);
1216 g_assert (bytes_written > 0); /* zero is never returned */
1218 write_message_print_transport_debug (bytes_written, data);
1220 data->total_written += bytes_written;
1221 g_assert (data->total_written <= data->blob_size);
1222 if (data->total_written == data->blob_size)
1224 g_simple_async_result_complete (simple);
1225 g_object_unref (simple);
1229 write_message_continue_writing (data);
1235 if (fd_list != NULL)
1237 g_simple_async_result_set_error (simple,
1240 "Tried sending a file descriptor on unsupported stream of type %s",
1241 g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1242 g_simple_async_result_complete (simple);
1243 g_object_unref (simple);
1248 g_output_stream_write_async (ostream,
1249 (const gchar *) data->blob + data->total_written,
1250 data->blob_size - data->total_written,
1252 data->worker->cancellable,
1253 write_message_async_cb,
1263 /* called in private thread shared by all GDBusConnection instances
1265 * write-lock is not held on entry
1266 * output_pending is PENDING_WRITE on entry
1269 write_message_async (GDBusWorker *worker,
1270 MessageToWriteData *data,
1271 GAsyncReadyCallback callback,
1274 data->simple = g_simple_async_result_new (NULL,
1277 write_message_async);
1278 data->total_written = 0;
1279 write_message_continue_writing (data);
1282 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1284 write_message_finish (GAsyncResult *res,
1287 g_warn_if_fail (g_simple_async_result_get_source_tag (G_SIMPLE_ASYNC_RESULT (res)) == write_message_async);
1288 if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error))
1293 /* ---------------------------------------------------------------------------------------------------- */
1295 static void continue_writing (GDBusWorker *worker);
1299 GDBusWorker *worker;
1304 flush_data_list_complete (const GList *flushers,
1305 const GError *error)
1309 for (l = flushers; l != NULL; l = l->next)
1311 FlushData *f = l->data;
1313 f->error = error != NULL ? g_error_copy (error) : NULL;
1315 g_mutex_lock (&f->mutex);
1316 g_cond_signal (&f->cond);
1317 g_mutex_unlock (&f->mutex);
1321 /* called in private thread shared by all GDBusConnection instances
1323 * write-lock is not held on entry
1324 * output_pending is PENDING_FLUSH on entry
1327 ostream_flush_cb (GObject *source_object,
1331 FlushAsyncData *data = user_data;
1335 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1341 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1343 _g_dbus_debug_print_lock ();
1344 g_print ("========================================================================\n"
1345 "GDBus-debug:Transport:\n"
1346 " ---- FLUSHED stream of type %s\n",
1347 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1348 _g_dbus_debug_print_unlock ();
1352 g_assert (data->flushers != NULL);
1353 flush_data_list_complete (data->flushers, error);
1354 g_list_free (data->flushers);
1357 g_error_free (error);
1359 /* Make sure we tell folks that we don't have additional
1361 g_mutex_lock (&data->worker->write_lock);
1362 data->worker->write_num_messages_flushed = data->worker->write_num_messages_written;
1363 g_assert (data->worker->output_pending == PENDING_FLUSH);
1364 data->worker->output_pending = PENDING_NONE;
1365 g_mutex_unlock (&data->worker->write_lock);
1367 /* OK, cool, finally kick off the next write */
1368 continue_writing (data->worker);
1370 _g_dbus_worker_unref (data->worker);
1374 /* called in private thread shared by all GDBusConnection instances
1376 * write-lock is not held on entry
1377 * output_pending is PENDING_FLUSH on entry
1380 start_flush (FlushAsyncData *data)
1382 g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1384 data->worker->cancellable,
1389 /* called in private thread shared by all GDBusConnection instances
1391 * write-lock is held on entry
1392 * output_pending is PENDING_NONE on entry
1395 message_written_unlocked (GDBusWorker *worker,
1396 MessageToWriteData *message_data)
1398 if (G_UNLIKELY (_g_dbus_debug_message ()))
1401 _g_dbus_debug_print_lock ();
1402 g_print ("========================================================================\n"
1403 "GDBus-debug:Message:\n"
1404 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1405 message_data->blob_size);
1406 s = g_dbus_message_print (message_data->message, 2);
1409 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1411 s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1412 g_print ("%s\n", s);
1415 _g_dbus_debug_print_unlock ();
1418 worker->write_num_messages_written += 1;
1421 /* called in private thread shared by all GDBusConnection instances
1423 * write-lock is held on entry
1424 * output_pending is PENDING_NONE on entry
1426 * Returns: non-%NULL, setting @output_pending, if we need to flush now
1428 static FlushAsyncData *
1429 prepare_flush_unlocked (GDBusWorker *worker)
1436 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1438 FlushData *f = l->data;
1441 if (f->number_to_wait_for == worker->write_num_messages_written)
1443 flushers = g_list_append (flushers, f);
1444 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1447 if (flushers != NULL)
1449 g_assert (worker->output_pending == PENDING_NONE);
1450 worker->output_pending = PENDING_FLUSH;
1453 if (flushers != NULL)
1455 FlushAsyncData *data;
1457 data = g_new0 (FlushAsyncData, 1);
1458 data->worker = _g_dbus_worker_ref (worker);
1459 data->flushers = flushers;
1466 /* called in private thread shared by all GDBusConnection instances
1468 * write-lock is not held on entry
1469 * output_pending is PENDING_WRITE on entry
1472 write_message_cb (GObject *source_object,
1476 MessageToWriteData *data = user_data;
1479 g_mutex_lock (&data->worker->write_lock);
1480 g_assert (data->worker->output_pending == PENDING_WRITE);
1481 data->worker->output_pending = PENDING_NONE;
1484 if (!write_message_finish (res, &error))
1486 g_mutex_unlock (&data->worker->write_lock);
1489 _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1490 g_error_free (error);
1492 g_mutex_lock (&data->worker->write_lock);
1495 message_written_unlocked (data->worker, data);
1497 g_mutex_unlock (&data->worker->write_lock);
1499 continue_writing (data->worker);
1501 message_to_write_data_free (data);
1504 /* called in private thread shared by all GDBusConnection instances
1506 * write-lock is not held on entry
1507 * output_pending is PENDING_CLOSE on entry
1510 iostream_close_cb (GObject *source_object,
1514 GDBusWorker *worker = user_data;
1515 GError *error = NULL;
1516 GList *pending_close_attempts, *pending_flush_attempts;
1519 g_io_stream_close_finish (worker->stream, res, &error);
1521 g_mutex_lock (&worker->write_lock);
1523 pending_close_attempts = worker->pending_close_attempts;
1524 worker->pending_close_attempts = NULL;
1526 pending_flush_attempts = worker->write_pending_flushes;
1527 worker->write_pending_flushes = NULL;
1529 send_queue = worker->write_queue;
1530 worker->write_queue = g_queue_new ();
1532 g_assert (worker->output_pending == PENDING_CLOSE);
1533 worker->output_pending = PENDING_NONE;
1535 g_mutex_unlock (&worker->write_lock);
1537 while (pending_close_attempts != NULL)
1539 CloseData *close_data = pending_close_attempts->data;
1541 pending_close_attempts = g_list_delete_link (pending_close_attempts,
1542 pending_close_attempts);
1544 if (close_data->result != NULL)
1547 g_simple_async_result_set_from_error (close_data->result, error);
1549 /* this must be in an idle because the result is likely to be
1550 * intended for another thread
1552 g_simple_async_result_complete_in_idle (close_data->result);
1555 close_data_free (close_data);
1558 g_clear_error (&error);
1560 /* all messages queued for sending are discarded */
1561 g_queue_free_full (send_queue, (GDestroyNotify) message_to_write_data_free);
1562 /* all queued flushes fail */
1563 error = g_error_new (G_IO_ERROR, G_IO_ERROR_CANCELLED,
1564 _("Operation was cancelled"));
1565 flush_data_list_complete (pending_flush_attempts, error);
1566 g_list_free (pending_flush_attempts);
1567 g_clear_error (&error);
1569 _g_dbus_worker_unref (worker);
1572 /* called in private thread shared by all GDBusConnection instances
1574 * write-lock is not held on entry
1575 * output_pending must be PENDING_NONE on entry
1578 continue_writing (GDBusWorker *worker)
1580 MessageToWriteData *data;
1581 FlushAsyncData *flush_async_data;
1584 /* we mustn't try to write two things at once */
1585 g_assert (worker->output_pending == PENDING_NONE);
1587 g_mutex_lock (&worker->write_lock);
1590 flush_async_data = NULL;
1592 /* if we want to close the connection, that takes precedence */
1593 if (worker->pending_close_attempts != NULL)
1595 worker->close_expected = TRUE;
1596 worker->output_pending = PENDING_CLOSE;
1598 g_io_stream_close_async (worker->stream, G_PRIORITY_DEFAULT,
1599 NULL, iostream_close_cb,
1600 _g_dbus_worker_ref (worker));
1604 flush_async_data = prepare_flush_unlocked (worker);
1606 if (flush_async_data == NULL)
1608 data = g_queue_pop_head (worker->write_queue);
1611 worker->output_pending = PENDING_WRITE;
1615 g_mutex_unlock (&worker->write_lock);
1617 /* Note that write_lock is only used for protecting the @write_queue
1618 * and @output_pending fields of the GDBusWorker struct ... which we
1619 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1621 * Therefore, it's fine to drop it here when calling back into user
1622 * code and then writing the message out onto the GIOStream since this
1623 * function only runs on the worker thread.
1626 if (flush_async_data != NULL)
1628 start_flush (flush_async_data);
1629 g_assert (data == NULL);
1631 else if (data != NULL)
1633 GDBusMessage *old_message;
1635 gsize new_blob_size;
1638 old_message = data->message;
1639 data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1640 if (data->message == old_message)
1642 /* filters had no effect - do nothing */
1644 else if (data->message == NULL)
1646 /* filters dropped message */
1647 g_mutex_lock (&worker->write_lock);
1648 worker->output_pending = PENDING_NONE;
1649 g_mutex_unlock (&worker->write_lock);
1650 message_to_write_data_free (data);
1655 /* filters altered the message -> reencode */
1657 new_blob = g_dbus_message_to_blob (data->message,
1659 worker->capabilities,
1661 if (new_blob == NULL)
1663 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1664 * the old message instead
1666 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1667 g_dbus_message_get_serial (data->message),
1669 g_error_free (error);
1673 g_free (data->blob);
1674 data->blob = (gchar *) new_blob;
1675 data->blob_size = new_blob_size;
1679 write_message_async (worker,
1686 /* called in private thread shared by all GDBusConnection instances
1688 * write-lock is not held on entry
1689 * output_pending may be anything
1692 continue_writing_in_idle_cb (gpointer user_data)
1694 GDBusWorker *worker = user_data;
1696 /* Because this is the worker thread, we can read this struct member
1697 * without holding the lock: no other thread ever modifies it.
1699 if (worker->output_pending == PENDING_NONE)
1700 continue_writing (worker);
1706 * @write_data: (transfer full) (allow-none):
1707 * @flush_data: (transfer full) (allow-none):
1708 * @close_data: (transfer full) (allow-none):
1710 * Can be called from any thread
1712 * write_lock is held on entry
1713 * output_pending may be anything
1716 schedule_writing_unlocked (GDBusWorker *worker,
1717 MessageToWriteData *write_data,
1718 FlushData *flush_data,
1719 CloseData *close_data)
1721 if (write_data != NULL)
1722 g_queue_push_tail (worker->write_queue, write_data);
1724 if (flush_data != NULL)
1725 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, flush_data);
1727 if (close_data != NULL)
1728 worker->pending_close_attempts = g_list_prepend (worker->pending_close_attempts,
1731 /* If we had output pending, the next bit of output will happen
1732 * automatically when it finishes, so we only need to do this
1733 * if nothing was pending.
1735 * The idle callback will re-check that output_pending is still
1736 * PENDING_NONE, to guard against output starting before the idle.
1738 if (worker->output_pending == PENDING_NONE)
1740 GSource *idle_source;
1741 idle_source = g_idle_source_new ();
1742 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1743 g_source_set_callback (idle_source,
1744 continue_writing_in_idle_cb,
1745 _g_dbus_worker_ref (worker),
1746 (GDestroyNotify) _g_dbus_worker_unref);
1747 g_source_attach (idle_source, worker->shared_thread_data->context);
1748 g_source_unref (idle_source);
1752 /* ---------------------------------------------------------------------------------------------------- */
1754 /* can be called from any thread - steals blob
1756 * write_lock is not held on entry
1757 * output_pending may be anything
1760 _g_dbus_worker_send_message (GDBusWorker *worker,
1761 GDBusMessage *message,
1765 MessageToWriteData *data;
1767 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1768 g_return_if_fail (blob != NULL);
1769 g_return_if_fail (blob_len > 16);
1771 data = g_new0 (MessageToWriteData, 1);
1772 data->worker = _g_dbus_worker_ref (worker);
1773 data->message = g_object_ref (message);
1774 data->blob = blob; /* steal! */
1775 data->blob_size = blob_len;
1777 g_mutex_lock (&worker->write_lock);
1778 schedule_writing_unlocked (worker, data, NULL, NULL);
1779 g_mutex_unlock (&worker->write_lock);
1782 /* ---------------------------------------------------------------------------------------------------- */
1783 GKdbus* g_dbus_worker_get_kdbus (GDBusWorker *worker)
1785 return worker->kdbus;
1789 _g_dbus_worker_new (GIOStream *stream,
1790 GDBusCapabilityFlags capabilities,
1791 gboolean initially_frozen,
1792 GDBusWorkerMessageReceivedCallback message_received_callback,
1793 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1794 GDBusWorkerDisconnectedCallback disconnected_callback,
1797 GDBusWorker *worker;
1798 GSource *idle_source;
1800 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1801 g_return_val_if_fail (message_received_callback != NULL, NULL);
1802 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1803 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1805 worker = g_new0 (GDBusWorker, 1);
1806 worker->ref_count = 1;
1808 g_mutex_init (&worker->read_lock);
1809 worker->message_received_callback = message_received_callback;
1810 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1811 worker->disconnected_callback = disconnected_callback;
1812 worker->user_data = user_data;
1813 worker->stream = g_object_ref (stream);
1814 worker->capabilities = capabilities;
1815 worker->cancellable = g_cancellable_new ();
1816 worker->output_pending = PENDING_NONE;
1818 worker->frozen = initially_frozen;
1819 worker->received_messages_while_frozen = g_queue_new ();
1821 g_mutex_init (&worker->write_lock);
1822 worker->write_queue = g_queue_new ();
1824 if (G_IS_SOCKET_CONNECTION (worker->stream))
1825 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1827 if (G_IS_KDBUS_CONNECTION (worker->stream))
1828 worker->kdbus = g_kdbus_connection_get_kdbus (G_KDBUS_CONNECTION (worker->stream));
1830 worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1833 idle_source = g_idle_source_new ();
1834 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1835 g_source_set_callback (idle_source,
1836 _g_dbus_worker_do_initial_read,
1837 _g_dbus_worker_ref (worker),
1838 (GDestroyNotify) _g_dbus_worker_unref);
1839 g_source_attach (idle_source, worker->shared_thread_data->context);
1840 g_source_unref (idle_source);
1845 /* ---------------------------------------------------------------------------------------------------- */
1847 /* can be called from any thread
1849 * write_lock is not held on entry
1850 * output_pending may be anything
1853 _g_dbus_worker_close (GDBusWorker *worker,
1854 GCancellable *cancellable,
1855 GSimpleAsyncResult *result)
1857 CloseData *close_data;
1859 close_data = g_slice_new0 (CloseData);
1860 close_data->worker = _g_dbus_worker_ref (worker);
1861 close_data->cancellable =
1862 (cancellable == NULL ? NULL : g_object_ref (cancellable));
1863 close_data->result = (result == NULL ? NULL : g_object_ref (result));
1865 /* Don't set worker->close_expected here - we're in the wrong thread.
1866 * It'll be set before the actual close happens.
1868 g_cancellable_cancel (worker->cancellable);
1869 g_mutex_lock (&worker->write_lock);
1870 schedule_writing_unlocked (worker, NULL, NULL, close_data);
1871 g_mutex_unlock (&worker->write_lock);
1874 /* This can be called from any thread - frees worker. Note that
1875 * callbacks might still happen if called from another thread than the
1876 * worker - use your own synchronization primitive in the callbacks.
1878 * write_lock is not held on entry
1879 * output_pending may be anything
1882 _g_dbus_worker_stop (GDBusWorker *worker)
1884 g_atomic_int_set (&worker->stopped, TRUE);
1886 /* Cancel any pending operations and schedule a close of the underlying I/O
1887 * stream in the worker thread
1889 _g_dbus_worker_close (worker, NULL, NULL);
1891 /* _g_dbus_worker_close holds a ref until after an idle in the worker
1892 * thread has run, so we no longer need to unref in an idle like in
1895 _g_dbus_worker_unref (worker);
1898 /* ---------------------------------------------------------------------------------------------------- */
1900 /* can be called from any thread (except the worker thread) - blocks
1901 * calling thread until all queued outgoing messages are written and
1902 * the transport has been flushed
1904 * write_lock is not held on entry
1905 * output_pending may be anything
1908 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1909 GCancellable *cancellable,
1914 guint64 pending_writes;
1919 g_mutex_lock (&worker->write_lock);
1921 /* if the queue is empty, no write is in-flight and we haven't written
1922 * anything since the last flush, then there's nothing to wait for
1924 pending_writes = g_queue_get_length (worker->write_queue);
1926 /* if a write is in-flight, we shouldn't be satisfied until the first
1927 * flush operation that follows it
1929 if (worker->output_pending == PENDING_WRITE)
1930 pending_writes += 1;
1932 if (pending_writes > 0 ||
1933 worker->write_num_messages_written != worker->write_num_messages_flushed)
1935 data = g_new0 (FlushData, 1);
1936 g_mutex_init (&data->mutex);
1937 g_cond_init (&data->cond);
1938 data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
1939 g_mutex_lock (&data->mutex);
1941 schedule_writing_unlocked (worker, NULL, data, NULL);
1943 g_mutex_unlock (&worker->write_lock);
1947 g_cond_wait (&data->cond, &data->mutex);
1948 g_mutex_unlock (&data->mutex);
1950 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1951 g_cond_clear (&data->cond);
1952 g_mutex_clear (&data->mutex);
1953 if (data->error != NULL)
1956 g_propagate_error (error, data->error);
1964 /* ---------------------------------------------------------------------------------------------------- */
1966 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1967 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1968 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1969 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1970 #define G_DBUS_DEBUG_CALL (1<<4)
1971 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1972 #define G_DBUS_DEBUG_INCOMING (1<<6)
1973 #define G_DBUS_DEBUG_RETURN (1<<7)
1974 #define G_DBUS_DEBUG_EMISSION (1<<8)
1975 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1977 static gint _gdbus_debug_flags = 0;
1980 _g_dbus_debug_authentication (void)
1982 _g_dbus_initialize ();
1983 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1987 _g_dbus_debug_transport (void)
1989 _g_dbus_initialize ();
1990 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1994 _g_dbus_debug_message (void)
1996 _g_dbus_initialize ();
1997 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
2001 _g_dbus_debug_payload (void)
2003 _g_dbus_initialize ();
2004 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
2008 _g_dbus_debug_call (void)
2010 _g_dbus_initialize ();
2011 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
2015 _g_dbus_debug_signal (void)
2017 _g_dbus_initialize ();
2018 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
2022 _g_dbus_debug_incoming (void)
2024 _g_dbus_initialize ();
2025 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
2029 _g_dbus_debug_return (void)
2031 _g_dbus_initialize ();
2032 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
2036 _g_dbus_debug_emission (void)
2038 _g_dbus_initialize ();
2039 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
2043 _g_dbus_debug_address (void)
2045 _g_dbus_initialize ();
2046 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
2049 G_LOCK_DEFINE_STATIC (print_lock);
2052 _g_dbus_debug_print_lock (void)
2054 G_LOCK (print_lock);
2058 _g_dbus_debug_print_unlock (void)
2060 G_UNLOCK (print_lock);
2064 * _g_dbus_initialize:
2066 * Does various one-time init things such as
2068 * - registering the G_DBUS_ERROR error domain
2069 * - parses the G_DBUS_DEBUG environment variable
2072 _g_dbus_initialize (void)
2074 static volatile gsize initialized = 0;
2076 if (g_once_init_enter (&initialized))
2078 volatile GQuark g_dbus_error_domain;
2081 g_dbus_error_domain = G_DBUS_ERROR;
2082 (g_dbus_error_domain); /* To avoid -Wunused-but-set-variable */
2084 debug = g_getenv ("G_DBUS_DEBUG");
2087 const GDebugKey keys[] = {
2088 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
2089 { "transport", G_DBUS_DEBUG_TRANSPORT },
2090 { "message", G_DBUS_DEBUG_MESSAGE },
2091 { "payload", G_DBUS_DEBUG_PAYLOAD },
2092 { "call", G_DBUS_DEBUG_CALL },
2093 { "signal", G_DBUS_DEBUG_SIGNAL },
2094 { "incoming", G_DBUS_DEBUG_INCOMING },
2095 { "return", G_DBUS_DEBUG_RETURN },
2096 { "emission", G_DBUS_DEBUG_EMISSION },
2097 { "address", G_DBUS_DEBUG_ADDRESS }
2100 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
2101 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
2102 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
2105 g_once_init_leave (&initialized, 1);
2109 /* ---------------------------------------------------------------------------------------------------- */
2112 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
2114 const GVariantType *arg_types[256];
2118 for (n = 0; args[n] != NULL; n++)
2120 /* DBus places a hard limit of 255 on signature length.
2121 * therefore number of args must be less than 256.
2125 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
2127 if G_UNLIKELY (arg_types[n] == NULL)
2133 return g_variant_type_new_tuple (arg_types, n);
2136 /* ---------------------------------------------------------------------------------------------------- */
2140 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
2143 _g_dbus_win32_get_user_sid (void)
2147 DWORD token_information_len;
2154 h = INVALID_HANDLE_VALUE;
2156 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
2158 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
2162 /* Get length of buffer */
2163 token_information_len = 0;
2164 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
2166 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
2168 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2172 user = g_malloc (token_information_len);
2173 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
2175 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
2179 psid = user->User.Sid;
2180 if (!IsValidSid (psid))
2182 g_warning ("Invalid SID");
2186 if (!ConvertSidToStringSidA (psid, &sid))
2188 g_warning ("Invalid SID");
2192 ret = g_strdup (sid);
2197 if (h != INVALID_HANDLE_VALUE)
2203 /* ---------------------------------------------------------------------------------------------------- */
2206 _g_dbus_get_machine_id (GError **error)
2209 HW_PROFILE_INFOA info;
2210 char *src, *dest, *res;
2213 if (!GetCurrentHwProfileA (&info))
2215 char *message = g_win32_error_message (GetLastError ());
2219 _("Unable to get Hardware profile: %s"), message);
2224 /* Form: {12340001-4980-1920-6788-123456789012} */
2225 src = &info.szHwProfileGuid[0];
2227 res = g_malloc (32+1);
2231 for (i = 0; i < 8; i++)
2234 for (i = 0; i < 4; i++)
2237 for (i = 0; i < 4; i++)
2240 for (i = 0; i < 4; i++)
2243 for (i = 0; i < 12; i++)
2250 GError *first_error;
2251 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2254 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2258 !g_file_get_contents ("/etc/machine-id",
2263 g_propagate_prefixed_error (error, first_error,
2264 _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2268 /* ignore the error from the first try, if any */
2269 g_clear_error (&first_error);
2270 /* TODO: validate value */
2277 /* ---------------------------------------------------------------------------------------------------- */
2280 _g_dbus_enum_to_string (GType enum_type, gint value)
2284 GEnumValue *enum_value;
2286 klass = g_type_class_ref (enum_type);
2287 enum_value = g_enum_get_value (klass, value);
2288 if (enum_value != NULL)
2289 ret = g_strdup (enum_value->value_nick);
2291 ret = g_strdup_printf ("unknown (value %d)", value);
2292 g_type_class_unref (klass);
2296 /* ---------------------------------------------------------------------------------------------------- */
2299 write_message_print_transport_debug (gssize bytes_written,
2300 MessageToWriteData *data)
2302 if (G_LIKELY (!_g_dbus_debug_transport ()))
2305 _g_dbus_debug_print_lock ();
2306 g_print ("========================================================================\n"
2307 "GDBus-debug:Transport:\n"
2308 " >>>> WROTE %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2309 " size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
2311 g_dbus_message_get_serial (data->message),
2313 data->total_written,
2314 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
2315 _g_dbus_debug_print_unlock ();
2320 /* ---------------------------------------------------------------------------------------------------- */
2323 read_message_print_transport_debug (gssize bytes_read,
2324 GDBusWorker *worker)
2328 gint32 message_length;
2330 if (G_LIKELY (!_g_dbus_debug_transport ()))
2333 size = bytes_read + worker->read_buffer_cur_size;
2337 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2340 switch (worker->read_buffer[0])
2344 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2348 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2351 /* an error will be set elsewhere if this happens */
2356 _g_dbus_debug_print_lock ();
2357 g_print ("========================================================================\n"
2358 "GDBus-debug:Transport:\n"
2359 " <<<< READ %" G_GSIZE_FORMAT " bytes of message with serial %d and\n"
2360 " size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
2364 worker->read_buffer_cur_size,
2365 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
2366 _g_dbus_debug_print_unlock ();
2371 /* ---------------------------------------------------------------------------------------------------- */
2374 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2375 GValue *return_accu,
2376 const GValue *handler_return,
2379 gboolean continue_emission;
2380 gboolean signal_return;
2382 signal_return = g_value_get_boolean (handler_return);
2383 g_value_set_boolean (return_accu, signal_return);
2384 continue_emission = signal_return;
2386 return continue_emission;