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"
57 /* ---------------------------------------------------------------------------------------------------- */
60 _g_dbus_hexdump (const gchar *data, gsize len, guint indent)
65 ret = g_string_new (NULL);
67 for (n = 0; n < len; n += 16)
69 g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
71 for (m = n; m < n + 16; m++)
73 if (m > n && (m%4) == 0)
74 g_string_append_c (ret, ' ');
76 g_string_append_printf (ret, "%02x ", (guchar) data[m]);
78 g_string_append (ret, " ");
81 g_string_append (ret, " ");
83 for (m = n; m < len && m < n + 16; m++)
84 g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
86 g_string_append_c (ret, '\n');
89 return g_string_free (ret, FALSE);
92 /* ---------------------------------------------------------------------------------------------------- */
94 /* Unfortunately ancillary messages are discarded when reading from a
95 * socket using the GSocketInputStream abstraction. So we provide a
96 * very GInputStream-ish API that uses GSocket in this case (very
97 * similar to GSocketInputStream).
103 GCancellable *cancellable;
108 GSocketControlMessage ***messages;
111 GSimpleAsyncResult *simple;
113 gboolean from_mainloop;
114 } ReadWithControlData;
117 read_with_control_data_free (ReadWithControlData *data)
119 g_object_unref (data->socket);
120 if (data->cancellable != NULL)
121 g_object_unref (data->cancellable);
122 g_object_unref (data->simple);
127 _g_socket_read_with_control_messages_ready (GSocket *socket,
128 GIOCondition condition,
131 ReadWithControlData *data = user_data;
137 vector.buffer = data->buffer;
138 vector.size = data->count;
139 result = g_socket_receive_message (data->socket,
150 g_simple_async_result_set_op_res_gssize (data->simple, result);
154 g_assert (error != NULL);
155 g_simple_async_result_set_from_error (data->simple, error);
156 g_error_free (error);
159 if (data->from_mainloop)
160 g_simple_async_result_complete (data->simple);
162 g_simple_async_result_complete_in_idle (data->simple);
168 _g_socket_read_with_control_messages (GSocket *socket,
171 GSocketControlMessage ***messages,
174 GCancellable *cancellable,
175 GAsyncReadyCallback callback,
178 ReadWithControlData *data;
180 data = g_new0 (ReadWithControlData, 1);
181 data->socket = g_object_ref (socket);
182 data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
183 data->buffer = buffer;
185 data->messages = messages;
186 data->num_messages = num_messages;
188 data->simple = g_simple_async_result_new (G_OBJECT (socket),
191 _g_socket_read_with_control_messages);
193 if (!g_socket_condition_check (socket, G_IO_IN))
196 data->from_mainloop = TRUE;
197 source = g_socket_create_source (data->socket,
198 G_IO_IN | G_IO_HUP | G_IO_ERR,
200 g_source_set_callback (source,
201 (GSourceFunc) _g_socket_read_with_control_messages_ready,
203 (GDestroyNotify) read_with_control_data_free);
204 g_source_attach (source, g_main_context_get_thread_default ());
205 g_source_unref (source);
209 _g_socket_read_with_control_messages_ready (data->socket, G_IO_IN, data);
210 read_with_control_data_free (data);
215 _g_socket_read_with_control_messages_finish (GSocket *socket,
216 GAsyncResult *result,
219 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
221 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
222 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == _g_socket_read_with_control_messages);
224 if (g_simple_async_result_propagate_error (simple, error))
227 return g_simple_async_result_get_op_res_gssize (simple);
230 /* ---------------------------------------------------------------------------------------------------- */
232 G_LOCK_DEFINE_STATIC (shared_thread_lock);
238 GMainContext *context;
242 static SharedThreadData *shared_thread_data = NULL;
245 shared_thread_func (gpointer data)
247 g_main_context_push_thread_default (shared_thread_data->context);
248 g_main_loop_run (shared_thread_data->loop);
249 g_main_context_pop_thread_default (shared_thread_data->context);
253 typedef void (*GDBusSharedThreadFunc) (gpointer user_data);
257 GDBusSharedThreadFunc func;
263 invoke_caller (gpointer user_data)
265 CallerData *data = user_data;
266 data->func (data->user_data);
272 _g_dbus_shared_thread_ref (GDBusSharedThreadFunc func,
276 GSource *idle_source;
279 G_LOCK (shared_thread_lock);
281 if (shared_thread_data != NULL)
283 shared_thread_data->num_users += 1;
287 shared_thread_data = g_new0 (SharedThreadData, 1);
288 shared_thread_data->num_users = 1;
291 shared_thread_data->context = g_main_context_new ();
292 shared_thread_data->loop = g_main_loop_new (shared_thread_data->context, FALSE);
293 shared_thread_data->thread = g_thread_create (shared_thread_func,
297 g_assert_no_error (error);
301 data = g_new0 (CallerData, 1);
303 data->user_data = user_data;
306 idle_source = g_idle_source_new ();
307 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
308 g_source_set_callback (idle_source,
312 g_source_attach (idle_source, shared_thread_data->context);
313 g_source_unref (idle_source);
315 /* wait for the user code to run.. hmm.. probably use a condition variable instead */
321 G_UNLOCK (shared_thread_lock);
325 _g_dbus_shared_thread_unref (void)
327 /* TODO: actually destroy the shared thread here */
329 G_LOCK (shared_thread_lock);
330 g_assert (shared_thread_data != NULL);
331 shared_thread_data->num_users -= 1;
332 if (shared_thread_data->num_users == 0)
334 g_main_loop_quit (shared_thread_data->loop);
335 //g_thread_join (shared_thread_data->thread);
336 g_main_loop_unref (shared_thread_data->loop);
337 g_main_context_unref (shared_thread_data->context);
338 g_free (shared_thread_data);
339 shared_thread_data = NULL;
340 G_UNLOCK (shared_thread_lock);
344 G_UNLOCK (shared_thread_lock);
349 /* ---------------------------------------------------------------------------------------------------- */
353 volatile gint ref_count;
357 /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
358 * only affects messages received from the other peer (since GDBusServer is the
359 * only user) - we might want it to affect messages sent to the other peer too?
362 GQueue *received_messages_while_frozen;
365 GDBusCapabilityFlags capabilities;
366 GCancellable *cancellable;
367 GDBusWorkerMessageReceivedCallback message_received_callback;
368 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
369 GDBusWorkerDisconnectedCallback disconnected_callback;
374 /* if not NULL, stream is GSocketConnection */
377 /* used for reading */
380 gsize read_buffer_allocated_size;
381 gsize read_buffer_cur_size;
382 gsize read_buffer_bytes_wanted;
383 GUnixFDList *read_fd_list;
384 GSocketControlMessage **read_ancillary_messages;
385 gint read_num_ancillary_messages;
387 /* used for writing */
390 gboolean write_is_pending;
393 struct _MessageToWriteData ;
394 typedef struct _MessageToWriteData MessageToWriteData;
396 static void message_to_write_data_free (MessageToWriteData *data);
399 _g_dbus_worker_ref (GDBusWorker *worker)
401 g_atomic_int_inc (&worker->ref_count);
406 _g_dbus_worker_unref (GDBusWorker *worker)
408 if (g_atomic_int_dec_and_test (&worker->ref_count))
410 _g_dbus_shared_thread_unref ();
412 g_object_unref (worker->stream);
414 g_mutex_free (worker->read_lock);
415 g_object_unref (worker->cancellable);
416 if (worker->read_fd_list != NULL)
417 g_object_unref (worker->read_fd_list);
419 g_queue_foreach (worker->received_messages_while_frozen, (GFunc) g_object_unref, NULL);
420 g_queue_free (worker->received_messages_while_frozen);
422 g_mutex_free (worker->write_lock);
423 g_queue_foreach (worker->write_queue, (GFunc) message_to_write_data_free, NULL);
424 g_queue_free (worker->write_queue);
431 _g_dbus_worker_emit_disconnected (GDBusWorker *worker,
432 gboolean remote_peer_vanished,
435 if (!worker->stopped)
436 worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
440 _g_dbus_worker_emit_message_received (GDBusWorker *worker,
441 GDBusMessage *message)
443 if (!worker->stopped)
444 worker->message_received_callback (worker, message, worker->user_data);
448 _g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker *worker,
449 GDBusMessage *message)
453 if (!worker->stopped)
454 ret = worker->message_about_to_be_sent_callback (worker, message, worker->user_data);
458 /* can only be called from private thread with read-lock held - takes ownership of @message */
460 _g_dbus_worker_queue_or_deliver_received_message (GDBusWorker *worker,
461 GDBusMessage *message)
463 if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
466 g_queue_push_tail (worker->received_messages_while_frozen, message);
470 /* not frozen, nor anything in queue */
471 _g_dbus_worker_emit_message_received (worker, message);
472 g_object_unref (message);
476 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
478 unfreeze_in_idle_cb (gpointer user_data)
480 GDBusWorker *worker = user_data;
481 GDBusMessage *message;
483 g_mutex_lock (worker->read_lock);
486 while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
488 _g_dbus_worker_emit_message_received (worker, message);
489 g_object_unref (message);
491 worker->frozen = FALSE;
495 g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
497 g_mutex_unlock (worker->read_lock);
501 /* can be called from any thread */
503 _g_dbus_worker_unfreeze (GDBusWorker *worker)
505 GSource *idle_source;
506 idle_source = g_idle_source_new ();
507 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
508 g_source_set_callback (idle_source,
510 _g_dbus_worker_ref (worker),
511 (GDestroyNotify) _g_dbus_worker_unref);
512 g_source_attach (idle_source, shared_thread_data->context);
513 g_source_unref (idle_source);
516 /* ---------------------------------------------------------------------------------------------------- */
518 static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
520 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
522 _g_dbus_worker_do_read_cb (GInputStream *input_stream,
526 GDBusWorker *worker = user_data;
530 g_mutex_lock (worker->read_lock);
532 /* If already stopped, don't even process the reply */
537 if (worker->socket == NULL)
538 bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
542 bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
545 if (worker->read_num_ancillary_messages > 0)
548 for (n = 0; n < worker->read_num_ancillary_messages; n++)
550 GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
556 else if (G_IS_UNIX_FD_MESSAGE (control_message))
558 GUnixFDMessage *fd_message;
562 fd_message = G_UNIX_FD_MESSAGE (control_message);
563 fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
564 if (worker->read_fd_list == NULL)
566 worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
571 for (n = 0; n < num_fds; n++)
573 /* TODO: really want a append_steal() */
574 g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
580 else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
592 "Unexpected ancillary message of type %s received from peer",
593 g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
594 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
595 g_error_free (error);
596 g_object_unref (control_message);
598 while (n < worker->read_num_ancillary_messages)
599 g_object_unref (worker->read_ancillary_messages[n++]);
600 g_free (worker->read_ancillary_messages);
604 g_object_unref (control_message);
606 g_free (worker->read_ancillary_messages);
609 if (bytes_read == -1)
611 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
612 g_error_free (error);
617 g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
619 g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
620 g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
621 g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
622 G_IO_IN | G_IO_OUT | G_IO_HUP),
627 /* TODO: hmm, hmm... */
633 "Underlying GIOStream returned 0 bytes on an async read");
634 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
635 g_error_free (error);
639 worker->read_buffer_cur_size += bytes_read;
640 if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
642 /* OK, got what we asked for! */
643 if (worker->read_buffer_bytes_wanted == 16)
646 /* OK, got the header - determine how many more bytes are needed */
648 message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
651 if (message_len == -1)
653 g_warning ("_g_dbus_worker_do_read_cb: error determing bytes needed: %s", error->message);
654 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
655 g_error_free (error);
659 worker->read_buffer_bytes_wanted = message_len;
660 _g_dbus_worker_do_read_unlocked (worker);
664 GDBusMessage *message;
667 /* TODO: use connection->priv->auth to decode the message */
669 message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
670 worker->read_buffer_cur_size,
671 worker->capabilities,
676 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
677 g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
679 "The payload is as follows:\n"
681 worker->read_buffer_cur_size,
685 _g_dbus_worker_emit_disconnected (worker, FALSE, error);
686 g_error_free (error);
691 if (worker->read_fd_list != NULL)
693 g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
694 worker->read_fd_list = NULL;
698 if (G_UNLIKELY (_g_dbus_debug_message ()))
701 _g_dbus_debug_print_lock ();
702 g_print ("========================================================================\n"
703 "GDBus-debug:Message:\n"
704 " <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
705 worker->read_buffer_cur_size);
706 s = g_dbus_message_print (message, 2);
709 if (G_UNLIKELY (_g_dbus_debug_payload ()))
711 s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
715 _g_dbus_debug_print_unlock ();
718 /* yay, got a message, go deliver it */
719 _g_dbus_worker_queue_or_deliver_received_message (worker, message);
721 /* start reading another message! */
722 worker->read_buffer_bytes_wanted = 0;
723 worker->read_buffer_cur_size = 0;
724 _g_dbus_worker_do_read_unlocked (worker);
729 /* didn't get all the bytes we requested - so repeat the request... */
730 _g_dbus_worker_do_read_unlocked (worker);
734 g_mutex_unlock (worker->read_lock);
736 /* gives up the reference acquired when calling g_input_stream_read_async() */
737 _g_dbus_worker_unref (worker);
740 /* called in private thread shared by all GDBusConnection instances (with read-lock held) */
742 _g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
744 /* if bytes_wanted is zero, it means start reading a message */
745 if (worker->read_buffer_bytes_wanted == 0)
747 worker->read_buffer_cur_size = 0;
748 worker->read_buffer_bytes_wanted = 16;
751 /* ensure we have a (big enough) buffer */
752 if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
754 /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
755 worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
756 worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
759 if (worker->socket == NULL)
760 g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
761 worker->read_buffer + worker->read_buffer_cur_size,
762 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
765 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
766 _g_dbus_worker_ref (worker));
769 worker->read_ancillary_messages = NULL;
770 worker->read_num_ancillary_messages = 0;
771 _g_socket_read_with_control_messages (worker->socket,
772 worker->read_buffer + worker->read_buffer_cur_size,
773 worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
774 &worker->read_ancillary_messages,
775 &worker->read_num_ancillary_messages,
778 (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
779 _g_dbus_worker_ref (worker));
783 /* called in private thread shared by all GDBusConnection instances (without read-lock held) */
785 _g_dbus_worker_do_read (GDBusWorker *worker)
787 g_mutex_lock (worker->read_lock);
788 _g_dbus_worker_do_read_unlocked (worker);
789 g_mutex_unlock (worker->read_lock);
792 /* ---------------------------------------------------------------------------------------------------- */
794 struct _MessageToWriteData
796 GDBusMessage *message;
802 message_to_write_data_free (MessageToWriteData *data)
804 g_object_unref (data->message);
809 /* ---------------------------------------------------------------------------------------------------- */
811 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
813 write_message (GDBusWorker *worker,
814 MessageToWriteData *data,
819 g_return_val_if_fail (data->blob_size > 16, FALSE);
823 /* First, the initial 16 bytes - special case UNIX sockets here
824 * since it may involve writing an ancillary message with file
829 GOutputVector vector;
830 GSocketControlMessage *message;
831 GUnixFDList *fd_list;
832 gssize bytes_written;
834 fd_list = g_dbus_message_get_unix_fd_list (data->message);
839 if (!G_IS_UNIX_CONNECTION (worker->stream))
843 G_IO_ERROR_INVALID_ARGUMENT,
844 "Tried sending a file descriptor on unsupported stream of type %s",
845 g_type_name (G_TYPE_FROM_INSTANCE (worker->stream)));
848 else if (!(worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
850 g_set_error_literal (error,
852 G_IO_ERROR_INVALID_ARGUMENT,
853 "Tried sending a file descriptor but remote peer does not support this capability");
856 message = g_unix_fd_message_new_with_fd_list (fd_list);
859 vector.buffer = data->blob;
862 bytes_written = g_socket_send_message (worker->socket,
866 message != NULL ? &message : NULL,
867 message != NULL ? 1 : 0,
871 if (bytes_written == -1)
873 g_prefix_error (error, _("Error writing first 16 bytes of message to socket: "));
875 g_object_unref (message);
879 g_object_unref (message);
881 if (bytes_written < 16)
883 /* TODO: I think this needs to be handled ... are we guaranteed that the ancillary
886 g_assert_not_reached ();
890 /* write the first 16 bytes (guaranteed to return an error if everything can't be written) */
891 if (!g_output_stream_write_all (g_io_stream_get_output_stream (worker->stream),
892 (const gchar *) data->blob,
894 NULL, /* bytes_written */
895 worker->cancellable, /* cancellable */
900 /* Then write the rest of the message (guaranteed to return an error if everything can't be written) */
901 if (!g_output_stream_write_all (g_io_stream_get_output_stream (worker->stream),
902 (const gchar *) data->blob + 16,
903 data->blob_size - 16,
904 NULL, /* bytes_written */
905 worker->cancellable, /* cancellable */
911 if (G_UNLIKELY (_g_dbus_debug_message ()))
914 _g_dbus_debug_print_lock ();
915 g_print ("========================================================================\n"
916 "GDBus-debug:Message:\n"
917 " >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
919 s = g_dbus_message_print (data->message, 2);
922 if (G_UNLIKELY (_g_dbus_debug_payload ()))
924 s = _g_dbus_hexdump (data->blob, data->blob_size, 2);
928 _g_dbus_debug_print_unlock ();
935 /* ---------------------------------------------------------------------------------------------------- */
937 /* called in private thread shared by all GDBusConnection instances (without write-lock held) */
939 write_message_in_idle_cb (gpointer user_data)
941 GDBusWorker *worker = user_data;
942 gboolean more_writes_are_pending;
943 MessageToWriteData *data;
944 gboolean message_was_dropped;
947 g_mutex_lock (worker->write_lock);
948 data = g_queue_pop_head (worker->write_queue);
949 g_assert (data != NULL);
950 more_writes_are_pending = (g_queue_get_length (worker->write_queue) > 0);
951 worker->write_is_pending = more_writes_are_pending;
952 g_mutex_unlock (worker->write_lock);
954 /* Note that write_lock is only used for protecting the @write_queue
955 * and @write_is_pending fields of the GDBusWorker struct ... which we
956 * need to modify from arbitrary threads in _g_dbus_worker_send_message().
958 * Therefore, it's fine to drop it here when calling back into user
959 * code and then writing the message out onto the GIOStream since this
960 * function only runs on the worker thread.
962 message_was_dropped = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
963 if (G_LIKELY (!message_was_dropped))
966 if (!write_message (worker,
971 _g_dbus_worker_emit_disconnected (worker, TRUE, error);
972 g_error_free (error);
975 message_to_write_data_free (data);
977 return more_writes_are_pending;
980 /* ---------------------------------------------------------------------------------------------------- */
982 /* can be called from any thread - steals blob */
984 _g_dbus_worker_send_message (GDBusWorker *worker,
985 GDBusMessage *message,
989 MessageToWriteData *data;
991 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
992 g_return_if_fail (blob != NULL);
993 g_return_if_fail (blob_len > 16);
995 data = g_new0 (MessageToWriteData, 1);
996 data->message = g_object_ref (message);
997 data->blob = blob; /* steal! */
998 data->blob_size = blob_len;
1000 g_mutex_lock (worker->write_lock);
1001 g_queue_push_tail (worker->write_queue, data);
1002 if (!worker->write_is_pending)
1004 GSource *idle_source;
1006 worker->write_is_pending = TRUE;
1008 idle_source = g_idle_source_new ();
1009 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1010 g_source_set_callback (idle_source,
1011 write_message_in_idle_cb,
1012 _g_dbus_worker_ref (worker),
1013 (GDestroyNotify) _g_dbus_worker_unref);
1014 g_source_attach (idle_source, shared_thread_data->context);
1015 g_source_unref (idle_source);
1017 g_mutex_unlock (worker->write_lock);
1020 /* ---------------------------------------------------------------------------------------------------- */
1023 _g_dbus_worker_thread_begin_func (gpointer user_data)
1025 GDBusWorker *worker = user_data;
1027 worker->thread = g_thread_self ();
1030 _g_dbus_worker_do_read (worker);
1034 _g_dbus_worker_new (GIOStream *stream,
1035 GDBusCapabilityFlags capabilities,
1036 gboolean initially_frozen,
1037 GDBusWorkerMessageReceivedCallback message_received_callback,
1038 GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1039 GDBusWorkerDisconnectedCallback disconnected_callback,
1042 GDBusWorker *worker;
1044 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1045 g_return_val_if_fail (message_received_callback != NULL, NULL);
1046 g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1047 g_return_val_if_fail (disconnected_callback != NULL, NULL);
1049 worker = g_new0 (GDBusWorker, 1);
1050 worker->ref_count = 1;
1052 worker->read_lock = g_mutex_new ();
1053 worker->message_received_callback = message_received_callback;
1054 worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1055 worker->disconnected_callback = disconnected_callback;
1056 worker->user_data = user_data;
1057 worker->stream = g_object_ref (stream);
1058 worker->capabilities = capabilities;
1059 worker->cancellable = g_cancellable_new ();
1061 worker->frozen = initially_frozen;
1062 worker->received_messages_while_frozen = g_queue_new ();
1064 worker->write_lock = g_mutex_new ();
1065 worker->write_queue = g_queue_new ();
1067 if (G_IS_SOCKET_CONNECTION (worker->stream))
1068 worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1070 _g_dbus_shared_thread_ref (_g_dbus_worker_thread_begin_func, worker);
1075 /* This can be called from any thread - frees worker - guarantees no callbacks
1076 * will ever be issued again
1079 _g_dbus_worker_stop (GDBusWorker *worker)
1081 /* If we're called in the worker thread it means we are called from
1082 * a worker callback. This is fine, we just can't lock in that case since
1083 * we're already holding the lock...
1085 if (g_thread_self () != worker->thread)
1086 g_mutex_lock (worker->read_lock);
1087 worker->stopped = TRUE;
1088 if (g_thread_self () != worker->thread)
1089 g_mutex_unlock (worker->read_lock);
1091 g_cancellable_cancel (worker->cancellable);
1092 _g_dbus_worker_unref (worker);
1095 #define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1096 #define G_DBUS_DEBUG_MESSAGE (1<<1)
1097 #define G_DBUS_DEBUG_PAYLOAD (1<<2)
1098 #define G_DBUS_DEBUG_CALL (1<<3)
1099 #define G_DBUS_DEBUG_SIGNAL (1<<4)
1100 #define G_DBUS_DEBUG_INCOMING (1<<5)
1101 #define G_DBUS_DEBUG_EMISSION (1<<6)
1102 #define G_DBUS_DEBUG_ADDRESS (1<<7)
1103 #define G_DBUS_DEBUG_ALL 0xffffffff
1104 static gint _gdbus_debug_flags = 0;
1107 _g_dbus_debug_authentication (void)
1109 _g_dbus_initialize ();
1110 return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1114 _g_dbus_debug_message (void)
1116 _g_dbus_initialize ();
1117 return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1121 _g_dbus_debug_payload (void)
1123 _g_dbus_initialize ();
1124 return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1128 _g_dbus_debug_call (void)
1130 _g_dbus_initialize ();
1131 return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1135 _g_dbus_debug_signal (void)
1137 _g_dbus_initialize ();
1138 return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1142 _g_dbus_debug_incoming (void)
1144 _g_dbus_initialize ();
1145 return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1149 _g_dbus_debug_emission (void)
1151 _g_dbus_initialize ();
1152 return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1156 _g_dbus_debug_address (void)
1158 _g_dbus_initialize ();
1159 return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1162 G_LOCK_DEFINE_STATIC (print_lock);
1165 _g_dbus_debug_print_lock (void)
1167 G_LOCK (print_lock);
1171 _g_dbus_debug_print_unlock (void)
1173 G_UNLOCK (print_lock);
1177 * _g_dbus_initialize:
1179 * Does various one-time init things such as
1181 * - registering the G_DBUS_ERROR error domain
1182 * - parses the G_DBUS_DEBUG environment variable
1185 _g_dbus_initialize (void)
1187 static volatile gsize initialized = 0;
1189 if (g_once_init_enter (&initialized))
1191 volatile GQuark g_dbus_error_domain;
1194 g_dbus_error_domain = G_DBUS_ERROR;
1196 debug = g_getenv ("G_DBUS_DEBUG");
1201 tokens = g_strsplit (debug, ",", 0);
1202 for (n = 0; tokens[n] != NULL; n++)
1204 if (g_strcmp0 (tokens[n], "authentication") == 0)
1205 _gdbus_debug_flags |= G_DBUS_DEBUG_AUTHENTICATION;
1206 else if (g_strcmp0 (tokens[n], "message") == 0)
1207 _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1208 else if (g_strcmp0 (tokens[n], "payload") == 0) /* implies `message' */
1209 _gdbus_debug_flags |= (G_DBUS_DEBUG_MESSAGE | G_DBUS_DEBUG_PAYLOAD);
1210 else if (g_strcmp0 (tokens[n], "call") == 0)
1211 _gdbus_debug_flags |= G_DBUS_DEBUG_CALL;
1212 else if (g_strcmp0 (tokens[n], "signal") == 0)
1213 _gdbus_debug_flags |= G_DBUS_DEBUG_SIGNAL;
1214 else if (g_strcmp0 (tokens[n], "incoming") == 0)
1215 _gdbus_debug_flags |= G_DBUS_DEBUG_INCOMING;
1216 else if (g_strcmp0 (tokens[n], "emission") == 0)
1217 _gdbus_debug_flags |= G_DBUS_DEBUG_EMISSION;
1218 else if (g_strcmp0 (tokens[n], "address") == 0)
1219 _gdbus_debug_flags |= G_DBUS_DEBUG_ADDRESS;
1220 else if (g_strcmp0 (tokens[n], "all") == 0)
1221 _gdbus_debug_flags |= G_DBUS_DEBUG_ALL;
1223 g_strfreev (tokens);
1226 g_once_init_leave (&initialized, 1);
1230 /* ---------------------------------------------------------------------------------------------------- */
1233 _g_dbus_compute_complete_signature (GDBusArgInfo **args)
1235 const GVariantType *arg_types[256];
1239 for (n = 0; args[n] != NULL; n++)
1241 /* DBus places a hard limit of 255 on signature length.
1242 * therefore number of args must be less than 256.
1246 arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
1248 if G_UNLIKELY (arg_types[n] == NULL)
1254 return g_variant_type_new_tuple (arg_types, n);
1257 /* ---------------------------------------------------------------------------------------------------- */
1261 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
1264 _g_dbus_win32_get_user_sid (void)
1268 DWORD token_information_len;
1275 h = INVALID_HANDLE_VALUE;
1277 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &h))
1279 g_warning ("OpenProcessToken failed with error code %d", (gint) GetLastError ());
1283 /* Get length of buffer */
1284 token_information_len = 0;
1285 if (!GetTokenInformation (h, TokenUser, NULL, 0, &token_information_len))
1287 if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1289 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1293 user = g_malloc (token_information_len);
1294 if (!GetTokenInformation (h, TokenUser, user, token_information_len, &token_information_len))
1296 g_warning ("GetTokenInformation() failed with error code %d", (gint) GetLastError ());
1300 psid = user->User.Sid;
1301 if (!IsValidSid (psid))
1303 g_warning ("Invalid SID");
1307 if (!ConvertSidToStringSidA (psid, &sid))
1309 g_warning ("Invalid SID");
1313 ret = g_strdup (sid);
1318 if (h != INVALID_HANDLE_VALUE)
1324 /* ---------------------------------------------------------------------------------------------------- */
1327 _g_dbus_get_machine_id (GError **error)
1330 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
1332 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
1337 g_prefix_error (error, _("Unable to load /var/lib/dbus/machine-id: "));
1341 /* TODO: validate value */
1347 /* ---------------------------------------------------------------------------------------------------- */
1350 _g_dbus_enum_to_string (GType enum_type, gint value)
1354 GEnumValue *enum_value;
1356 klass = g_type_class_ref (enum_type);
1357 enum_value = g_enum_get_value (klass, value);
1358 if (enum_value != NULL)
1359 ret = g_strdup (enum_value->value_nick);
1361 ret = g_strdup_printf ("unknown (value %d)", value);
1362 g_type_class_unref (klass);
1366 /* ---------------------------------------------------------------------------------------------------- */
1368 #define __G_DBUS_PRIVATE_C__
1369 #include "gioaliasdef.c"