1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
33 #include "gdbusprivate.h"
34 #include "gdbusmessage.h"
35 #include "gdbuserror.h"
36 #include "gdbusintrospection.h"
37 #include "gasyncresult.h"
38 #include "gsimpleasyncresult.h"
39 #include "ginputstream.h"
40 #include "giostream.h"
41 #include "gsocketcontrolmessage.h"
42 #include "gsocketconnection.h"
45 #include "gunixfdmessage.h"
46 #include "gunixconnection.h"
47 #include "gunixcredentialsmessage.h"
56 /* ---------------------------------------------------------------------------------------------------- */
59 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
64 ret = g_string_new (NULL);
66 for (n = 0; n < len; n += 16)
68 g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
70 for (m = n; m < n + 16; m++)
72 if (m > n && (m%4) == 0)
73 g_string_append_c (ret, ' ');
75 g_string_append_printf (ret, "%02x ", (guchar) data[m]);
77 g_string_append (ret, " ");
80 g_string_append (ret, " ");
82 for (m = n; m < len && m < n + 16; m++)
83 g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
85 g_string_append_c (ret, '\n');
88 return g_string_free (ret, FALSE);
91 /* ---------------------------------------------------------------------------------------------------- */
93 /* Unfortunately ancillary messages are discarded when reading from a
94 * socket using the GSocketInputStream abstraction. So we provide a
95 * very GInputStream-ish API that uses GSocket in this case (very
96 * similar to GSocketInputStream).
102 GCancellable *cancellable;
107 GSocketControlMessage ***messages;
110 GSimpleAsyncResult *simple;
112 gboolean from_mainloop;
113 } ReadWithControlData;
116 read_with_control_data_free (ReadWithControlData *data)
118 g_object_unref (data->socket);
119 if (data->cancellable != NULL)
120 g_object_unref (data->cancellable);
121 g_object_unref (data->simple);
126 _g_socket_read_with_control_messages_ready (GSocket *socket,
127 GIOCondition condition,
130 ReadWithControlData *data = user_data;
136 vector.buffer = data->buffer;
137 vector.size = data->count;
138 result = g_socket_receive_message (data->socket,
149 g_simple_async_result_set_op_res_gssize (data->simple, result);
153 g_assert (error != NULL);
154 g_simple_async_result_set_from_error (data->simple, error);
155 g_error_free (error);
158 if (data->from_mainloop)
159 g_simple_async_result_complete (data->simple);
161 g_simple_async_result_complete_in_idle (data->simple);
167 _g_socket_read_with_control_messages (GSocket *socket,
170 GSocketControlMessage ***messages,
173 GCancellable *cancellable,
174 GAsyncReadyCallback callback,
177 ReadWithControlData *data;
179 data = g_new0 (ReadWithControlData, 1);
180 data->socket = g_object_ref (socket);
181 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
182 data->buffer = buffer;
184 data->messages = messages;
185 data->num_messages = num_messages;
187 data->simple = g_simple_async_result_new (G_OBJECT (socket),
190 _g_socket_read_with_control_messages);
192 if (!g_socket_condition_check (socket, G_IO_IN))
195 data->from_mainloop = TRUE;
196 source = g_socket_create_source (data->socket,
197 G_IO_IN | G_IO_HUP | G_IO_ERR,
199 g_source_set_callback (source,
200 (GSourceFunc) _g_socket_read_with_control_messages_ready,
202 (GDestroyNotify) read_with_control_data_free);
203 g_source_attach (source, g_main_context_get_thread_default ());
204 g_source_unref (source);
208 _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
209 read_with_control_data_free (data);
214 _g_socket_read_with_control_messages_finish (GSocket *socket,
215 GAsyncResult *result,
218 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
220 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
221 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
223 if (g_simple_async_result_propagate_error (simple, error))
226 return g_simple_async_result_get_op_res_gssize (simple);
229 /* ---------------------------------------------------------------------------------------------------- */
231 G_LOCK_DEFINE_STATIC (shared_thread_lock);
237 GMainContext *context;
241 static SharedThreadData *shared_thread_data = NULL;
244 shared_thread_func (gpointer data)
246 g_main_context_push_thread_default (shared_thread_data->context);
247 g_main_loop_run (shared_thread_data->loop);
248 g_main_context_pop_thread_default (shared_thread_data->context);
252 typedef void (*GDBusSharedThreadFunc) (gpointer user_data);
256 GDBusSharedThreadFunc func;
262 invoke_caller (gpointer user_data)
264 CallerData *data = user_data;
265 data->func (data->user_data);
271 _g_dbus_shared_thread_ref (GDBusSharedThreadFunc func,
275 GSource *idle_source;
278 G_LOCK (shared_thread_lock);
280 if (shared_thread_data != NULL)
282 shared_thread_data->num_users += 1;
286 shared_thread_data = g_new0 (SharedThreadData, 1);
287 shared_thread_data->num_users = 1;
290 shared_thread_data->context = g_main_context_new ();
291 shared_thread_data->loop = g_main_loop_new (shared_thread_data->context, FALSE);
292 shared_thread_data->thread = g_thread_create (shared_thread_func,
296 g_assert_no_error (error);
300 data = g_new0 (CallerData, 1);
302 data->user_data = user_data;
305 idle_source = g_idle_source_new ();
306 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
307 g_source_set_callback (idle_source,
311 g_source_attach (idle_source, shared_thread_data->context);
312 g_source_unref (idle_source);
314 /* wait for the user code to run.. hmm.. probably use a condition variable instead */
320 G_UNLOCK (shared_thread_lock);
324 _g_dbus_shared_thread_unref (void)
326 /* TODO: actually destroy the shared thread here */
328 G_LOCK (shared_thread_lock);
329 g_assert (shared_thread_data != NULL);
330 shared_thread_data->num_users -= 1;
331 if (shared_thread_data->num_users == 0)
333 g_main_loop_quit (shared_thread_data->loop);
334 //g_thread_join (shared_thread_data->thread);
335 g_main_loop_unref (shared_thread_data->loop);
336 g_main_context_unref (shared_thread_data->context);
337 g_free (shared_thread_data);
338 shared_thread_data = NULL;
339 G_UNLOCK (shared_thread_lock);
343 G_UNLOCK (shared_thread_lock);
348 /* ---------------------------------------------------------------------------------------------------- */
352 volatile gint ref_count;
356 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
357 * only affects messages received from the other peer (since GDBusServer is the
358 * only user) - we might want it to affect messages sent to the other peer too?
361 GQueue *received_messages_while_frozen;
364 GDBusCapabilityFlags capabilities;
365 GCancellable *cancellable;
366 GDBusWorkerMessageReceivedCallback message_received_callback;
367 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
368 GDBusWorkerDisconnectedCallback disconnected_callback;
373 /* if not NULL, stream is GSocketConnection */
376 /* used for reading */
379 gsize read_buffer_allocated_size;
380 gsize read_buffer_cur_size;
381 gsize read_buffer_bytes_wanted;
382 GUnixFDList *read_fd_list;
383 GSocketControlMessage **read_ancillary_messages;
384 gint read_num_ancillary_messages;
386 /* used for writing */
389 gboolean write_is_pending;
390 guint64 write_num_messages_written;
391 GList *write_pending_flushes;
398 guint64 number_to_wait_for;
401 struct _MessageToWriteData ;
402 typedef struct _MessageToWriteData MessageToWriteData;
404 static void message_to_write_data_free (MessageToWriteData *data);
407 _g_dbus_worker_ref (GDBusWorker *worker)
409 g_atomic_int_inc (&worker->ref_count);
414 _g_dbus_worker_unref (GDBusWorker *worker)
416 if (g_atomic_int_dec_and_test (&worker->ref_count))
418 g_assert (worker->write_pending_flushes == NULL);
420 _g_dbus_shared_thread_unref ();
422 g_object_unref (worker->stream);
424 g_mutex_free (worker->read_lock);
425 g_object_unref (worker->cancellable);
426 if (worker->read_fd_list != NULL)
427 g_object_unref (worker->read_fd_list);
429 g_queue_foreach (worker->received_messages_while_frozen, (GFunc) g_object_unref, NULL);
430 g_queue_free (worker->received_messages_while_frozen);
432 g_mutex_free (worker->write_lock);
433 g_queue_foreach (worker->write_queue, (GFunc) message_to_write_data_free, NULL);
434 g_queue_free (worker->write_queue);
441 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
442 gboolean remote_peer_vanished,
445 if (!worker->stopped)
446 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
450 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
451 GDBusMessage *message)
453 if (!worker->stopped)
454 worker->message_received_callback (worker, message, worker->user_data);
458 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
459 GDBusMessage *message)
463 if (!worker->stopped)
464 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
468 /* can only be called from private thread with read-lock held - takes ownership of @message */
470 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
471 GDBusMessage *message)
473 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
476 g_queue_push_tail (worker->received_messages_while_frozen, message);
480 /* not frozen, nor anything in queue */
481 _g_dbus_worker_emit_message_received (worker, message);
482 g_object_unref (message);
486 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
488 unfreeze_in_idle_cb (gpointer user_data)
490 GDBusWorker *worker = user_data;
491 GDBusMessage *message;
493 g_mutex_lock (worker->read_lock);
496 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
498 _g_dbus_worker_emit_message_received (worker, message);
499 g_object_unref (message);
501 worker->frozen = FALSE;
505 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
507 g_mutex_unlock (worker->read_lock);
511 /* can be called from any thread */
513 _g_dbus_worker_unfreeze (GDBusWorker *worker)
515 GSource *idle_source;
516 idle_source = g_idle_source_new ();
517 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
518 g_source_set_callback (idle_source,
520 _g_dbus_worker_ref (worker),
521 (GDestroyNotify) _g_dbus_worker_unref);
522 g_source_attach (idle_source, shared_thread_data->context);
523 g_source_unref (idle_source);
526 /* ---------------------------------------------------------------------------------------------------- */
528 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
530 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
532 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
536 GDBusWorker *worker = user_data;
540 g_mutex_lock (worker->read_lock);
542 /* If already stopped, don't even process the reply */
547 if (worker->socket == NULL)
548 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
552 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
555 if (worker->read_num_ancillary_messages > 0)
558 for (n = 0; n < worker->read_num_ancillary_messages; n++)
560 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
566 else if (G_IS_UNIX_FD_MESSAGE (control_message))
568 GUnixFDMessage *fd_message;
572 fd_message = G_UNIX_FD_MESSAGE (control_message);
573 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
574 if (worker->read_fd_list == NULL)
576 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
581 for (n = 0; n < num_fds; n++)
583 /* TODO: really want a append_steal() */
584 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
590 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
602 "Unexpected ancillary message of type %s received from peer",
603 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
604 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
605 g_error_free (error);
606 g_object_unref (control_message);
608 while (n < worker->read_num_ancillary_messages)
609 g_object_unref (worker->read_ancillary_messages[n++]);
610 g_free (worker->read_ancillary_messages);
614 g_object_unref (control_message);
616 g_free (worker->read_ancillary_messages);
619 if (bytes_read == -1)
621 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
622 g_error_free (error);
627 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
629 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
630 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
631 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
632 G_IO_IN | G_IO_OUT | G_IO_HUP),
637 /* TODO: hmm, hmm... */
643 "Underlying GIOStream returned 0 bytes on an async read");
644 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
645 g_error_free (error);
649 worker->read_buffer_cur_size += bytes_read;
650 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
652 /* OK, got what we asked for! */
653 if (worker->read_buffer_bytes_wanted == 16)
656 /* OK, got the header - determine how many more bytes are needed */
658 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
661 if (message_len == -1)
663 g_warning ("_g_dbus_worker_do_read_cb: error determing bytes needed: %s", error->message);
664 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
665 g_error_free (error);
669 worker->read_buffer_bytes_wanted = message_len;
670 _g_dbus_worker_do_read_unlocked (worker);
674 GDBusMessage *message;
677 /* TODO: use connection->priv->auth to decode the message */
679 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
680 worker->read_buffer_cur_size,
681 worker->capabilities,
686 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
687 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
689 "The payload is as follows:\n"
691 worker->read_buffer_cur_size,
695 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
696 g_error_free (error);
701 if (worker->read_fd_list != NULL)
703 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
704 worker->read_fd_list = NULL;
708 if (G_UNLIKELY (_g_dbus_debug_message ()))
711 _g_dbus_debug_print_lock ();
712 g_print ("========================================================================\n"
713 "GDBus-debug:Message:\n"
714 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
715 worker->read_buffer_cur_size);
716 s = g_dbus_message_print (message, 2);
719 if (G_UNLIKELY (_g_dbus_debug_payload ()))
721 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
725 _g_dbus_debug_print_unlock ();
728 /* yay, got a message, go deliver it */
729 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
731 /* start reading another message! */
732 worker->read_buffer_bytes_wanted = 0;
733 worker->read_buffer_cur_size = 0;
734 _g_dbus_worker_do_read_unlocked (worker);
739 /* didn't get all the bytes we requested - so repeat the request... */
740 _g_dbus_worker_do_read_unlocked (worker);
744 g_mutex_unlock (worker->read_lock);
746 /* gives up the reference acquired when calling g_input_stream_read_async() */
747 _g_dbus_worker_unref (worker);
750 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
752 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
754 /* if bytes_wanted is zero, it means start reading a message */
755 if (worker->read_buffer_bytes_wanted == 0)
757 worker->read_buffer_cur_size = 0;
758 worker->read_buffer_bytes_wanted = 16;
761 /* ensure we have a (big enough) buffer */
762 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
764 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
765 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
766 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
769 if (worker->socket == NULL)
770 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
771 worker->read_buffer + worker->read_buffer_cur_size,
772 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
775 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
776 _g_dbus_worker_ref (worker));
779 worker->read_ancillary_messages = NULL;
780 worker->read_num_ancillary_messages = 0;
781 _g_socket_read_with_control_messages (worker->socket,
782 worker->read_buffer + worker->read_buffer_cur_size,
783 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
784 &worker->read_ancillary_messages,
785 &worker->read_num_ancillary_messages,
788 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
789 _g_dbus_worker_ref (worker));
793 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
795 _g_dbus_worker_do_read (GDBusWorker *worker)
797 g_mutex_lock (worker->read_lock);
798 _g_dbus_worker_do_read_unlocked (worker);
799 g_mutex_unlock (worker->read_lock);
802 /* ---------------------------------------------------------------------------------------------------- */
804 struct _MessageToWriteData
806 GDBusMessage *message;
812 message_to_write_data_free (MessageToWriteData *data)
814 g_object_unref (data->message);
819 /* ---------------------------------------------------------------------------------------------------- */
821 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
823 write_message (GDBusWorker *worker,
824 MessageToWriteData *data,
831 g_return_val_if_fail (data->blob_size > 16, FALSE);
835 /* First, the initial 16 bytes - special case UNIX sockets here
836 * since it may involve writing an ancillary message with file
841 GOutputVector vector;
842 GSocketControlMessage *message;
843 GUnixFDList *fd_list;
844 gssize bytes_written;
846 fd_list = g_dbus_message_get_unix_fd_list (data->message);
851 if (!G_IS_UNIX_CONNECTION (worker->stream))
855 G_IO_ERROR_INVALID_ARGUMENT,
856 "Tried sending a file descriptor on unsupported stream of type %s",
857 g_type_name (G_TYPE_FROM_INSTANCE (worker->stream)));
860 else if (!(worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
862 g_set_error_literal (error,
864 G_IO_ERROR_INVALID_ARGUMENT,
865 "Tried sending a file descriptor but remote peer does not support this capability");
868 message = g_unix_fd_message_new_with_fd_list (fd_list);
871 vector.buffer = data->blob;
874 bytes_written = g_socket_send_message (worker->socket,
878 message != NULL ? &message : NULL,
879 message != NULL ? 1 : 0,
883 if (bytes_written == -1)
885 g_prefix_error (error, _("Error writing first 16 bytes of message to socket: "));
887 g_object_unref (message);
891 g_object_unref (message);
893 if (bytes_written < 16)
895 /* TODO: I think this needs to be handled ... are we guaranteed that the ancillary
898 g_assert_not_reached ();
902 /* write the first 16 bytes (guaranteed to return an error if everything can't be written) */
903 if (!g_output_stream_write_all (g_io_stream_get_output_stream (worker->stream),
904 (const gchar *) data->blob,
906 NULL, /* bytes_written */
907 worker->cancellable, /* cancellable */
912 /* Then write the rest of the message (guaranteed to return an error if everything can't be written) */
913 if (!g_output_stream_write_all (g_io_stream_get_output_stream (worker->stream),
914 (const gchar *) data->blob + 16,
915 data->blob_size - 16,
916 NULL, /* bytes_written */
917 worker->cancellable, /* cancellable */
923 /* wake up pending flushes */
924 g_mutex_lock (worker->write_lock);
925 worker->write_num_messages_written += 1;
926 for (l = worker->write_pending_flushes; l != NULL; l = ll)
928 FlushData *f = l->data;
931 if (f->number_to_wait_for == worker->write_num_messages_written)
933 g_mutex_lock (f->mutex);
934 g_cond_signal (f->cond);
935 g_mutex_unlock (f->mutex);
936 worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
939 g_mutex_unlock (worker->write_lock);
941 if (G_UNLIKELY (_g_dbus_debug_message ()))
944 _g_dbus_debug_print_lock ();
945 g_print ("========================================================================\n"
946 "GDBus-debug:Message:\n"
947 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
949 s = g_dbus_message_print (data->message, 2);
952 if (G_UNLIKELY (_g_dbus_debug_payload ()))
954 s = _g_dbus_hexdump (data->blob, data->blob_size, 2);
958 _g_dbus_debug_print_unlock ();
965 /* ---------------------------------------------------------------------------------------------------- */
967 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
969 write_message_in_idle_cb (gpointer user_data)
971 GDBusWorker *worker = user_data;
972 gboolean more_writes_are_pending;
973 MessageToWriteData *data;
974 gboolean message_was_dropped;
977 g_mutex_lock (worker->write_lock);
978 data = g_queue_pop_head (worker->write_queue);
979 g_assert (data != NULL);
980 more_writes_are_pending = (g_queue_get_length (worker->write_queue) > 0);
981 worker->write_is_pending = more_writes_are_pending;
982 g_mutex_unlock (worker->write_lock);
984 /* Note that write_lock is only used for protecting the @write_queue
985 * and @write_is_pending fields of the GDBusWorker struct ... which we
986 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
988 * Therefore, it's fine to drop it here when calling back into user
989 * code and then writing the message out onto the GIOStream since this
990 * function only runs on the worker thread.
992 message_was_dropped = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
993 if (G_LIKELY (!message_was_dropped))
996 if (!write_message (worker,
1001 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
1002 g_error_free (error);
1005 message_to_write_data_free (data);
1007 return more_writes_are_pending;
1010 /* ---------------------------------------------------------------------------------------------------- */
1012 /* can be called from any thread - steals blob */
1014 _g_dbus_worker_send_message (GDBusWorker *worker,
1015 GDBusMessage *message,
1019 MessageToWriteData *data;
1021 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1022 g_return_if_fail (blob != NULL);
1023 g_return_if_fail (blob_len > 16);
1025 data = g_new0 (MessageToWriteData, 1);
1026 data->message = g_object_ref (message);
1027 data->blob = blob; /* steal! */
1028 data->blob_size = blob_len;
1030 g_mutex_lock (worker->write_lock);
1031 g_queue_push_tail (worker->write_queue, data);
1032 if (!worker->write_is_pending)
1034 GSource *idle_source;
1036 worker->write_is_pending = TRUE;
1038 idle_source = g_idle_source_new ();
1039 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1040 g_source_set_callback (idle_source,
1041 write_message_in_idle_cb,
1042 _g_dbus_worker_ref (worker),
1043 (GDestroyNotify) _g_dbus_worker_unref);
1044 g_source_attach (idle_source, shared_thread_data->context);
1045 g_source_unref (idle_source);
1047 g_mutex_unlock (worker->write_lock);
1050 /* ---------------------------------------------------------------------------------------------------- */
1053 _g_dbus_worker_thread_begin_func (gpointer user_data)
1055 GDBusWorker *worker = user_data;
1057 worker->thread = g_thread_self ();
1060 _g_dbus_worker_do_read (worker);
1064 _g_dbus_worker_new (GIOStream *stream,
1065 GDBusCapabilityFlags capabilities,
1066 gboolean initially_frozen,
1067 GDBusWorkerMessageReceivedCallback message_received_callback,
1068 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1069 GDBusWorkerDisconnectedCallback disconnected_callback,
1072 GDBusWorker *worker;
1074 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1075 g_return_val_if_fail (message_received_callback != NULL, NULL);
1076 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1077 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1079 worker = g_new0 (GDBusWorker, 1);
1080 worker->ref_count = 1;
1082 worker->read_lock = g_mutex_new ();
1083 worker->message_received_callback = message_received_callback;
1084 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1085 worker->disconnected_callback = disconnected_callback;
1086 worker->user_data = user_data;
1087 worker->stream = g_object_ref (stream);
1088 worker->capabilities = capabilities;
1089 worker->cancellable = g_cancellable_new ();
1091 worker->frozen = initially_frozen;
1092 worker->received_messages_while_frozen = g_queue_new ();
1094 worker->write_lock = g_mutex_new ();
1095 worker->write_queue = g_queue_new ();
1097 if (G_IS_SOCKET_CONNECTION (worker->stream))
1098 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1100 _g_dbus_shared_thread_ref (_g_dbus_worker_thread_begin_func, worker);
1105 /* ---------------------------------------------------------------------------------------------------- */
1107 /* This can be called from any thread - frees worker - guarantees no callbacks
1108 * will ever be issued again
1111 _g_dbus_worker_stop (GDBusWorker *worker)
1113 /* If we're called in the worker thread it means we are called from
1114 * a worker callback. This is fine, we just can't lock in that case since
1115 * we're already holding the lock...
1117 if (g_thread_self () != worker->thread)
1118 g_mutex_lock (worker->read_lock);
1119 worker->stopped = TRUE;
1120 if (g_thread_self () != worker->thread)
1121 g_mutex_unlock (worker->read_lock);
1123 g_cancellable_cancel (worker->cancellable);
1124 _g_dbus_worker_unref (worker);
1127 /* ---------------------------------------------------------------------------------------------------- */
1129 /* can be called from any thread (except the worker thread) - blocks
1130 * calling thread until all queued outgoing messages are written and
1131 * the transport has been flushed
1134 _g_dbus_worker_flush_sync (GDBusWorker *worker,
1135 GCancellable *cancellable,
1143 /* if the queue is empty, there's nothing to wait for */
1144 g_mutex_lock (worker->write_lock);
1145 if (g_queue_get_length (worker->write_queue) > 0)
1147 data = g_new0 (FlushData, 1);
1148 data->mutex = g_mutex_new ();
1149 data->cond = g_cond_new ();
1150 data->number_to_wait_for = worker->write_num_messages_written + g_queue_get_length (worker->write_queue);
1151 g_mutex_lock (data->mutex);
1152 worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, data);
1154 g_mutex_unlock (worker->write_lock);
1158 g_cond_wait (data->cond, data->mutex);
1159 g_mutex_unlock (data->mutex);
1161 /* note:the element is removed from worker->write_pending_flushes in write_message() */
1162 g_cond_free (data->cond);
1163 g_mutex_free (data->mutex);
1167 ret = g_output_stream_flush (g_io_stream_get_output_stream (worker->stream),
1173 /* ---------------------------------------------------------------------------------------------------- */
1175 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1176 #define G_DBUS_DEBUG_MESSAGE (1<<1)
1177 #define G_DBUS_DEBUG_PAYLOAD (1<<2)
1178 #define G_DBUS_DEBUG_CALL (1<<3)
1179 #define G_DBUS_DEBUG_SIGNAL (1<<4)
1180 #define G_DBUS_DEBUG_INCOMING (1<<5)
1181 #define G_DBUS_DEBUG_RETURN (1<<6)
1182 #define G_DBUS_DEBUG_EMISSION (1<<7)
1183 #define G_DBUS_DEBUG_ADDRESS (1<<8)
1185 static gint _gdbus_debug_flags = 0;
1188 _g_dbus_debug_authentication (void)
1190 _g_dbus_initialize ();
1191 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1195 _g_dbus_debug_message (void)
1197 _g_dbus_initialize ();
1198 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1202 _g_dbus_debug_payload (void)
1204 _g_dbus_initialize ();
1205 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1209 _g_dbus_debug_call (void)
1211 _g_dbus_initialize ();
1212 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1216 _g_dbus_debug_signal (void)
1218 _g_dbus_initialize ();
1219 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1223 _g_dbus_debug_incoming (void)
1225 _g_dbus_initialize ();
1226 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1230 _g_dbus_debug_return (void)
1232 _g_dbus_initialize ();
1233 return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1237 _g_dbus_debug_emission (void)
1239 _g_dbus_initialize ();
1240 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1244 _g_dbus_debug_address (void)
1246 _g_dbus_initialize ();
1247 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1250 G_LOCK_DEFINE_STATIC (print_lock);
1253 _g_dbus_debug_print_lock (void)
1255 G_LOCK (print_lock);
1259 _g_dbus_debug_print_unlock (void)
1261 G_UNLOCK (print_lock);
1265 * _g_dbus_initialize:
1267 * Does various one-time init things such as
1269 * - registering the G_DBUS_ERROR error domain
1270 * - parses the G_DBUS_DEBUG environment variable
1273 _g_dbus_initialize (void)
1275 static volatile gsize initialized = 0;
1277 if (g_once_init_enter (&initialized))
1279 volatile GQuark g_dbus_error_domain;
1282 g_dbus_error_domain = G_DBUS_ERROR;
1284 debug = g_getenv ("G_DBUS_DEBUG");
1287 const GDebugKey keys[] = {
1288 { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1289 { "message", G_DBUS_DEBUG_MESSAGE },
1290 { "payload", G_DBUS_DEBUG_PAYLOAD },
1291 { "call", G_DBUS_DEBUG_CALL },
1292 { "signal", G_DBUS_DEBUG_SIGNAL },
1293 { "incoming", G_DBUS_DEBUG_INCOMING },
1294 { "return", G_DBUS_DEBUG_RETURN },
1295 { "emission", G_DBUS_DEBUG_EMISSION },
1296 { "address", G_DBUS_DEBUG_ADDRESS }
1299 _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1300 if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1301 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1304 g_once_init_leave (&initialized, 1);
1308 /* ---------------------------------------------------------------------------------------------------- */
1311 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1313 const GVariantType *arg_types[256];
1317 for (n = 0; args[n] != NULL; n++)
1319 /* DBus places a hard limit of 255 on signature length.
1320 * therefore number of args must be less than 256.
1324 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1326 if G_UNLIKELY (arg_types[n] == NULL)
1332 return g_variant_type_new_tuple (arg_types, n);
1335 /* ---------------------------------------------------------------------------------------------------- */
1339 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1342 _g_dbus_win32_get_user_sid (void)
1346 DWORD token_information_len;
1353 h = INVALID_HANDLE_VALUE;
1355 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
1357 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
1361 /* Get length of buffer */
1362 token_information_len = 0;
1363 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
1365 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1367 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1371 user = g_malloc (token_information_len);
1372 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
1374 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1378 psid = user->User.Sid;
1379 if (!IsValidSid (psid))
1381 g_warning ("Invalid SID");
1385 if (!ConvertSidToStringSidA (psid, &sid))
1387 g_warning ("Invalid SID");
1391 ret = g_strdup (sid);
1396 if (h != INVALID_HANDLE_VALUE)
1402 /* ---------------------------------------------------------------------------------------------------- */
1405 _g_dbus_get_machine_id (GError **error)
1408 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
1410 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
1415 g_prefix_error (error, _("Unable to load /var/lib/dbus/machine-id: "));
1419 /* TODO: validate value */
1425 /* ---------------------------------------------------------------------------------------------------- */
1428 _g_dbus_enum_to_string (GType enum_type, gint value)
1432 GEnumValue *enum_value;
1434 klass = g_type_class_ref (enum_type);
1435 enum_value = g_enum_get_value (klass, value);
1436 if (enum_value != NULL)
1437 ret = g_strdup (enum_value->value_nick);
1439 ret = g_strdup_printf ("unknown (value %d)", value);
1440 g_type_class_unref (klass);
1444 /* ---------------------------------------------------------------------------------------------------- */