configure.ac: Remove --disable-znodelete options
[glib.git] / gio / gdbusprivate.c
blobb5f8b650923b5503814cdef3fec4eda95971b3ca
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>
21 #include "config.h"
23 #include <stdlib.h>
24 #include <string.h>
26 #include "giotypes.h"
27 #include "gioenumtypes.h"
28 #include "gsocket.h"
29 #include "gdbusauthobserver.h"
30 #include "gdbusprivate.h"
31 #include "gdbusmessage.h"
32 #include "gdbusconnection.h"
33 #include "gdbusproxy.h"
34 #include "gdbuserror.h"
35 #include "gdbusintrospection.h"
36 #include "gtask.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"
46 #ifdef G_OS_UNIX
47 #include "gunixfdmessage.h"
48 #include "gunixconnection.h"
49 #include "gunixcredentialsmessage.h"
50 #endif
52 #ifdef G_OS_WIN32
53 #include <windows.h>
54 #endif
56 #include "glibintl.h"
58 static gboolean _g_dbus_worker_do_initial_read (gpointer data);
59 static void schedule_pending_close (GDBusWorker *worker);
61 /* ---------------------------------------------------------------------------------------------------- */
63 gchar *
64 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
66 guint n, m;
67 GString *ret;
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, ' ');
79 if (m < len)
80 g_string_append_printf (ret, "%02x ", (guchar) data[m]);
81 else
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).
104 typedef struct
106 void *buffer;
107 gsize count;
109 GSocketControlMessage ***messages;
110 gint *num_messages;
111 } ReadWithControlData;
113 static void
114 read_with_control_data_free (ReadWithControlData *data)
116 g_slice_free (ReadWithControlData, data);
119 static gboolean
120 _g_socket_read_with_control_messages_ready (GSocket *socket,
121 GIOCondition condition,
122 gpointer user_data)
124 GTask *task = user_data;
125 ReadWithControlData *data = g_task_get_task_data (task);
126 GError *error;
127 gssize result;
128 GInputVector vector;
130 error = NULL;
131 vector.buffer = data->buffer;
132 vector.size = data->count;
133 result = g_socket_receive_message (socket,
134 NULL, /* address */
135 &vector,
137 data->messages,
138 data->num_messages,
139 NULL,
140 g_task_get_cancellable (task),
141 &error);
143 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
145 g_error_free (error);
146 return TRUE;
149 g_assert (result >= 0 || error != NULL);
150 if (result >= 0)
151 g_task_return_int (task, result);
152 else
153 g_task_return_error (task, error);
154 g_object_unref (task);
156 return FALSE;
159 static void
160 _g_socket_read_with_control_messages (GSocket *socket,
161 void *buffer,
162 gsize count,
163 GSocketControlMessage ***messages,
164 gint *num_messages,
165 gint io_priority,
166 GCancellable *cancellable,
167 GAsyncReadyCallback callback,
168 gpointer user_data)
170 GTask *task;
171 ReadWithControlData *data;
172 GSource *source;
174 data = g_slice_new0 (ReadWithControlData);
175 data->buffer = buffer;
176 data->count = count;
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))
187 return;
190 source = g_socket_create_source (socket,
191 G_IO_IN | G_IO_HUP | G_IO_ERR,
192 cancellable);
193 g_task_attach_source (task, source, (GSourceFunc) _g_socket_read_with_control_messages_ready);
194 g_source_unref (source);
197 static gssize
198 _g_socket_read_with_control_messages_finish (GSocket *socket,
199 GAsyncResult *result,
200 GError **error)
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;
215 static void
216 ensure_type (GType gtype)
218 g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
221 static void
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;
229 static void
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 /* ---------------------------------------------------------------------------------------------------- */
261 typedef struct
263 volatile gint refcount;
264 GThread *thread;
265 GMainContext *context;
266 GMainLoop *loop;
267 } SharedThreadData;
269 static gpointer
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 ();
280 return NULL;
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);
296 data->refcount = 0;
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,
302 data);
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);
309 return ret;
312 static void
313 _g_dbus_shared_thread_unref (SharedThreadData *data)
315 /* TODO: actually destroy the shared thread here */
316 #if 0
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);
325 #endif
328 /* ---------------------------------------------------------------------------------------------------- */
330 typedef enum {
331 PENDING_NONE = 0,
332 PENDING_WRITE,
333 PENDING_FLUSH,
334 PENDING_CLOSE
335 } OutputPending;
337 struct GDBusWorker
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?
350 gboolean frozen;
351 GDBusCapabilityFlags capabilities;
352 GQueue *received_messages_while_frozen;
354 GIOStream *stream;
355 GCancellable *cancellable;
356 GDBusWorkerMessageReceivedCallback message_received_callback;
357 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
358 GDBusWorkerDisconnectedCallback disconnected_callback;
359 gpointer user_data;
361 /* if not NULL, stream is GSocketConnection */
362 GSocket *socket;
364 /* used for reading */
365 GMutex read_lock;
366 gchar *read_buffer;
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 */
381 GMutex write_lock;
382 /* queue of MessageToWriteData, protected by write_lock */
383 GQueue *write_queue;
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 /* ---------------------------------------------------------------------------------------------------- */
402 typedef struct
404 GMutex mutex;
405 GCond cond;
406 guint64 number_to_wait_for;
407 GError *error;
408 } FlushData;
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);
421 typedef struct {
422 GDBusWorker *worker;
423 GTask *task;
424 } CloseData;
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 /* ---------------------------------------------------------------------------------------------------- */
436 static GDBusWorker *
437 _g_dbus_worker_ref (GDBusWorker *worker)
439 g_atomic_int_inc (&worker->ref_count);
440 return worker;
443 static void
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);
464 g_free (worker);
468 static void
469 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
470 gboolean remote_peer_vanished,
471 GError *error)
473 if (!g_atomic_int_get (&worker->stopped))
474 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
477 static void
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)
489 GDBusMessage *ret;
490 if (!g_atomic_int_get (&worker->stopped))
491 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
492 else
493 ret = message;
494 return ret;
497 /* can only be called from private thread with read-lock held - takes ownership of @message */
498 static void
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)
504 /* queue up */
505 g_queue_push_tail (worker->received_messages_while_frozen, message);
507 else
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) */
516 static gboolean
517 unfreeze_in_idle_cb (gpointer user_data)
519 GDBusWorker *worker = user_data;
520 GDBusMessage *message;
522 g_mutex_lock (&worker->read_lock);
523 if (worker->frozen)
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;
532 else
534 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
536 g_mutex_unlock (&worker->read_lock);
537 return FALSE;
540 /* can be called from any thread */
541 void
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,
548 unfreeze_in_idle_cb,
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) */
561 static void
562 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
563 GAsyncResult *res,
564 gpointer user_data)
566 GDBusWorker *worker = user_data;
567 GError *error;
568 gssize bytes_read;
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))
574 goto out;
576 error = NULL;
577 if (worker->socket == NULL)
578 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
579 res,
580 &error);
581 else
582 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
583 res,
584 &error);
585 if (worker->read_num_ancillary_messages > 0)
587 gint n;
588 for (n = 0; n < worker->read_num_ancillary_messages; n++)
590 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
592 if (FALSE)
595 #ifdef G_OS_UNIX
596 else if (G_IS_UNIX_FD_MESSAGE (control_message))
598 GUnixFDMessage *fd_message;
599 gint *fds;
600 gint num_fds;
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);
608 else
610 gint n;
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);
618 g_free (fds);
620 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
622 /* do nothing */
624 #endif
625 else
627 if (error == NULL)
629 g_set_error (&error,
630 G_IO_ERROR,
631 G_IO_ERROR_FAILED,
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);
637 n++;
638 while (n < worker->read_num_ancillary_messages)
639 g_object_unref (worker->read_ancillary_messages[n++]);
640 g_free (worker->read_ancillary_messages);
641 goto out;
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"
657 " ---- %s %d: %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,
660 error->message);
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);
682 else
683 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
685 g_error_free (error);
686 goto out;
689 #if 0
690 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
691 (gint) bytes_read,
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),
696 worker->stream,
697 worker);
698 #endif
700 /* TODO: hmm, hmm... */
701 if (bytes_read == 0)
703 g_set_error (&error,
704 G_IO_ERROR,
705 G_IO_ERROR_FAILED,
706 "Underlying GIOStream returned 0 bytes on an async read");
707 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
708 g_error_free (error);
709 goto out;
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)
720 gssize message_len;
721 /* OK, got the header - determine how many more bytes are needed */
722 error = NULL;
723 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
725 &error);
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);
731 goto out;
734 worker->read_buffer_bytes_wanted = message_len;
735 _g_dbus_worker_do_read_unlocked (worker);
737 else
739 GDBusMessage *message;
740 error = NULL;
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,
747 &error);
748 if (message == NULL)
750 gchar *s;
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"
753 "The error is: %s\n"
754 "The payload is as follows:\n"
755 "%s",
756 worker->read_buffer_cur_size,
757 error->message,
759 g_free (s);
760 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
761 g_error_free (error);
762 goto out;
765 #ifdef G_OS_UNIX
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;
772 #endif
774 if (G_UNLIKELY (_g_dbus_debug_message ()))
776 gchar *s;
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);
783 g_print ("%s", s);
784 g_free (s);
785 if (G_UNLIKELY (_g_dbus_debug_payload ()))
787 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
788 g_print ("%s\n", s);
789 g_free (s);
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);
803 else
805 /* didn't get all the bytes we requested - so repeat the request... */
806 _g_dbus_worker_do_read_unlocked (worker);
809 out:
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) */
820 static void
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,
846 G_PRIORITY_DEFAULT,
847 worker->cancellable,
848 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
849 _g_dbus_worker_ref (worker));
850 else
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,
859 G_PRIORITY_DEFAULT,
860 worker->cancellable,
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) */
867 static gboolean
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);
874 return FALSE;
877 /* ---------------------------------------------------------------------------------------------------- */
879 struct _MessageToWriteData
881 GDBusWorker *worker;
882 GDBusMessage *message;
883 gchar *blob;
884 gsize blob_size;
886 gsize total_written;
887 GTask *task;
890 static void
891 message_to_write_data_free (MessageToWriteData *data)
893 _g_dbus_worker_unref (data->worker);
894 if (data->message)
895 g_object_unref (data->message);
896 g_free (data->blob);
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
909 static void
910 write_message_async_cb (GObject *source_object,
911 GAsyncResult *res,
912 gpointer user_data)
914 MessageToWriteData *data = user_data;
915 GTask *task;
916 gssize bytes_written;
917 GError *error;
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.
922 task = data->task;
924 error = NULL;
925 bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
926 res,
927 &error);
928 if (bytes_written == -1)
930 g_task_return_error (task, error);
931 g_object_unref (task);
932 goto out;
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);
944 goto out;
947 write_message_continue_writing (data);
949 out:
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
958 #ifdef G_OS_UNIX
959 static gboolean
960 on_socket_ready (GSocket *socket,
961 GIOCondition condition,
962 gpointer user_data)
964 MessageToWriteData *data = user_data;
965 write_message_continue_writing (data);
966 return FALSE; /* remove source */
968 #endif
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
975 static void
976 write_message_continue_writing (MessageToWriteData *data)
978 GOutputStream *ostream;
979 #ifdef G_OS_UNIX
980 GTask *task;
981 GUnixFDList *fd_list;
982 #endif
984 #ifdef G_OS_UNIX
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.
988 task = data->task;
989 #endif
991 ostream = g_io_stream_get_output_stream (data->worker->stream);
992 #ifdef G_OS_UNIX
993 fd_list = g_dbus_message_get_unix_fd_list (data->message);
994 #endif
996 g_assert (!g_output_stream_has_pending (ostream));
997 g_assert_cmpint (data->total_written, <, data->blob_size);
999 if (FALSE)
1002 #ifdef G_OS_UNIX
1003 else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
1005 GOutputVector vector;
1006 GSocketControlMessage *control_message;
1007 gssize bytes_written;
1008 GError *error;
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,
1019 G_IO_ERROR,
1020 G_IO_ERROR_FAILED,
1021 "Tried sending a file descriptor but remote peer does not support this capability");
1022 g_object_unref (task);
1023 goto out;
1025 control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1028 error = NULL;
1029 bytes_written = g_socket_send_message (data->worker->socket,
1030 NULL, /* address */
1031 &vector,
1033 control_message != NULL ? &control_message : NULL,
1034 control_message != NULL ? 1 : 0,
1035 G_SOCKET_MSG_NONE,
1036 data->worker->cancellable,
1037 &error);
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))
1046 GSource *source;
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,
1052 data,
1053 NULL); /* GDestroyNotify */
1054 g_source_attach (source, g_main_context_get_thread_default ());
1055 g_source_unref (source);
1056 g_error_free (error);
1057 goto out;
1059 g_task_return_error (task, error);
1060 g_object_unref (task);
1061 goto out;
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);
1073 goto out;
1076 write_message_continue_writing (data);
1078 #endif
1079 else
1081 #ifdef G_OS_UNIX
1082 if (fd_list != NULL)
1084 g_task_return_new_error (task,
1085 G_IO_ERROR,
1086 G_IO_ERROR_FAILED,
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);
1090 goto out;
1092 #endif
1094 g_output_stream_write_async (ostream,
1095 (const gchar *) data->blob + data->total_written,
1096 data->blob_size - data->total_written,
1097 G_PRIORITY_DEFAULT,
1098 data->worker->cancellable,
1099 write_message_async_cb,
1100 data);
1102 #ifdef G_OS_UNIX
1103 out:
1104 #endif
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
1113 static void
1114 write_message_async (GDBusWorker *worker,
1115 MessageToWriteData *data,
1116 GAsyncReadyCallback callback,
1117 gpointer user_data)
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) */
1126 static gboolean
1127 write_message_finish (GAsyncResult *res,
1128 GError **error)
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);
1138 typedef struct
1140 GDBusWorker *worker;
1141 GList *flushers;
1142 } FlushAsyncData;
1144 static void
1145 flush_data_list_complete (const GList *flushers,
1146 const GError *error)
1148 const GList *l;
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
1167 static void
1168 ostream_flush_cb (GObject *source_object,
1169 GAsyncResult *res,
1170 gpointer user_data)
1172 FlushAsyncData *data = user_data;
1173 GError *error;
1175 error = NULL;
1176 g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1177 res,
1178 &error);
1180 if (error == NULL)
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);
1197 if (error != NULL)
1198 g_error_free (error);
1200 /* Make sure we tell folks that we don't have additional
1201 flushes pending */
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);
1212 g_free (data);
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
1220 static void
1221 start_flush (FlushAsyncData *data)
1223 g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1224 G_PRIORITY_DEFAULT,
1225 data->worker->cancellable,
1226 ostream_flush_cb,
1227 data);
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
1235 static void
1236 message_written_unlocked (GDBusWorker *worker,
1237 MessageToWriteData *message_data)
1239 if (G_UNLIKELY (_g_dbus_debug_message ()))
1241 gchar *s;
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);
1248 g_print ("%s", s);
1249 g_free (s);
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);
1254 g_free (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)
1272 GList *l;
1273 GList *ll;
1274 GList *flushers;
1276 flushers = NULL;
1277 for (l = worker->write_pending_flushes; l != NULL; l = ll)
1279 FlushData *f = l->data;
1280 ll = l->next;
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;
1301 return data;
1304 return NULL;
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
1312 static void
1313 write_message_cb (GObject *source_object,
1314 GAsyncResult *res,
1315 gpointer user_data)
1317 MessageToWriteData *data = user_data;
1318 GError *error;
1320 g_mutex_lock (&data->worker->write_lock);
1321 g_assert (data->worker->output_pending == PENDING_WRITE);
1322 data->worker->output_pending = PENDING_NONE;
1324 error = NULL;
1325 if (!write_message_finish (res, &error))
1327 g_mutex_unlock (&data->worker->write_lock);
1329 /* TODO: handle */
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
1350 static void
1351 iostream_close_cb (GObject *source_object,
1352 GAsyncResult *res,
1353 gpointer user_data)
1355 GDBusWorker *worker = user_data;
1356 GError *error = NULL;
1357 GList *pending_close_attempts, *pending_flush_attempts;
1358 GQueue *send_queue;
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)
1387 if (error != NULL)
1388 g_task_return_error (close_data->task, g_error_copy (error));
1389 else
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
1415 static void
1416 continue_writing (GDBusWorker *worker)
1418 MessageToWriteData *data;
1419 FlushAsyncData *flush_async_data;
1421 write_next:
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);
1427 data = NULL;
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));
1445 else
1447 flush_async_data = prepare_flush_unlocked (worker);
1449 if (flush_async_data == NULL)
1451 data = g_queue_pop_head (worker->write_queue);
1453 if (data != NULL)
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;
1477 guchar *new_blob;
1478 gsize new_blob_size;
1479 GError *error;
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);
1494 goto write_next;
1496 else
1498 /* filters altered the message -> reencode */
1499 error = NULL;
1500 new_blob = g_dbus_message_to_blob (data->message,
1501 &new_blob_size,
1502 worker->capabilities,
1503 &error);
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),
1511 error->message);
1512 g_error_free (error);
1514 else
1516 g_free (data->blob);
1517 data->blob = (gchar *) new_blob;
1518 data->blob_size = new_blob_size;
1522 write_message_async (worker,
1523 data,
1524 write_message_cb,
1525 data);
1529 /* called in private thread shared by all GDBusConnection instances
1531 * write-lock is not held on entry
1532 * output_pending may be anything
1534 static gboolean
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);
1545 return FALSE;
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
1558 static void
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,
1572 close_data);
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);
1596 static void
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
1612 void
1613 _g_dbus_worker_send_message (GDBusWorker *worker,
1614 GDBusMessage *message,
1615 gchar *blob,
1616 gsize blob_len)
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 /* ---------------------------------------------------------------------------------------------------- */
1637 GDBusWorker *
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,
1644 gpointer user_data)
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 ();
1678 /* begin reading */
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);
1689 return worker;
1692 /* ---------------------------------------------------------------------------------------------------- */
1694 /* can be called from any thread
1696 * write_lock is not held on entry
1697 * output_pending may be anything
1699 void
1700 _g_dbus_worker_close (GDBusWorker *worker,
1701 GTask *task)
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
1725 void
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
1737 * commit 322e25b535
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
1751 gboolean
1752 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1753 GCancellable *cancellable,
1754 GError **error)
1756 gboolean ret;
1757 FlushData *data;
1758 guint64 pending_writes;
1760 data = NULL;
1761 ret = TRUE;
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);
1789 if (data != NULL)
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)
1799 ret = FALSE;
1800 g_propagate_error (error, data->error);
1802 g_free (data);
1805 return ret;
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;
1823 gboolean
1824 _g_dbus_debug_authentication (void)
1826 _g_dbus_initialize ();
1827 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1830 gboolean
1831 _g_dbus_debug_transport (void)
1833 _g_dbus_initialize ();
1834 return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1837 gboolean
1838 _g_dbus_debug_message (void)
1840 _g_dbus_initialize ();
1841 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1844 gboolean
1845 _g_dbus_debug_payload (void)
1847 _g_dbus_initialize ();
1848 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1851 gboolean
1852 _g_dbus_debug_call (void)
1854 _g_dbus_initialize ();
1855 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1858 gboolean
1859 _g_dbus_debug_signal (void)
1861 _g_dbus_initialize ();
1862 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1865 gboolean
1866 _g_dbus_debug_incoming (void)
1868 _g_dbus_initialize ();
1869 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1872 gboolean
1873 _g_dbus_debug_return (void)
1875 _g_dbus_initialize ();
1876 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1879 gboolean
1880 _g_dbus_debug_emission (void)
1882 _g_dbus_initialize ();
1883 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1886 gboolean
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);
1895 void
1896 _g_dbus_debug_print_lock (void)
1898 G_LOCK (print_lock);
1901 void
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
1915 void
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;
1923 const gchar *debug;
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");
1929 if (debug != NULL)
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 /* ---------------------------------------------------------------------------------------------------- */
1958 GVariantType *
1959 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1961 const GVariantType *arg_types[256];
1962 guint n;
1964 if (args)
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.
1970 g_assert (n < 256);
1972 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1974 if G_UNLIKELY (arg_types[n] == NULL)
1975 return NULL;
1977 else
1978 n = 0;
1980 return g_variant_type_new_tuple (arg_types, n);
1983 /* ---------------------------------------------------------------------------------------------------- */
1985 #ifdef G_OS_WIN32
1987 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1989 gchar *
1990 _g_dbus_win32_get_user_sid (void)
1992 HANDLE h;
1993 TOKEN_USER *user;
1994 DWORD token_information_len;
1995 PSID psid;
1996 gchar *sid;
1997 gchar *ret;
1999 ret = NULL;
2000 user = NULL;
2001 h = INVALID_HANDLE_VALUE;
2003 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
2005 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
2006 goto out;
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 ());
2016 goto out;
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 ());
2023 goto out;
2026 psid = user->User.Sid;
2027 if (!IsValidSid (psid))
2029 g_warning ("Invalid SID");
2030 goto out;
2033 if (!ConvertSidToStringSidA (psid, &sid))
2035 g_warning ("Invalid SID");
2036 goto out;
2039 ret = g_strdup (sid);
2040 LocalFree (sid);
2042 out:
2043 g_free (user);
2044 if (h != INVALID_HANDLE_VALUE)
2045 CloseHandle (h);
2046 return ret;
2048 #endif
2050 /* ---------------------------------------------------------------------------------------------------- */
2052 gchar *
2053 _g_dbus_get_machine_id (GError **error)
2055 #ifdef G_OS_WIN32
2056 HW_PROFILE_INFOA info;
2057 char *src, *dest, *res;
2058 int i;
2060 if (!GetCurrentHwProfileA (&info))
2062 char *message = g_win32_error_message (GetLastError ());
2063 g_set_error (error,
2064 G_IO_ERROR,
2065 G_IO_ERROR_FAILED,
2066 _("Unable to get Hardware profile: %s"), message);
2067 g_free (message);
2068 return NULL;
2071 /* Form: {12340001-4980-1920-6788-123456789012} */
2072 src = &info.szHwProfileGuid[0];
2074 res = g_malloc (32+1);
2075 dest = res;
2077 src++; /* Skip { */
2078 for (i = 0; i < 8; i++)
2079 *dest++ = *src++;
2080 src++; /* Skip - */
2081 for (i = 0; i < 4; i++)
2082 *dest++ = *src++;
2083 src++; /* Skip - */
2084 for (i = 0; i < 4; i++)
2085 *dest++ = *src++;
2086 src++; /* Skip - */
2087 for (i = 0; i < 4; i++)
2088 *dest++ = *src++;
2089 src++; /* Skip - */
2090 for (i = 0; i < 12; i++)
2091 *dest++ = *src++;
2092 *dest = 0;
2094 return res;
2095 #else
2096 gchar *ret;
2097 GError *first_error;
2098 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
2099 ret = NULL;
2100 first_error = NULL;
2101 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
2102 &ret,
2103 NULL,
2104 &first_error) &&
2105 !g_file_get_contents ("/etc/machine-id",
2106 &ret,
2107 NULL,
2108 NULL))
2110 g_propagate_prefixed_error (error, first_error,
2111 _("Unable to load /var/lib/dbus/machine-id or /etc/machine-id: "));
2113 else
2115 /* ignore the error from the first try, if any */
2116 g_clear_error (&first_error);
2117 /* TODO: validate value */
2118 g_strstrip (ret);
2120 return ret;
2121 #endif
2124 /* ---------------------------------------------------------------------------------------------------- */
2126 gchar *
2127 _g_dbus_enum_to_string (GType enum_type, gint value)
2129 gchar *ret;
2130 GEnumClass *klass;
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);
2137 else
2138 ret = g_strdup_printf ("unknown (value %d)", value);
2139 g_type_class_unref (klass);
2140 return ret;
2143 /* ---------------------------------------------------------------------------------------------------- */
2145 static void
2146 write_message_print_transport_debug (gssize bytes_written,
2147 MessageToWriteData *data)
2149 if (G_LIKELY (!_g_dbus_debug_transport ()))
2150 goto out;
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",
2157 bytes_written,
2158 g_dbus_message_get_serial (data->message),
2159 data->blob_size,
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 ();
2163 out:
2167 /* ---------------------------------------------------------------------------------------------------- */
2169 static void
2170 read_message_print_transport_debug (gssize bytes_read,
2171 GDBusWorker *worker)
2173 gsize size;
2174 gint32 serial;
2175 gint32 message_length;
2177 if (G_LIKELY (!_g_dbus_debug_transport ()))
2178 goto out;
2180 size = bytes_read + worker->read_buffer_cur_size;
2181 serial = 0;
2182 message_length = 0;
2183 if (size >= 16)
2184 message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2185 if (size >= 1)
2187 switch (worker->read_buffer[0])
2189 case 'l':
2190 if (size >= 12)
2191 serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2192 break;
2193 case 'B':
2194 if (size >= 12)
2195 serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2196 break;
2197 default:
2198 /* an error will be set elsewhere if this happens */
2199 goto out;
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",
2208 bytes_read,
2209 serial,
2210 message_length,
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 ();
2214 out:
2218 /* ---------------------------------------------------------------------------------------------------- */
2220 gboolean
2221 _g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2222 GValue *return_accu,
2223 const GValue *handler_return,
2224 gpointer dummy)
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 /* ---------------------------------------------------------------------------------------------------- */
2238 static void
2239 append_nibble (GString *s, gint val)
2241 g_string_append_c (s, val >= 10 ? ('a' + val - 10) : ('0' + val));
2244 /* ---------------------------------------------------------------------------------------------------- */
2246 gchar *
2247 _g_dbus_hexencode (const gchar *str,
2248 gsize str_len)
2250 gsize n;
2251 GString *s;
2253 s = g_string_new (NULL);
2254 for (n = 0; n < str_len; n++)
2256 gint val;
2257 gint upper_nibble;
2258 gint lower_nibble;
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);