1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
27 #include "gioenumtypes.h"
29 #include "gdbusauthobserver.h"
30 #include "gdbusprivate.h"
31 #include "gdbusmessage.h"
32 #include "gdbusconnection.h"
33 #include "gdbusproxy.h"
34 #include "gdbuserror.h"
35 #include "gdbusintrospection.h"
37 #include "ginputstream.h"
38 #include "gmemoryinputstream.h"
39 #include "giostream.h"
40 #include "glib/gstdio.h"
41 #include "gsocketaddress.h"
42 #include "gsocketcontrolmessage.h"
43 #include "gsocketconnection.h"
44 #include "gsocketoutputstream.h"
47 #include "gunixfdmessage.h"
48 #include "gunixconnection.h"
49 #include "gunixcredentialsmessage.h"
58 static gboolean
_g_dbus_worker_do_initial_read (gpointer data
);
59 static void schedule_pending_close (GDBusWorker
*worker
);
61 /* ---------------------------------------------------------------------------------------------------- */
64 _g_dbus_hexdump (const gchar
*data
, gsize len
, guint indent
)
69 ret
= g_string_new (NULL
);
71 for (n
= 0; n
< len
; n
+= 16)
73 g_string_append_printf (ret
, "%*s%04x: ", indent
, "", n
);
75 for (m
= n
; m
< n
+ 16; m
++)
77 if (m
> n
&& (m
%4) == 0)
78 g_string_append_c (ret
, ' ');
80 g_string_append_printf (ret
, "%02x ", (guchar
) data
[m
]);
82 g_string_append (ret
, " ");
85 g_string_append (ret
, " ");
87 for (m
= n
; m
< len
&& m
< n
+ 16; m
++)
88 g_string_append_c (ret
, g_ascii_isprint (data
[m
]) ? data
[m
] : '.');
90 g_string_append_c (ret
, '\n');
93 return g_string_free (ret
, FALSE
);
96 /* ---------------------------------------------------------------------------------------------------- */
98 /* Unfortunately ancillary messages are discarded when reading from a
99 * socket using the GSocketInputStream abstraction. So we provide a
100 * very GInputStream-ish API that uses GSocket in this case (very
101 * similar to GSocketInputStream).
109 GSocketControlMessage
***messages
;
111 } ReadWithControlData
;
114 read_with_control_data_free (ReadWithControlData
*data
)
116 g_slice_free (ReadWithControlData
, data
);
120 _g_socket_read_with_control_messages_ready (GSocket
*socket
,
121 GIOCondition condition
,
124 GTask
*task
= user_data
;
125 ReadWithControlData
*data
= g_task_get_task_data (task
);
131 vector
.buffer
= data
->buffer
;
132 vector
.size
= data
->count
;
133 result
= g_socket_receive_message (socket
,
140 g_task_get_cancellable (task
),
143 if (g_error_matches (error
, G_IO_ERROR
, G_IO_ERROR_WOULD_BLOCK
))
145 g_error_free (error
);
149 g_assert (result
>= 0 || error
!= NULL
);
151 g_task_return_int (task
, result
);
153 g_task_return_error (task
, error
);
154 g_object_unref (task
);
160 _g_socket_read_with_control_messages (GSocket
*socket
,
163 GSocketControlMessage
***messages
,
166 GCancellable
*cancellable
,
167 GAsyncReadyCallback callback
,
171 ReadWithControlData
*data
;
174 data
= g_slice_new0 (ReadWithControlData
);
175 data
->buffer
= buffer
;
177 data
->messages
= messages
;
178 data
->num_messages
= num_messages
;
180 task
= g_task_new (socket
, cancellable
, callback
, user_data
);
181 g_task_set_source_tag (task
, _g_socket_read_with_control_messages
);
182 g_task_set_task_data (task
, data
, (GDestroyNotify
) read_with_control_data_free
);
184 if (g_socket_condition_check (socket
, G_IO_IN
))
186 if (!_g_socket_read_with_control_messages_ready (socket
, G_IO_IN
, task
))
190 source
= g_socket_create_source (socket
,
191 G_IO_IN
| G_IO_HUP
| G_IO_ERR
,
193 g_task_attach_source (task
, source
, (GSourceFunc
) _g_socket_read_with_control_messages_ready
);
194 g_source_unref (source
);
198 _g_socket_read_with_control_messages_finish (GSocket
*socket
,
199 GAsyncResult
*result
,
202 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
203 g_return_val_if_fail (g_task_is_valid (result
, socket
), -1);
205 return g_task_propagate_int (G_TASK (result
), error
);
208 /* ---------------------------------------------------------------------------------------------------- */
210 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=674885
211 and see also the original https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
213 static GPtrArray
*ensured_classes
= NULL
;
216 ensure_type (GType gtype
)
218 g_ptr_array_add (ensured_classes
, g_type_class_ref (gtype
));
222 release_required_types (void)
224 g_ptr_array_foreach (ensured_classes
, (GFunc
) g_type_class_unref
, NULL
);
225 g_ptr_array_unref (ensured_classes
);
226 ensured_classes
= NULL
;
230 ensure_required_types (void)
232 g_assert (ensured_classes
== NULL
);
233 ensured_classes
= g_ptr_array_new ();
234 /* Generally in this list, you should initialize types which are used as
235 * properties first, then the class which has them. For example, GDBusProxy
236 * has a type of GDBusConnection, so we initialize GDBusConnection first.
237 * And because GDBusConnection has a property of type GDBusConnectionFlags,
238 * we initialize that first.
240 * Similarly, GSocket has a type of GSocketAddress.
242 * We don't fill out the whole dependency tree right now because in practice
243 * it tends to be just types that GDBus use that cause pain, and there
244 * is work on a more general approach in https://bugzilla.gnome.org/show_bug.cgi?id=674885
246 ensure_type (G_TYPE_TASK
);
247 ensure_type (G_TYPE_MEMORY_INPUT_STREAM
);
248 ensure_type (G_TYPE_DBUS_CONNECTION_FLAGS
);
249 ensure_type (G_TYPE_DBUS_CAPABILITY_FLAGS
);
250 ensure_type (G_TYPE_DBUS_AUTH_OBSERVER
);
251 ensure_type (G_TYPE_DBUS_CONNECTION
);
252 ensure_type (G_TYPE_DBUS_PROXY
);
253 ensure_type (G_TYPE_SOCKET_FAMILY
);
254 ensure_type (G_TYPE_SOCKET_TYPE
);
255 ensure_type (G_TYPE_SOCKET_PROTOCOL
);
256 ensure_type (G_TYPE_SOCKET_ADDRESS
);
257 ensure_type (G_TYPE_SOCKET
);
259 /* ---------------------------------------------------------------------------------------------------- */
263 volatile gint refcount
;
265 GMainContext
*context
;
270 gdbus_shared_thread_func (gpointer user_data
)
272 SharedThreadData
*data
= user_data
;
274 g_main_context_push_thread_default (data
->context
);
275 g_main_loop_run (data
->loop
);
276 g_main_context_pop_thread_default (data
->context
);
278 release_required_types ();
283 /* ---------------------------------------------------------------------------------------------------- */
285 static SharedThreadData
*
286 _g_dbus_shared_thread_ref (void)
288 static gsize shared_thread_data
= 0;
289 SharedThreadData
*ret
;
291 if (g_once_init_enter (&shared_thread_data
))
293 SharedThreadData
*data
;
295 data
= g_new0 (SharedThreadData
, 1);
298 data
->context
= g_main_context_new ();
299 data
->loop
= g_main_loop_new (data
->context
, FALSE
);
300 data
->thread
= g_thread_new ("gdbus",
301 gdbus_shared_thread_func
,
303 /* We can cast between gsize and gpointer safely */
304 g_once_init_leave (&shared_thread_data
, (gsize
) data
);
307 ret
= (SharedThreadData
*) shared_thread_data
;
308 g_atomic_int_inc (&ret
->refcount
);
313 _g_dbus_shared_thread_unref (SharedThreadData
*data
)
315 /* TODO: actually destroy the shared thread here */
317 g_assert (data
!= NULL
);
318 if (g_atomic_int_dec_and_test (&data
->refcount
))
320 g_main_loop_quit (data
->loop
);
321 //g_thread_join (data->thread);
322 g_main_loop_unref (data
->loop
);
323 g_main_context_unref (data
->context
);
328 /* ---------------------------------------------------------------------------------------------------- */
339 volatile gint ref_count
;
341 SharedThreadData
*shared_thread_data
;
343 /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
344 volatile gint stopped
;
346 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
347 * only affects messages received from the other peer (since GDBusServer is the
348 * only user) - we might want it to affect messages sent to the other peer too?
351 GDBusCapabilityFlags capabilities
;
352 GQueue
*received_messages_while_frozen
;
355 GCancellable
*cancellable
;
356 GDBusWorkerMessageReceivedCallback message_received_callback
;
357 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback
;
358 GDBusWorkerDisconnectedCallback disconnected_callback
;
361 /* if not NULL, stream is GSocketConnection */
364 /* used for reading */
367 gsize read_buffer_allocated_size
;
368 gsize read_buffer_cur_size
;
369 gsize read_buffer_bytes_wanted
;
370 GUnixFDList
*read_fd_list
;
371 GSocketControlMessage
**read_ancillary_messages
;
372 gint read_num_ancillary_messages
;
374 /* Whether an async write, flush or close, or none of those, is pending.
375 * Only the worker thread may change its value, and only with the write_lock.
376 * Other threads may read its value when holding the write_lock.
377 * The worker thread may read its value at any time.
379 OutputPending output_pending
;
380 /* used for writing */
382 /* queue of MessageToWriteData, protected by write_lock */
384 /* protected by write_lock */
385 guint64 write_num_messages_written
;
386 /* number of messages we'd written out last time we flushed;
387 * protected by write_lock
389 guint64 write_num_messages_flushed
;
390 /* list of FlushData, protected by write_lock */
391 GList
*write_pending_flushes
;
392 /* list of CloseData, protected by write_lock */
393 GList
*pending_close_attempts
;
394 /* no lock - only used from the worker thread */
395 gboolean close_expected
;
398 static void _g_dbus_worker_unref (GDBusWorker
*worker
);
400 /* ---------------------------------------------------------------------------------------------------- */
406 guint64 number_to_wait_for
;
410 struct _MessageToWriteData
;
411 typedef struct _MessageToWriteData MessageToWriteData
;
413 static void message_to_write_data_free (MessageToWriteData
*data
);
415 static void read_message_print_transport_debug (gssize bytes_read
,
416 GDBusWorker
*worker
);
418 static void write_message_print_transport_debug (gssize bytes_written
,
419 MessageToWriteData
*data
);
426 static void close_data_free (CloseData
*close_data
)
428 g_clear_object (&close_data
->task
);
430 _g_dbus_worker_unref (close_data
->worker
);
431 g_slice_free (CloseData
, close_data
);
434 /* ---------------------------------------------------------------------------------------------------- */
437 _g_dbus_worker_ref (GDBusWorker
*worker
)
439 g_atomic_int_inc (&worker
->ref_count
);
444 _g_dbus_worker_unref (GDBusWorker
*worker
)
446 if (g_atomic_int_dec_and_test (&worker
->ref_count
))
448 g_assert (worker
->write_pending_flushes
== NULL
);
450 _g_dbus_shared_thread_unref (worker
->shared_thread_data
);
452 g_object_unref (worker
->stream
);
454 g_mutex_clear (&worker
->read_lock
);
455 g_object_unref (worker
->cancellable
);
456 if (worker
->read_fd_list
!= NULL
)
457 g_object_unref (worker
->read_fd_list
);
459 g_queue_free_full (worker
->received_messages_while_frozen
, (GDestroyNotify
) g_object_unref
);
460 g_mutex_clear (&worker
->write_lock
);
461 g_queue_free_full (worker
->write_queue
, (GDestroyNotify
) message_to_write_data_free
);
462 g_free (worker
->read_buffer
);
469 _g_dbus_worker_emit_disconnected (GDBusWorker
*worker
,
470 gboolean remote_peer_vanished
,
473 if (!g_atomic_int_get (&worker
->stopped
))
474 worker
->disconnected_callback (worker
, remote_peer_vanished
, error
, worker
->user_data
);
478 _g_dbus_worker_emit_message_received (GDBusWorker
*worker
,
479 GDBusMessage
*message
)
481 if (!g_atomic_int_get (&worker
->stopped
))
482 worker
->message_received_callback (worker
, message
, worker
->user_data
);
485 static GDBusMessage
*
486 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker
*worker
,
487 GDBusMessage
*message
)
490 if (!g_atomic_int_get (&worker
->stopped
))
491 ret
= worker
->message_about_to_be_sent_callback (worker
, message
, worker
->user_data
);
497 /* can only be called from private thread with read-lock held - takes ownership of @message */
499 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker
*worker
,
500 GDBusMessage
*message
)
502 if (worker
->frozen
|| g_queue_get_length (worker
->received_messages_while_frozen
) > 0)
505 g_queue_push_tail (worker
->received_messages_while_frozen
, message
);
509 /* not frozen, nor anything in queue */
510 _g_dbus_worker_emit_message_received (worker
, message
);
511 g_object_unref (message
);
515 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
517 unfreeze_in_idle_cb (gpointer user_data
)
519 GDBusWorker
*worker
= user_data
;
520 GDBusMessage
*message
;
522 g_mutex_lock (&worker
->read_lock
);
525 while ((message
= g_queue_pop_head (worker
->received_messages_while_frozen
)) != NULL
)
527 _g_dbus_worker_emit_message_received (worker
, message
);
528 g_object_unref (message
);
530 worker
->frozen
= FALSE
;
534 g_assert (g_queue_get_length (worker
->received_messages_while_frozen
) == 0);
536 g_mutex_unlock (&worker
->read_lock
);
540 /* can be called from any thread */
542 _g_dbus_worker_unfreeze (GDBusWorker
*worker
)
544 GSource
*idle_source
;
545 idle_source
= g_idle_source_new ();
546 g_source_set_priority (idle_source
, G_PRIORITY_DEFAULT
);
547 g_source_set_callback (idle_source
,
549 _g_dbus_worker_ref (worker
),
550 (GDestroyNotify
) _g_dbus_worker_unref
);
551 g_source_set_name (idle_source
, "[gio] unfreeze_in_idle_cb");
552 g_source_attach (idle_source
, worker
->shared_thread_data
->context
);
553 g_source_unref (idle_source
);
556 /* ---------------------------------------------------------------------------------------------------- */
558 static void _g_dbus_worker_do_read_unlocked (GDBusWorker
*worker
);
560 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
562 _g_dbus_worker_do_read_cb (GInputStream
*input_stream
,
566 GDBusWorker
*worker
= user_data
;
570 g_mutex_lock (&worker
->read_lock
);
572 /* If already stopped, don't even process the reply */
573 if (g_atomic_int_get (&worker
->stopped
))
577 if (worker
->socket
== NULL
)
578 bytes_read
= g_input_stream_read_finish (g_io_stream_get_input_stream (worker
->stream
),
582 bytes_read
= _g_socket_read_with_control_messages_finish (worker
->socket
,
585 if (worker
->read_num_ancillary_messages
> 0)
588 for (n
= 0; n
< worker
->read_num_ancillary_messages
; n
++)
590 GSocketControlMessage
*control_message
= G_SOCKET_CONTROL_MESSAGE (worker
->read_ancillary_messages
[n
]);
596 else if (G_IS_UNIX_FD_MESSAGE (control_message
))
598 GUnixFDMessage
*fd_message
;
602 fd_message
= G_UNIX_FD_MESSAGE (control_message
);
603 fds
= g_unix_fd_message_steal_fds (fd_message
, &num_fds
);
604 if (worker
->read_fd_list
== NULL
)
606 worker
->read_fd_list
= g_unix_fd_list_new_from_array (fds
, num_fds
);
611 for (n
= 0; n
< num_fds
; n
++)
613 /* TODO: really want a append_steal() */
614 g_unix_fd_list_append (worker
->read_fd_list
, fds
[n
], NULL
);
615 (void) g_close (fds
[n
], NULL
);
620 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message
))
632 "Unexpected ancillary message of type %s received from peer",
633 g_type_name (G_TYPE_FROM_INSTANCE (control_message
)));
634 _g_dbus_worker_emit_disconnected (worker
, TRUE
, error
);
635 g_error_free (error
);
636 g_object_unref (control_message
);
638 while (n
< worker
->read_num_ancillary_messages
)
639 g_object_unref (worker
->read_ancillary_messages
[n
++]);
640 g_free (worker
->read_ancillary_messages
);
644 g_object_unref (control_message
);
646 g_free (worker
->read_ancillary_messages
);
649 if (bytes_read
== -1)
651 if (G_UNLIKELY (_g_dbus_debug_transport ()))
653 _g_dbus_debug_print_lock ();
654 g_print ("========================================================================\n"
655 "GDBus-debug:Transport:\n"
656 " ---- READ ERROR on stream of type %s:\n"
658 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker
->stream
))),
659 g_quark_to_string (error
->domain
), error
->code
,
661 _g_dbus_debug_print_unlock ();
664 /* Every async read that uses this callback uses worker->cancellable
665 * as its GCancellable. worker->cancellable gets cancelled if and only
666 * if the GDBusConnection tells us to close (either via
667 * _g_dbus_worker_stop, which is called on last-unref, or directly),
668 * so a cancelled read must mean our connection was closed locally.
670 * If we're closing, other errors are possible - notably,
671 * G_IO_ERROR_CLOSED can be seen if we close the stream with an async
672 * read in-flight. It seems sensible to treat all read errors during
673 * closing as an expected thing that doesn't trip exit-on-close.
675 * Because close_expected can't be set until we get into the worker
676 * thread, but the cancellable is signalled sooner (from another
677 * thread), we do still need to check the error.
679 if (worker
->close_expected
||
680 g_error_matches (error
, G_IO_ERROR
, G_IO_ERROR_CANCELLED
))
681 _g_dbus_worker_emit_disconnected (worker
, FALSE
, NULL
);
683 _g_dbus_worker_emit_disconnected (worker
, TRUE
, error
);
685 g_error_free (error
);
690 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
692 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker
->stream
))),
693 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker
->stream
))),
694 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker
->stream
)),
695 G_IO_IN
| G_IO_OUT
| G_IO_HUP
),
700 /* TODO: hmm, hmm... */
706 "Underlying GIOStream returned 0 bytes on an async read");
707 _g_dbus_worker_emit_disconnected (worker
, TRUE
, error
);
708 g_error_free (error
);
712 read_message_print_transport_debug (bytes_read
, worker
);
714 worker
->read_buffer_cur_size
+= bytes_read
;
715 if (worker
->read_buffer_bytes_wanted
== worker
->read_buffer_cur_size
)
717 /* OK, got what we asked for! */
718 if (worker
->read_buffer_bytes_wanted
== 16)
721 /* OK, got the header - determine how many more bytes are needed */
723 message_len
= g_dbus_message_bytes_needed ((guchar
*) worker
->read_buffer
,
726 if (message_len
== -1)
728 g_warning ("_g_dbus_worker_do_read_cb: error determining bytes needed: %s", error
->message
);
729 _g_dbus_worker_emit_disconnected (worker
, FALSE
, error
);
730 g_error_free (error
);
734 worker
->read_buffer_bytes_wanted
= message_len
;
735 _g_dbus_worker_do_read_unlocked (worker
);
739 GDBusMessage
*message
;
742 /* TODO: use connection->priv->auth to decode the message */
744 message
= g_dbus_message_new_from_blob ((guchar
*) worker
->read_buffer
,
745 worker
->read_buffer_cur_size
,
746 worker
->capabilities
,
751 s
= _g_dbus_hexdump (worker
->read_buffer
, worker
->read_buffer_cur_size
, 2);
752 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT
" bytes\n"
754 "The payload is as follows:\n"
756 worker
->read_buffer_cur_size
,
760 _g_dbus_worker_emit_disconnected (worker
, FALSE
, error
);
761 g_error_free (error
);
766 if (worker
->read_fd_list
!= NULL
)
768 g_dbus_message_set_unix_fd_list (message
, worker
->read_fd_list
);
769 g_object_unref (worker
->read_fd_list
);
770 worker
->read_fd_list
= NULL
;
774 if (G_UNLIKELY (_g_dbus_debug_message ()))
777 _g_dbus_debug_print_lock ();
778 g_print ("========================================================================\n"
779 "GDBus-debug:Message:\n"
780 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT
" bytes)\n",
781 worker
->read_buffer_cur_size
);
782 s
= g_dbus_message_print (message
, 2);
785 if (G_UNLIKELY (_g_dbus_debug_payload ()))
787 s
= _g_dbus_hexdump (worker
->read_buffer
, worker
->read_buffer_cur_size
, 2);
791 _g_dbus_debug_print_unlock ();
794 /* yay, got a message, go deliver it */
795 _g_dbus_worker_queue_or_deliver_received_message (worker
, message
);
797 /* start reading another message! */
798 worker
->read_buffer_bytes_wanted
= 0;
799 worker
->read_buffer_cur_size
= 0;
800 _g_dbus_worker_do_read_unlocked (worker
);
805 /* didn't get all the bytes we requested - so repeat the request... */
806 _g_dbus_worker_do_read_unlocked (worker
);
810 g_mutex_unlock (&worker
->read_lock
);
812 /* gives up the reference acquired when calling g_input_stream_read_async() */
813 _g_dbus_worker_unref (worker
);
815 /* check if there is any pending close */
816 schedule_pending_close (worker
);
819 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
821 _g_dbus_worker_do_read_unlocked (GDBusWorker
*worker
)
823 /* Note that we do need to keep trying to read even if close_expected is
824 * true, because only failing a read causes us to signal 'closed'.
827 /* if bytes_wanted is zero, it means start reading a message */
828 if (worker
->read_buffer_bytes_wanted
== 0)
830 worker
->read_buffer_cur_size
= 0;
831 worker
->read_buffer_bytes_wanted
= 16;
834 /* ensure we have a (big enough) buffer */
835 if (worker
->read_buffer
== NULL
|| worker
->read_buffer_bytes_wanted
> worker
->read_buffer_allocated_size
)
837 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
838 worker
->read_buffer_allocated_size
= MAX (worker
->read_buffer_bytes_wanted
, 4096);
839 worker
->read_buffer
= g_realloc (worker
->read_buffer
, worker
->read_buffer_allocated_size
);
842 if (worker
->socket
== NULL
)
843 g_input_stream_read_async (g_io_stream_get_input_stream (worker
->stream
),
844 worker
->read_buffer
+ worker
->read_buffer_cur_size
,
845 worker
->read_buffer_bytes_wanted
- worker
->read_buffer_cur_size
,
848 (GAsyncReadyCallback
) _g_dbus_worker_do_read_cb
,
849 _g_dbus_worker_ref (worker
));
852 worker
->read_ancillary_messages
= NULL
;
853 worker
->read_num_ancillary_messages
= 0;
854 _g_socket_read_with_control_messages (worker
->socket
,
855 worker
->read_buffer
+ worker
->read_buffer_cur_size
,
856 worker
->read_buffer_bytes_wanted
- worker
->read_buffer_cur_size
,
857 &worker
->read_ancillary_messages
,
858 &worker
->read_num_ancillary_messages
,
861 (GAsyncReadyCallback
) _g_dbus_worker_do_read_cb
,
862 _g_dbus_worker_ref (worker
));
866 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
868 _g_dbus_worker_do_initial_read (gpointer data
)
870 GDBusWorker
*worker
= data
;
871 g_mutex_lock (&worker
->read_lock
);
872 _g_dbus_worker_do_read_unlocked (worker
);
873 g_mutex_unlock (&worker
->read_lock
);
877 /* ---------------------------------------------------------------------------------------------------- */
879 struct _MessageToWriteData
882 GDBusMessage
*message
;
891 message_to_write_data_free (MessageToWriteData
*data
)
893 _g_dbus_worker_unref (data
->worker
);
895 g_object_unref (data
->message
);
897 g_slice_free (MessageToWriteData
, data
);
900 /* ---------------------------------------------------------------------------------------------------- */
902 static void write_message_continue_writing (MessageToWriteData
*data
);
904 /* called in private thread shared by all GDBusConnection instances
906 * write-lock is not held on entry
907 * output_pending is PENDING_WRITE on entry
910 write_message_async_cb (GObject
*source_object
,
914 MessageToWriteData
*data
= user_data
;
916 gssize bytes_written
;
919 /* Note: we can't access data->task after calling g_task_return_* () because the
920 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
925 bytes_written
= g_output_stream_write_finish (G_OUTPUT_STREAM (source_object
),
928 if (bytes_written
== -1)
930 g_task_return_error (task
, error
);
931 g_object_unref (task
);
934 g_assert (bytes_written
> 0); /* zero is never returned */
936 write_message_print_transport_debug (bytes_written
, data
);
938 data
->total_written
+= bytes_written
;
939 g_assert (data
->total_written
<= data
->blob_size
);
940 if (data
->total_written
== data
->blob_size
)
942 g_task_return_boolean (task
, TRUE
);
943 g_object_unref (task
);
947 write_message_continue_writing (data
);
953 /* called in private thread shared by all GDBusConnection instances
955 * write-lock is not held on entry
956 * output_pending is PENDING_WRITE on entry
960 on_socket_ready (GSocket
*socket
,
961 GIOCondition condition
,
964 MessageToWriteData
*data
= user_data
;
965 write_message_continue_writing (data
);
966 return FALSE
; /* remove source */
970 /* called in private thread shared by all GDBusConnection instances
972 * write-lock is not held on entry
973 * output_pending is PENDING_WRITE on entry
976 write_message_continue_writing (MessageToWriteData
*data
)
978 GOutputStream
*ostream
;
981 GUnixFDList
*fd_list
;
985 /* Note: we can't access data->task after calling g_task_return_* () because the
986 * callback can free @data and we're not completing in idle. So use a copy of the pointer.
991 ostream
= g_io_stream_get_output_stream (data
->worker
->stream
);
993 fd_list
= g_dbus_message_get_unix_fd_list (data
->message
);
996 g_assert (!g_output_stream_has_pending (ostream
));
997 g_assert_cmpint (data
->total_written
, <, data
->blob_size
);
1003 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream
) && data
->total_written
== 0)
1005 GOutputVector vector
;
1006 GSocketControlMessage
*control_message
;
1007 gssize bytes_written
;
1010 vector
.buffer
= data
->blob
;
1011 vector
.size
= data
->blob_size
;
1013 control_message
= NULL
;
1014 if (fd_list
!= NULL
&& g_unix_fd_list_get_length (fd_list
) > 0)
1016 if (!(data
->worker
->capabilities
& G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING
))
1018 g_task_return_new_error (task
,
1021 "Tried sending a file descriptor but remote peer does not support this capability");
1022 g_object_unref (task
);
1025 control_message
= g_unix_fd_message_new_with_fd_list (fd_list
);
1029 bytes_written
= g_socket_send_message (data
->worker
->socket
,
1033 control_message
!= NULL
? &control_message
: NULL
,
1034 control_message
!= NULL
? 1 : 0,
1036 data
->worker
->cancellable
,
1038 if (control_message
!= NULL
)
1039 g_object_unref (control_message
);
1041 if (bytes_written
== -1)
1043 /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1044 if (g_error_matches (error
, G_IO_ERROR
, G_IO_ERROR_WOULD_BLOCK
))
1047 source
= g_socket_create_source (data
->worker
->socket
,
1048 G_IO_OUT
| G_IO_HUP
| G_IO_ERR
,
1049 data
->worker
->cancellable
);
1050 g_source_set_callback (source
,
1051 (GSourceFunc
) on_socket_ready
,
1053 NULL
); /* GDestroyNotify */
1054 g_source_attach (source
, g_main_context_get_thread_default ());
1055 g_source_unref (source
);
1056 g_error_free (error
);
1059 g_task_return_error (task
, error
);
1060 g_object_unref (task
);
1063 g_assert (bytes_written
> 0); /* zero is never returned */
1065 write_message_print_transport_debug (bytes_written
, data
);
1067 data
->total_written
+= bytes_written
;
1068 g_assert (data
->total_written
<= data
->blob_size
);
1069 if (data
->total_written
== data
->blob_size
)
1071 g_task_return_boolean (task
, TRUE
);
1072 g_object_unref (task
);
1076 write_message_continue_writing (data
);
1082 if (fd_list
!= NULL
)
1084 g_task_return_new_error (task
,
1087 "Tried sending a file descriptor on unsupported stream of type %s",
1088 g_type_name (G_TYPE_FROM_INSTANCE (ostream
)));
1089 g_object_unref (task
);
1094 g_output_stream_write_async (ostream
,
1095 (const gchar
*) data
->blob
+ data
->total_written
,
1096 data
->blob_size
- data
->total_written
,
1098 data
->worker
->cancellable
,
1099 write_message_async_cb
,
1108 /* called in private thread shared by all GDBusConnection instances
1110 * write-lock is not held on entry
1111 * output_pending is PENDING_WRITE on entry
1114 write_message_async (GDBusWorker
*worker
,
1115 MessageToWriteData
*data
,
1116 GAsyncReadyCallback callback
,
1119 data
->task
= g_task_new (NULL
, NULL
, callback
, user_data
);
1120 g_task_set_source_tag (data
->task
, write_message_async
);
1121 data
->total_written
= 0;
1122 write_message_continue_writing (data
);
1125 /* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1127 write_message_finish (GAsyncResult
*res
,
1130 g_return_val_if_fail (g_task_is_valid (res
, NULL
), FALSE
);
1132 return g_task_propagate_boolean (G_TASK (res
), error
);
1134 /* ---------------------------------------------------------------------------------------------------- */
1136 static void continue_writing (GDBusWorker
*worker
);
1140 GDBusWorker
*worker
;
1145 flush_data_list_complete (const GList
*flushers
,
1146 const GError
*error
)
1150 for (l
= flushers
; l
!= NULL
; l
= l
->next
)
1152 FlushData
*f
= l
->data
;
1154 f
->error
= error
!= NULL
? g_error_copy (error
) : NULL
;
1156 g_mutex_lock (&f
->mutex
);
1157 g_cond_signal (&f
->cond
);
1158 g_mutex_unlock (&f
->mutex
);
1162 /* called in private thread shared by all GDBusConnection instances
1164 * write-lock is not held on entry
1165 * output_pending is PENDING_FLUSH on entry
1168 ostream_flush_cb (GObject
*source_object
,
1172 FlushAsyncData
*data
= user_data
;
1176 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object
),
1182 if (G_UNLIKELY (_g_dbus_debug_transport ()))
1184 _g_dbus_debug_print_lock ();
1185 g_print ("========================================================================\n"
1186 "GDBus-debug:Transport:\n"
1187 " ---- FLUSHED stream of type %s\n",
1188 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data
->worker
->stream
))));
1189 _g_dbus_debug_print_unlock ();
1193 g_assert (data
->flushers
!= NULL
);
1194 flush_data_list_complete (data
->flushers
, error
);
1195 g_list_free (data
->flushers
);
1198 g_error_free (error
);
1200 /* Make sure we tell folks that we don't have additional
1202 g_mutex_lock (&data
->worker
->write_lock
);
1203 data
->worker
->write_num_messages_flushed
= data
->worker
->write_num_messages_written
;
1204 g_assert (data
->worker
->output_pending
== PENDING_FLUSH
);
1205 data
->worker
->output_pending
= PENDING_NONE
;
1206 g_mutex_unlock (&data
->worker
->write_lock
);
1208 /* OK, cool, finally kick off the next write */
1209 continue_writing (data
->worker
);
1211 _g_dbus_worker_unref (data
->worker
);
1215 /* called in private thread shared by all GDBusConnection instances
1217 * write-lock is not held on entry
1218 * output_pending is PENDING_FLUSH on entry
1221 start_flush (FlushAsyncData
*data
)
1223 g_output_stream_flush_async (g_io_stream_get_output_stream (data
->worker
->stream
),
1225 data
->worker
->cancellable
,
1230 /* called in private thread shared by all GDBusConnection instances
1232 * write-lock is held on entry
1233 * output_pending is PENDING_NONE on entry
1236 message_written_unlocked (GDBusWorker
*worker
,
1237 MessageToWriteData
*message_data
)
1239 if (G_UNLIKELY (_g_dbus_debug_message ()))
1242 _g_dbus_debug_print_lock ();
1243 g_print ("========================================================================\n"
1244 "GDBus-debug:Message:\n"
1245 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT
" bytes)\n",
1246 message_data
->blob_size
);
1247 s
= g_dbus_message_print (message_data
->message
, 2);
1250 if (G_UNLIKELY (_g_dbus_debug_payload ()))
1252 s
= _g_dbus_hexdump (message_data
->blob
, message_data
->blob_size
, 2);
1253 g_print ("%s\n", s
);
1256 _g_dbus_debug_print_unlock ();
1259 worker
->write_num_messages_written
+= 1;
1262 /* called in private thread shared by all GDBusConnection instances
1264 * write-lock is held on entry
1265 * output_pending is PENDING_NONE on entry
1267 * Returns: non-%NULL, setting @output_pending, if we need to flush now
1269 static FlushAsyncData
*
1270 prepare_flush_unlocked (GDBusWorker
*worker
)
1277 for (l
= worker
->write_pending_flushes
; l
!= NULL
; l
= ll
)
1279 FlushData
*f
= l
->data
;
1282 if (f
->number_to_wait_for
== worker
->write_num_messages_written
)
1284 flushers
= g_list_append (flushers
, f
);
1285 worker
->write_pending_flushes
= g_list_delete_link (worker
->write_pending_flushes
, l
);
1288 if (flushers
!= NULL
)
1290 g_assert (worker
->output_pending
== PENDING_NONE
);
1291 worker
->output_pending
= PENDING_FLUSH
;
1294 if (flushers
!= NULL
)
1296 FlushAsyncData
*data
;
1298 data
= g_new0 (FlushAsyncData
, 1);
1299 data
->worker
= _g_dbus_worker_ref (worker
);
1300 data
->flushers
= flushers
;
1307 /* called in private thread shared by all GDBusConnection instances
1309 * write-lock is not held on entry
1310 * output_pending is PENDING_WRITE on entry
1313 write_message_cb (GObject
*source_object
,
1317 MessageToWriteData
*data
= user_data
;
1320 g_mutex_lock (&data
->worker
->write_lock
);
1321 g_assert (data
->worker
->output_pending
== PENDING_WRITE
);
1322 data
->worker
->output_pending
= PENDING_NONE
;
1325 if (!write_message_finish (res
, &error
))
1327 g_mutex_unlock (&data
->worker
->write_lock
);
1330 _g_dbus_worker_emit_disconnected (data
->worker
, TRUE
, error
);
1331 g_error_free (error
);
1333 g_mutex_lock (&data
->worker
->write_lock
);
1336 message_written_unlocked (data
->worker
, data
);
1338 g_mutex_unlock (&data
->worker
->write_lock
);
1340 continue_writing (data
->worker
);
1342 message_to_write_data_free (data
);
1345 /* called in private thread shared by all GDBusConnection instances
1347 * write-lock is not held on entry
1348 * output_pending is PENDING_CLOSE on entry
1351 iostream_close_cb (GObject
*source_object
,
1355 GDBusWorker
*worker
= user_data
;
1356 GError
*error
= NULL
;
1357 GList
*pending_close_attempts
, *pending_flush_attempts
;
1360 g_io_stream_close_finish (worker
->stream
, res
, &error
);
1362 g_mutex_lock (&worker
->write_lock
);
1364 pending_close_attempts
= worker
->pending_close_attempts
;
1365 worker
->pending_close_attempts
= NULL
;
1367 pending_flush_attempts
= worker
->write_pending_flushes
;
1368 worker
->write_pending_flushes
= NULL
;
1370 send_queue
= worker
->write_queue
;
1371 worker
->write_queue
= g_queue_new ();
1373 g_assert (worker
->output_pending
== PENDING_CLOSE
);
1374 worker
->output_pending
= PENDING_NONE
;
1376 g_mutex_unlock (&worker
->write_lock
);
1378 while (pending_close_attempts
!= NULL
)
1380 CloseData
*close_data
= pending_close_attempts
->data
;
1382 pending_close_attempts
= g_list_delete_link (pending_close_attempts
,
1383 pending_close_attempts
);
1385 if (close_data
->task
!= NULL
)
1388 g_task_return_error (close_data
->task
, g_error_copy (error
));
1390 g_task_return_boolean (close_data
->task
, TRUE
);
1393 close_data_free (close_data
);
1396 g_clear_error (&error
);
1398 /* all messages queued for sending are discarded */
1399 g_queue_free_full (send_queue
, (GDestroyNotify
) message_to_write_data_free
);
1400 /* all queued flushes fail */
1401 error
= g_error_new (G_IO_ERROR
, G_IO_ERROR_CANCELLED
,
1402 _("Operation was cancelled"));
1403 flush_data_list_complete (pending_flush_attempts
, error
);
1404 g_list_free (pending_flush_attempts
);
1405 g_clear_error (&error
);
1407 _g_dbus_worker_unref (worker
);
1410 /* called in private thread shared by all GDBusConnection instances
1412 * write-lock is not held on entry
1413 * output_pending must be PENDING_NONE on entry
1416 continue_writing (GDBusWorker
*worker
)
1418 MessageToWriteData
*data
;
1419 FlushAsyncData
*flush_async_data
;
1422 /* we mustn't try to write two things at once */
1423 g_assert (worker
->output_pending
== PENDING_NONE
);
1425 g_mutex_lock (&worker
->write_lock
);
1428 flush_async_data
= NULL
;
1430 /* if we want to close the connection, that takes precedence */
1431 if (worker
->pending_close_attempts
!= NULL
)
1433 GInputStream
*input
= g_io_stream_get_input_stream (worker
->stream
);
1435 if (!g_input_stream_has_pending (input
))
1437 worker
->close_expected
= TRUE
;
1438 worker
->output_pending
= PENDING_CLOSE
;
1440 g_io_stream_close_async (worker
->stream
, G_PRIORITY_DEFAULT
,
1441 NULL
, iostream_close_cb
,
1442 _g_dbus_worker_ref (worker
));
1447 flush_async_data
= prepare_flush_unlocked (worker
);
1449 if (flush_async_data
== NULL
)
1451 data
= g_queue_pop_head (worker
->write_queue
);
1454 worker
->output_pending
= PENDING_WRITE
;
1458 g_mutex_unlock (&worker
->write_lock
);
1460 /* Note that write_lock is only used for protecting the @write_queue
1461 * and @output_pending fields of the GDBusWorker struct ... which we
1462 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1464 * Therefore, it's fine to drop it here when calling back into user
1465 * code and then writing the message out onto the GIOStream since this
1466 * function only runs on the worker thread.
1469 if (flush_async_data
!= NULL
)
1471 start_flush (flush_async_data
);
1472 g_assert (data
== NULL
);
1474 else if (data
!= NULL
)
1476 GDBusMessage
*old_message
;
1478 gsize new_blob_size
;
1481 old_message
= data
->message
;
1482 data
->message
= _g_dbus_worker_emit_message_about_to_be_sent (worker
, data
->message
);
1483 if (data
->message
== old_message
)
1485 /* filters had no effect - do nothing */
1487 else if (data
->message
== NULL
)
1489 /* filters dropped message */
1490 g_mutex_lock (&worker
->write_lock
);
1491 worker
->output_pending
= PENDING_NONE
;
1492 g_mutex_unlock (&worker
->write_lock
);
1493 message_to_write_data_free (data
);
1498 /* filters altered the message -> reencode */
1500 new_blob
= g_dbus_message_to_blob (data
->message
,
1502 worker
->capabilities
,
1504 if (new_blob
== NULL
)
1506 /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1507 * the old message instead
1509 g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1510 g_dbus_message_get_serial (data
->message
),
1512 g_error_free (error
);
1516 g_free (data
->blob
);
1517 data
->blob
= (gchar
*) new_blob
;
1518 data
->blob_size
= new_blob_size
;
1522 write_message_async (worker
,
1529 /* called in private thread shared by all GDBusConnection instances
1531 * write-lock is not held on entry
1532 * output_pending may be anything
1535 continue_writing_in_idle_cb (gpointer user_data
)
1537 GDBusWorker
*worker
= user_data
;
1539 /* Because this is the worker thread, we can read this struct member
1540 * without holding the lock: no other thread ever modifies it.
1542 if (worker
->output_pending
== PENDING_NONE
)
1543 continue_writing (worker
);
1549 * @write_data: (transfer full) (nullable):
1550 * @flush_data: (transfer full) (nullable):
1551 * @close_data: (transfer full) (nullable):
1553 * Can be called from any thread
1555 * write_lock is held on entry
1556 * output_pending may be anything
1559 schedule_writing_unlocked (GDBusWorker
*worker
,
1560 MessageToWriteData
*write_data
,
1561 FlushData
*flush_data
,
1562 CloseData
*close_data
)
1564 if (write_data
!= NULL
)
1565 g_queue_push_tail (worker
->write_queue
, write_data
);
1567 if (flush_data
!= NULL
)
1568 worker
->write_pending_flushes
= g_list_prepend (worker
->write_pending_flushes
, flush_data
);
1570 if (close_data
!= NULL
)
1571 worker
->pending_close_attempts
= g_list_prepend (worker
->pending_close_attempts
,
1574 /* If we had output pending, the next bit of output will happen
1575 * automatically when it finishes, so we only need to do this
1576 * if nothing was pending.
1578 * The idle callback will re-check that output_pending is still
1579 * PENDING_NONE, to guard against output starting before the idle.
1581 if (worker
->output_pending
== PENDING_NONE
)
1583 GSource
*idle_source
;
1584 idle_source
= g_idle_source_new ();
1585 g_source_set_priority (idle_source
, G_PRIORITY_DEFAULT
);
1586 g_source_set_callback (idle_source
,
1587 continue_writing_in_idle_cb
,
1588 _g_dbus_worker_ref (worker
),
1589 (GDestroyNotify
) _g_dbus_worker_unref
);
1590 g_source_set_name (idle_source
, "[gio] continue_writing_in_idle_cb");
1591 g_source_attach (idle_source
, worker
->shared_thread_data
->context
);
1592 g_source_unref (idle_source
);
1597 schedule_pending_close (GDBusWorker
*worker
)
1599 g_mutex_lock (&worker
->write_lock
);
1600 if (worker
->pending_close_attempts
)
1601 schedule_writing_unlocked (worker
, NULL
, NULL
, NULL
);
1602 g_mutex_unlock (&worker
->write_lock
);
1605 /* ---------------------------------------------------------------------------------------------------- */
1607 /* can be called from any thread - steals blob
1609 * write_lock is not held on entry
1610 * output_pending may be anything
1613 _g_dbus_worker_send_message (GDBusWorker
*worker
,
1614 GDBusMessage
*message
,
1618 MessageToWriteData
*data
;
1620 g_return_if_fail (G_IS_DBUS_MESSAGE (message
));
1621 g_return_if_fail (blob
!= NULL
);
1622 g_return_if_fail (blob_len
> 16);
1624 data
= g_slice_new0 (MessageToWriteData
);
1625 data
->worker
= _g_dbus_worker_ref (worker
);
1626 data
->message
= g_object_ref (message
);
1627 data
->blob
= blob
; /* steal! */
1628 data
->blob_size
= blob_len
;
1630 g_mutex_lock (&worker
->write_lock
);
1631 schedule_writing_unlocked (worker
, data
, NULL
, NULL
);
1632 g_mutex_unlock (&worker
->write_lock
);
1635 /* ---------------------------------------------------------------------------------------------------- */
1638 _g_dbus_worker_new (GIOStream
*stream
,
1639 GDBusCapabilityFlags capabilities
,
1640 gboolean initially_frozen
,
1641 GDBusWorkerMessageReceivedCallback message_received_callback
,
1642 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback
,
1643 GDBusWorkerDisconnectedCallback disconnected_callback
,
1646 GDBusWorker
*worker
;
1647 GSource
*idle_source
;
1649 g_return_val_if_fail (G_IS_IO_STREAM (stream
), NULL
);
1650 g_return_val_if_fail (message_received_callback
!= NULL
, NULL
);
1651 g_return_val_if_fail (message_about_to_be_sent_callback
!= NULL
, NULL
);
1652 g_return_val_if_fail (disconnected_callback
!= NULL
, NULL
);
1654 worker
= g_new0 (GDBusWorker
, 1);
1655 worker
->ref_count
= 1;
1657 g_mutex_init (&worker
->read_lock
);
1658 worker
->message_received_callback
= message_received_callback
;
1659 worker
->message_about_to_be_sent_callback
= message_about_to_be_sent_callback
;
1660 worker
->disconnected_callback
= disconnected_callback
;
1661 worker
->user_data
= user_data
;
1662 worker
->stream
= g_object_ref (stream
);
1663 worker
->capabilities
= capabilities
;
1664 worker
->cancellable
= g_cancellable_new ();
1665 worker
->output_pending
= PENDING_NONE
;
1667 worker
->frozen
= initially_frozen
;
1668 worker
->received_messages_while_frozen
= g_queue_new ();
1670 g_mutex_init (&worker
->write_lock
);
1671 worker
->write_queue
= g_queue_new ();
1673 if (G_IS_SOCKET_CONNECTION (worker
->stream
))
1674 worker
->socket
= g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker
->stream
));
1676 worker
->shared_thread_data
= _g_dbus_shared_thread_ref ();
1679 idle_source
= g_idle_source_new ();
1680 g_source_set_priority (idle_source
, G_PRIORITY_DEFAULT
);
1681 g_source_set_callback (idle_source
,
1682 _g_dbus_worker_do_initial_read
,
1683 _g_dbus_worker_ref (worker
),
1684 (GDestroyNotify
) _g_dbus_worker_unref
);
1685 g_source_set_name (idle_source
, "[gio] _g_dbus_worker_do_initial_read");
1686 g_source_attach (idle_source
, worker
->shared_thread_data
->context
);
1687 g_source_unref (idle_source
);
1692 /* ---------------------------------------------------------------------------------------------------- */
1694 /* can be called from any thread
1696 * write_lock is not held on entry
1697 * output_pending may be anything
1700 _g_dbus_worker_close (GDBusWorker
*worker
,
1703 CloseData
*close_data
;
1705 close_data
= g_slice_new0 (CloseData
);
1706 close_data
->worker
= _g_dbus_worker_ref (worker
);
1707 close_data
->task
= (task
== NULL
? NULL
: g_object_ref (task
));
1709 /* Don't set worker->close_expected here - we're in the wrong thread.
1710 * It'll be set before the actual close happens.
1712 g_cancellable_cancel (worker
->cancellable
);
1713 g_mutex_lock (&worker
->write_lock
);
1714 schedule_writing_unlocked (worker
, NULL
, NULL
, close_data
);
1715 g_mutex_unlock (&worker
->write_lock
);
1718 /* This can be called from any thread - frees worker. Note that
1719 * callbacks might still happen if called from another thread than the
1720 * worker - use your own synchronization primitive in the callbacks.
1722 * write_lock is not held on entry
1723 * output_pending may be anything
1726 _g_dbus_worker_stop (GDBusWorker
*worker
)
1728 g_atomic_int_set (&worker
->stopped
, TRUE
);
1730 /* Cancel any pending operations and schedule a close of the underlying I/O
1731 * stream in the worker thread
1733 _g_dbus_worker_close (worker
, NULL
);
1735 /* _g_dbus_worker_close holds a ref until after an idle in the worker
1736 * thread has run, so we no longer need to unref in an idle like in
1739 _g_dbus_worker_unref (worker
);
1742 /* ---------------------------------------------------------------------------------------------------- */
1744 /* can be called from any thread (except the worker thread) - blocks
1745 * calling thread until all queued outgoing messages are written and
1746 * the transport has been flushed
1748 * write_lock is not held on entry
1749 * output_pending may be anything
1752 _g_dbus_worker_flush_sync (GDBusWorker
*worker
,
1753 GCancellable
*cancellable
,
1758 guint64 pending_writes
;
1763 g_mutex_lock (&worker
->write_lock
);
1765 /* if the queue is empty, no write is in-flight and we haven't written
1766 * anything since the last flush, then there's nothing to wait for
1768 pending_writes
= g_queue_get_length (worker
->write_queue
);
1770 /* if a write is in-flight, we shouldn't be satisfied until the first
1771 * flush operation that follows it
1773 if (worker
->output_pending
== PENDING_WRITE
)
1774 pending_writes
+= 1;
1776 if (pending_writes
> 0 ||
1777 worker
->write_num_messages_written
!= worker
->write_num_messages_flushed
)
1779 data
= g_new0 (FlushData
, 1);
1780 g_mutex_init (&data
->mutex
);
1781 g_cond_init (&data
->cond
);
1782 data
->number_to_wait_for
= worker
->write_num_messages_written
+ pending_writes
;
1783 g_mutex_lock (&data
->mutex
);
1785 schedule_writing_unlocked (worker
, NULL
, data
, NULL
);
1787 g_mutex_unlock (&worker
->write_lock
);
1791 g_cond_wait (&data
->cond
, &data
->mutex
);
1792 g_mutex_unlock (&data
->mutex
);
1794 /* note:the element is removed from worker->write_pending_flushes in flush_cb() above */
1795 g_cond_clear (&data
->cond
);
1796 g_mutex_clear (&data
->mutex
);
1797 if (data
->error
!= NULL
)
1800 g_propagate_error (error
, data
->error
);
1808 /* ---------------------------------------------------------------------------------------------------- */
1810 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1811 #define G_DBUS_DEBUG_TRANSPORT (1<<1)
1812 #define G_DBUS_DEBUG_MESSAGE (1<<2)
1813 #define G_DBUS_DEBUG_PAYLOAD (1<<3)
1814 #define G_DBUS_DEBUG_CALL (1<<4)
1815 #define G_DBUS_DEBUG_SIGNAL (1<<5)
1816 #define G_DBUS_DEBUG_INCOMING (1<<6)
1817 #define G_DBUS_DEBUG_RETURN (1<<7)
1818 #define G_DBUS_DEBUG_EMISSION (1<<8)
1819 #define G_DBUS_DEBUG_ADDRESS (1<<9)
1821 static gint _gdbus_debug_flags
= 0;
1824 _g_dbus_debug_authentication (void)
1826 _g_dbus_initialize ();
1827 return (_gdbus_debug_flags
& G_DBUS_DEBUG_AUTHENTICATION
) != 0;
1831 _g_dbus_debug_transport (void)
1833 _g_dbus_initialize ();
1834 return (_gdbus_debug_flags
& G_DBUS_DEBUG_TRANSPORT
) != 0;
1838 _g_dbus_debug_message (void)
1840 _g_dbus_initialize ();
1841 return (_gdbus_debug_flags
& G_DBUS_DEBUG_MESSAGE
) != 0;
1845 _g_dbus_debug_payload (void)
1847 _g_dbus_initialize ();
1848 return (_gdbus_debug_flags
& G_DBUS_DEBUG_PAYLOAD
) != 0;
1852 _g_dbus_debug_call (void)
1854 _g_dbus_initialize ();
1855 return (_gdbus_debug_flags
& G_DBUS_DEBUG_CALL
) != 0;
1859 _g_dbus_debug_signal (void)
1861 _g_dbus_initialize ();
1862 return (_gdbus_debug_flags
& G_DBUS_DEBUG_SIGNAL
) != 0;
1866 _g_dbus_debug_incoming (void)
1868 _g_dbus_initialize ();
1869 return (_gdbus_debug_flags
& G_DBUS_DEBUG_INCOMING
) != 0;
1873 _g_dbus_debug_return (void)
1875 _g_dbus_initialize ();
1876 return (_gdbus_debug_flags
& G_DBUS_DEBUG_RETURN
) != 0;
1880 _g_dbus_debug_emission (void)
1882 _g_dbus_initialize ();
1883 return (_gdbus_debug_flags
& G_DBUS_DEBUG_EMISSION
) != 0;
1887 _g_dbus_debug_address (void)
1889 _g_dbus_initialize ();
1890 return (_gdbus_debug_flags
& G_DBUS_DEBUG_ADDRESS
) != 0;
1893 G_LOCK_DEFINE_STATIC (print_lock
);
1896 _g_dbus_debug_print_lock (void)
1898 G_LOCK (print_lock
);
1902 _g_dbus_debug_print_unlock (void)
1904 G_UNLOCK (print_lock
);
1908 * _g_dbus_initialize:
1910 * Does various one-time init things such as
1912 * - registering the G_DBUS_ERROR error domain
1913 * - parses the G_DBUS_DEBUG environment variable
1916 _g_dbus_initialize (void)
1918 static volatile gsize initialized
= 0;
1920 if (g_once_init_enter (&initialized
))
1922 volatile GQuark g_dbus_error_domain
;
1925 g_dbus_error_domain
= G_DBUS_ERROR
;
1926 (g_dbus_error_domain
); /* To avoid -Wunused-but-set-variable */
1928 debug
= g_getenv ("G_DBUS_DEBUG");
1931 const GDebugKey keys
[] = {
1932 { "authentication", G_DBUS_DEBUG_AUTHENTICATION
},
1933 { "transport", G_DBUS_DEBUG_TRANSPORT
},
1934 { "message", G_DBUS_DEBUG_MESSAGE
},
1935 { "payload", G_DBUS_DEBUG_PAYLOAD
},
1936 { "call", G_DBUS_DEBUG_CALL
},
1937 { "signal", G_DBUS_DEBUG_SIGNAL
},
1938 { "incoming", G_DBUS_DEBUG_INCOMING
},
1939 { "return", G_DBUS_DEBUG_RETURN
},
1940 { "emission", G_DBUS_DEBUG_EMISSION
},
1941 { "address", G_DBUS_DEBUG_ADDRESS
}
1944 _gdbus_debug_flags
= g_parse_debug_string (debug
, keys
, G_N_ELEMENTS (keys
));
1945 if (_gdbus_debug_flags
& G_DBUS_DEBUG_PAYLOAD
)
1946 _gdbus_debug_flags
|= G_DBUS_DEBUG_MESSAGE
;
1949 /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
1950 ensure_required_types ();
1952 g_once_init_leave (&initialized
, 1);
1956 /* ---------------------------------------------------------------------------------------------------- */
1959 _g_dbus_compute_complete_signature (GDBusArgInfo
**args
)
1961 const GVariantType
*arg_types
[256];
1965 for (n
= 0; args
[n
] != NULL
; n
++)
1967 /* DBus places a hard limit of 255 on signature length.
1968 * therefore number of args must be less than 256.
1972 arg_types
[n
] = G_VARIANT_TYPE (args
[n
]->signature
);
1974 if G_UNLIKELY (arg_types
[n
] == NULL
)
1980 return g_variant_type_new_tuple (arg_types
, n
);
1983 /* ---------------------------------------------------------------------------------------------------- */
1987 extern BOOL WINAPI
ConvertSidToStringSidA (PSID Sid
, LPSTR
*StringSid
);
1990 _g_dbus_win32_get_user_sid (void)
1994 DWORD token_information_len
;
2001 h
= INVALID_HANDLE_VALUE
;
2003 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY
, &h
))
2005 g_warning ("OpenProcessToken failed with error code %d", (gint
) GetLastError ());
2009 /* Get length of buffer */
2010 token_information_len
= 0;
2011 if (!GetTokenInformation (h
, TokenUser
, NULL
, 0, &token_information_len
))
2013 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER
)
2015 g_warning ("GetTokenInformation() failed with error code %d", (gint
) GetLastError ());
2019 user
= g_malloc (token_information_len
);
2020 if (!GetTokenInformation (h
, TokenUser
, user
, token_information_len
, &token_information_len
))
2022 g_warning ("GetTokenInformation() failed with error code %d", (gint
) GetLastError ());
2026 psid
= user
->User
.Sid
;
2027 if (!IsValidSid (psid
))
2029 g_warning ("Invalid SID");
2033 if (!ConvertSidToStringSidA (psid
, &sid
))
2035 g_warning ("Invalid SID");
2039 ret
= g_strdup (sid
);
2044 if (h
!= INVALID_HANDLE_VALUE
)
2050 /* ---------------------------------------------------------------------------------------------------- */
2053 _g_dbus_get_machine_id (GError
**error
)
2056 HW_PROFILE_INFOA info
;
2057 char *src
, *dest
, *res
;
2060 if (!GetCurrentHwProfileA (&info
))
2062 char *message
= g_win32_error_message (GetLastError ());
2066 _("Unable to get Hardware profile: %s"), message
);
2071 /* Form: {12340001-4980-1920-6788-123456789012} */
2072 src
= &info
.szHwProfileGuid
[0];
2074 res
= g_malloc (32+1);
2078 for (i
= 0; i
< 8; i
++)
2081 for (i
= 0; i
< 4; i
++)
2084 for (i
= 0; i
< 4; i
++)
2087 for (i
= 0; i
< 4; i
++)
2090 for (i
= 0; i
< 12; i
++)
2097 GError
*first_error
;
2098 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2101 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2105 !g_file_get_contents ("/etc/machine-id",
2110 g_propagate_prefixed_error (error
, first_error
,
2111 _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2115 /* ignore the error from the first try, if any */
2116 g_clear_error (&first_error
);
2117 /* TODO: validate value */
2124 /* ---------------------------------------------------------------------------------------------------- */
2127 _g_dbus_enum_to_string (GType enum_type
, gint value
)
2131 GEnumValue
*enum_value
;
2133 klass
= g_type_class_ref (enum_type
);
2134 enum_value
= g_enum_get_value (klass
, value
);
2135 if (enum_value
!= NULL
)
2136 ret
= g_strdup (enum_value
->value_nick
);
2138 ret
= g_strdup_printf ("unknown (value %d)", value
);
2139 g_type_class_unref (klass
);
2143 /* ---------------------------------------------------------------------------------------------------- */
2146 write_message_print_transport_debug (gssize bytes_written
,
2147 MessageToWriteData
*data
)
2149 if (G_LIKELY (!_g_dbus_debug_transport ()))
2152 _g_dbus_debug_print_lock ();
2153 g_print ("========================================================================\n"
2154 "GDBus-debug:Transport:\n"
2155 " >>>> WROTE %" G_GSSIZE_FORMAT
" bytes of message with serial %d and\n"
2156 " size %" G_GSIZE_FORMAT
" from offset %" G_GSIZE_FORMAT
" on a %s\n",
2158 g_dbus_message_get_serial (data
->message
),
2160 data
->total_written
,
2161 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data
->worker
->stream
))));
2162 _g_dbus_debug_print_unlock ();
2167 /* ---------------------------------------------------------------------------------------------------- */
2170 read_message_print_transport_debug (gssize bytes_read
,
2171 GDBusWorker
*worker
)
2175 gint32 message_length
;
2177 if (G_LIKELY (!_g_dbus_debug_transport ()))
2180 size
= bytes_read
+ worker
->read_buffer_cur_size
;
2184 message_length
= g_dbus_message_bytes_needed ((guchar
*) worker
->read_buffer
, size
, NULL
);
2187 switch (worker
->read_buffer
[0])
2191 serial
= GUINT32_FROM_LE (((guint32
*) worker
->read_buffer
)[2]);
2195 serial
= GUINT32_FROM_BE (((guint32
*) worker
->read_buffer
)[2]);
2198 /* an error will be set elsewhere if this happens */
2203 _g_dbus_debug_print_lock ();
2204 g_print ("========================================================================\n"
2205 "GDBus-debug:Transport:\n"
2206 " <<<< READ %" G_GSSIZE_FORMAT
" bytes of message with serial %d and\n"
2207 " size %d to offset %" G_GSIZE_FORMAT
" from a %s\n",
2211 worker
->read_buffer_cur_size
,
2212 g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker
->stream
))));
2213 _g_dbus_debug_print_unlock ();
2218 /* ---------------------------------------------------------------------------------------------------- */
2221 _g_signal_accumulator_false_handled (GSignalInvocationHint
*ihint
,
2222 GValue
*return_accu
,
2223 const GValue
*handler_return
,
2226 gboolean continue_emission
;
2227 gboolean signal_return
;
2229 signal_return
= g_value_get_boolean (handler_return
);
2230 g_value_set_boolean (return_accu
, signal_return
);
2231 continue_emission
= signal_return
;
2233 return continue_emission
;
2236 /* ---------------------------------------------------------------------------------------------------- */
2239 append_nibble (GString
*s
, gint val
)
2241 g_string_append_c (s
, val
>= 10 ? ('a' + val
- 10) : ('0' + val
));
2244 /* ---------------------------------------------------------------------------------------------------- */
2247 _g_dbus_hexencode (const gchar
*str
,
2253 s
= g_string_new (NULL
);
2254 for (n
= 0; n
< str_len
; n
++)
2260 val
= ((const guchar
*) str
)[n
];
2261 upper_nibble
= val
>> 4;
2262 lower_nibble
= val
& 0x0f;
2264 append_nibble (s
, upper_nibble
);
2265 append_nibble (s
, lower_nibble
);
2268 return g_string_free (s
, FALSE
);