1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-transport-socket.c Socket subclasses of DBusTransport
4 * Copyright (C) 2002, 2003, 2004, 2006 Red Hat Inc.
6 * Licensed under the Academic Free License version 2.1
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "dbus-internals.h"
26 #include "dbus-connection-internal.h"
27 #include "dbus-nonce.h"
28 #include "dbus-transport-socket.h"
29 #include "dbus-transport-protected.h"
30 #include "dbus-watch.h"
31 #include "dbus-credentials.h"
34 * @defgroup DBusTransportSocket DBusTransport implementations for sockets
35 * @ingroup DBusInternals
36 * @brief Implementation details of DBusTransport on sockets
42 * Opaque object representing a socket file descriptor transport.
44 typedef struct DBusTransportSocket DBusTransportSocket;
47 * Implementation details of DBusTransportSocket. All members are private.
49 struct DBusTransportSocket
51 DBusTransport base; /**< Parent instance */
52 DBusSocket fd; /**< File descriptor. */
53 DBusWatch *read_watch; /**< Watch for readability. */
54 DBusWatch *write_watch; /**< Watch for writability. */
56 int max_bytes_read_per_iteration; /**< To avoid blocking too long. */
57 int max_bytes_written_per_iteration; /**< To avoid blocking too long. */
59 int message_bytes_written; /**< Number of bytes of current
60 * outgoing message that have
63 DBusString encoded_outgoing; /**< Encoded version of current
66 DBusString encoded_incoming; /**< Encoded version of current
72 free_watches (DBusTransport *transport)
74 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
76 _dbus_verbose ("start\n");
78 if (socket_transport->read_watch)
80 if (transport->connection)
81 _dbus_connection_remove_watch_unlocked (transport->connection,
82 socket_transport->read_watch);
83 _dbus_watch_invalidate (socket_transport->read_watch);
84 _dbus_watch_unref (socket_transport->read_watch);
85 socket_transport->read_watch = NULL;
88 if (socket_transport->write_watch)
90 if (transport->connection)
91 _dbus_connection_remove_watch_unlocked (transport->connection,
92 socket_transport->write_watch);
93 _dbus_watch_invalidate (socket_transport->write_watch);
94 _dbus_watch_unref (socket_transport->write_watch);
95 socket_transport->write_watch = NULL;
98 _dbus_verbose ("end\n");
102 socket_finalize (DBusTransport *transport)
104 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
106 _dbus_verbose ("\n");
108 free_watches (transport);
110 _dbus_string_free (&socket_transport->encoded_outgoing);
111 _dbus_string_free (&socket_transport->encoded_incoming);
113 _dbus_transport_finalize_base (transport);
115 _dbus_assert (socket_transport->read_watch == NULL);
116 _dbus_assert (socket_transport->write_watch == NULL);
118 dbus_free (transport);
122 check_write_watch (DBusTransport *transport)
124 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
127 if (transport->connection == NULL)
130 if (transport->disconnected)
132 _dbus_assert (socket_transport->write_watch == NULL);
136 _dbus_transport_ref (transport);
138 if (_dbus_transport_try_to_authenticate (transport))
139 needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
142 if (transport->send_credentials_pending)
146 DBusAuthState auth_state;
148 auth_state = _dbus_auth_do_work (transport->auth);
150 /* If we need memory we install the write watch just in case,
151 * if there's no need for it, it will get de-installed
152 * next time we try reading.
154 if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
155 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
162 _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %" DBUS_SOCKET_FORMAT " outgoing messages exist %d\n",
163 needed, transport->connection, socket_transport->write_watch,
164 _dbus_socket_printable (socket_transport->fd),
165 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
167 _dbus_connection_toggle_watch_unlocked (transport->connection,
168 socket_transport->write_watch,
171 _dbus_transport_unref (transport);
175 check_read_watch (DBusTransport *transport)
177 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
178 dbus_bool_t need_read_watch;
180 _dbus_verbose ("fd = %" DBUS_SOCKET_FORMAT "\n",
181 _dbus_socket_printable (socket_transport->fd));
183 if (transport->connection == NULL)
186 if (transport->disconnected)
188 _dbus_assert (socket_transport->read_watch == NULL);
192 _dbus_transport_ref (transport);
194 if (_dbus_transport_try_to_authenticate (transport))
196 (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
197 (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
200 if (transport->receive_credentials_pending)
201 need_read_watch = TRUE;
204 /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
205 * is to avoid spinning on the file descriptor when we're waiting
206 * to write or for some other part of the auth process
208 DBusAuthState auth_state;
210 auth_state = _dbus_auth_do_work (transport->auth);
212 /* If we need memory we install the read watch just in case,
213 * if there's no need for it, it will get de-installed
214 * next time we try reading. If we're authenticated we
215 * install it since we normally have it installed while
218 if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
219 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
220 auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
221 need_read_watch = TRUE;
223 need_read_watch = FALSE;
227 _dbus_verbose (" setting read watch enabled = %d\n", need_read_watch);
228 _dbus_connection_toggle_watch_unlocked (transport->connection,
229 socket_transport->read_watch,
232 _dbus_transport_unref (transport);
236 do_io_error (DBusTransport *transport)
238 _dbus_transport_ref (transport);
239 _dbus_transport_disconnect (transport);
240 _dbus_transport_unref (transport);
243 /* return value is whether we successfully read any new data. */
245 read_data_into_auth (DBusTransport *transport,
248 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
255 _dbus_auth_get_buffer (transport->auth, &buffer);
257 bytes_read = _dbus_read_socket (socket_transport->fd,
258 buffer, socket_transport->max_bytes_read_per_iteration);
259 saved_errno = _dbus_save_socket_errno ();
261 _dbus_auth_return_buffer (transport->auth, buffer);
265 _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
269 else if (bytes_read < 0)
271 /* EINTR already handled for us */
273 if (_dbus_get_is_errno_enomem (saved_errno))
277 else if (_dbus_get_is_errno_eagain_or_ewouldblock (saved_errno))
278 ; /* do nothing, just return FALSE below */
281 _dbus_verbose ("Error reading from remote app: %s\n",
282 _dbus_strerror (saved_errno));
283 do_io_error (transport);
290 _dbus_assert (bytes_read == 0);
292 _dbus_verbose ("Disconnected from remote app\n");
293 do_io_error (transport);
299 /* Return value is whether we successfully wrote any bytes */
301 write_data_from_auth (DBusTransport *transport)
303 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
306 const DBusString *buffer;
308 if (!_dbus_auth_get_bytes_to_send (transport->auth,
312 bytes_written = _dbus_write_socket (socket_transport->fd,
314 0, _dbus_string_get_length (buffer));
315 saved_errno = _dbus_save_socket_errno ();
317 if (bytes_written > 0)
319 _dbus_auth_bytes_sent (transport->auth, bytes_written);
322 else if (bytes_written < 0)
324 /* EINTR already handled for us */
326 if (_dbus_get_is_errno_eagain_or_ewouldblock (saved_errno))
330 _dbus_verbose ("Error writing to remote app: %s\n",
331 _dbus_strerror (saved_errno));
332 do_io_error (transport);
341 exchange_credentials (DBusTransport *transport,
342 dbus_bool_t do_reading,
343 dbus_bool_t do_writing)
345 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
346 DBusError error = DBUS_ERROR_INIT;
348 _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
349 do_reading, do_writing);
351 if (do_writing && transport->send_credentials_pending)
353 if (_dbus_send_credentials_socket (socket_transport->fd,
356 transport->send_credentials_pending = FALSE;
360 _dbus_verbose ("Failed to write credentials: %s\n", error.message);
361 dbus_error_free (&error);
362 do_io_error (transport);
366 if (do_reading && transport->receive_credentials_pending)
368 /* FIXME this can fail due to IO error _or_ OOM, broken
369 * (somewhat tricky to fix since the OOM error can be set after
370 * we already read the credentials byte, so basically we need to
371 * separate reading the byte and storing it in the
372 * transport->credentials). Does not really matter for now
373 * because storing in credentials never actually fails on unix.
375 if (_dbus_read_credentials_socket (socket_transport->fd,
376 transport->credentials,
379 transport->receive_credentials_pending = FALSE;
383 _dbus_verbose ("Failed to read credentials %s\n", error.message);
384 dbus_error_free (&error);
385 do_io_error (transport);
389 if (!(transport->send_credentials_pending ||
390 transport->receive_credentials_pending))
392 if (!_dbus_auth_set_credentials (transport->auth,
393 transport->credentials))
401 do_authentication (DBusTransport *transport,
402 dbus_bool_t do_reading,
403 dbus_bool_t do_writing,
404 dbus_bool_t *auth_completed)
407 dbus_bool_t orig_auth_state;
411 orig_auth_state = _dbus_transport_try_to_authenticate (transport);
413 /* This is essential to avoid the check_write_watch() at the end,
414 * we don't want to add a write watch in do_iteration before
415 * we try writing and get EAGAIN
420 *auth_completed = FALSE;
424 _dbus_transport_ref (transport);
426 while (!_dbus_transport_try_to_authenticate (transport) &&
427 _dbus_transport_get_is_connected (transport))
429 if (!exchange_credentials (transport, do_reading, do_writing))
436 if (transport->send_credentials_pending ||
437 transport->receive_credentials_pending)
439 _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
440 transport->send_credentials_pending,
441 transport->receive_credentials_pending);
445 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
446 switch (_dbus_auth_do_work (transport->auth))
448 case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
449 _dbus_verbose (" %s auth state: waiting for input\n",
450 TRANSPORT_SIDE (transport));
451 if (!do_reading || !read_data_into_auth (transport, &oom))
455 case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
456 _dbus_verbose (" %s auth state: waiting for memory\n",
457 TRANSPORT_SIDE (transport));
462 case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
463 _dbus_verbose (" %s auth state: bytes to send\n",
464 TRANSPORT_SIDE (transport));
465 if (!do_writing || !write_data_from_auth (transport))
469 case DBUS_AUTH_STATE_NEED_DISCONNECT:
470 _dbus_verbose (" %s auth state: need to disconnect\n",
471 TRANSPORT_SIDE (transport));
472 do_io_error (transport);
475 case DBUS_AUTH_STATE_AUTHENTICATED:
476 _dbus_verbose (" %s auth state: authenticated\n",
477 TRANSPORT_SIDE (transport));
480 case DBUS_AUTH_STATE_INVALID:
483 _dbus_assert_not_reached ("invalid auth state");
489 *auth_completed = (orig_auth_state != _dbus_transport_try_to_authenticate (transport));
491 check_read_watch (transport);
492 check_write_watch (transport);
493 _dbus_transport_unref (transport);
501 /* returns false on oom */
503 do_writing (DBusTransport *transport)
506 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
509 /* No messages without authentication! */
510 if (!_dbus_transport_try_to_authenticate (transport))
512 _dbus_verbose ("Not authenticated, not writing anything\n");
516 if (transport->disconnected)
518 _dbus_verbose ("Not connected, not writing anything\n");
523 _dbus_verbose ("do_writing(), have_messages = %d, fd = %" DBUS_SOCKET_FORMAT "\n",
524 _dbus_connection_has_messages_to_send_unlocked (transport->connection),
525 _dbus_socket_printable (socket_transport->fd));
531 while (!transport->disconnected &&
532 _dbus_connection_has_messages_to_send_unlocked (transport->connection))
535 DBusMessage *message;
536 const DBusString *header;
537 const DBusString *body;
538 int header_len, body_len;
539 int total_bytes_to_write;
542 if (total > socket_transport->max_bytes_written_per_iteration)
544 _dbus_verbose ("%d bytes exceeds %d bytes written per iteration, returning\n",
545 total, socket_transport->max_bytes_written_per_iteration);
549 message = _dbus_connection_get_message_to_send (transport->connection);
550 _dbus_assert (message != NULL);
551 dbus_message_lock (message);
554 _dbus_verbose ("writing message %p\n", message);
557 _dbus_message_get_network_data (message,
560 header_len = _dbus_string_get_length (header);
561 body_len = _dbus_string_get_length (body);
563 if (_dbus_auth_needs_encoding (transport->auth))
565 /* Does fd passing even make sense with encoded data? */
566 _dbus_assert(!DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport));
568 if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
570 if (!_dbus_auth_encode_data (transport->auth,
571 header, &socket_transport->encoded_outgoing))
577 if (!_dbus_auth_encode_data (transport->auth,
578 body, &socket_transport->encoded_outgoing))
580 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
586 total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
589 _dbus_verbose ("encoded message is %d bytes\n",
590 total_bytes_to_write);
594 _dbus_write_socket (socket_transport->fd,
595 &socket_transport->encoded_outgoing,
596 socket_transport->message_bytes_written,
597 total_bytes_to_write - socket_transport->message_bytes_written);
598 saved_errno = _dbus_save_socket_errno ();
602 total_bytes_to_write = header_len + body_len;
605 _dbus_verbose ("message is %d bytes\n",
606 total_bytes_to_write);
609 #ifdef HAVE_UNIX_FD_PASSING
610 if (socket_transport->message_bytes_written <= 0 && DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport))
612 /* Send the fds along with the first byte of the message */
616 _dbus_message_get_unix_fds(message, &unix_fds, &n);
619 _dbus_write_socket_with_unix_fds_two (socket_transport->fd,
621 socket_transport->message_bytes_written,
622 header_len - socket_transport->message_bytes_written,
627 saved_errno = _dbus_save_socket_errno ();
629 if (bytes_written > 0 && n > 0)
630 _dbus_verbose("Wrote %i unix fds\n", n);
635 if (socket_transport->message_bytes_written < header_len)
638 _dbus_write_socket_two (socket_transport->fd,
640 socket_transport->message_bytes_written,
641 header_len - socket_transport->message_bytes_written,
648 _dbus_write_socket (socket_transport->fd,
650 (socket_transport->message_bytes_written - header_len),
652 (socket_transport->message_bytes_written - header_len));
655 saved_errno = _dbus_save_socket_errno ();
659 if (bytes_written < 0)
661 /* EINTR already handled for us */
663 /* If the other end closed the socket with close() or shutdown(), we
664 * receive EPIPE here but we must not close the socket yet: there
665 * might still be some data to read. See:
666 * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
669 if (_dbus_get_is_errno_eagain_or_ewouldblock (saved_errno) || _dbus_get_is_errno_epipe (saved_errno))
672 /* Since Linux commit 25888e (from 2.6.37-rc4, Nov 2010), sendmsg()
673 * on Unix sockets returns -1 errno=ETOOMANYREFS when the passfd
674 * mechanism (SCM_RIGHTS) is used recursively with a recursion level
675 * of maximum 4. The kernel does not have an API to check whether
676 * the passed fds can be forwarded and it can change asynchronously.
678 * https://bugs.freedesktop.org/show_bug.cgi?id=80163
681 else if (_dbus_get_is_errno_etoomanyrefs (saved_errno))
683 /* We only send fds in the first byte of the message.
684 * ETOOMANYREFS cannot happen after.
686 _dbus_assert (socket_transport->message_bytes_written == 0);
688 _dbus_verbose (" discard message of %d bytes due to ETOOMANYREFS\n",
689 total_bytes_to_write);
691 socket_transport->message_bytes_written = 0;
692 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
693 _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
695 /* The message was not actually sent but it needs to be removed
696 * from the outgoing queue
698 _dbus_connection_message_sent_unlocked (transport->connection,
703 _dbus_verbose ("Error writing to remote app: %s\n",
704 _dbus_strerror (saved_errno));
705 do_io_error (transport);
711 _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
712 total_bytes_to_write);
714 total += bytes_written;
715 socket_transport->message_bytes_written += bytes_written;
717 _dbus_assert (socket_transport->message_bytes_written <=
718 total_bytes_to_write);
720 if (socket_transport->message_bytes_written == total_bytes_to_write)
722 socket_transport->message_bytes_written = 0;
723 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
724 _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
726 _dbus_connection_message_sent_unlocked (transport->connection,
739 /* returns false on out-of-memory */
741 do_reading (DBusTransport *transport)
743 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
750 _dbus_verbose ("fd = %" DBUS_SOCKET_FORMAT "\n",
751 _dbus_socket_printable (socket_transport->fd));
753 /* No messages without authentication! */
754 if (!_dbus_transport_try_to_authenticate (transport))
763 /* See if we've exceeded max messages and need to disable reading */
764 check_read_watch (transport);
766 if (total > socket_transport->max_bytes_read_per_iteration)
768 _dbus_verbose ("%d bytes exceeds %d bytes read per iteration, returning\n",
769 total, socket_transport->max_bytes_read_per_iteration);
773 _dbus_assert (socket_transport->read_watch != NULL ||
774 transport->disconnected);
776 if (transport->disconnected)
779 if (!dbus_watch_get_enabled (socket_transport->read_watch))
782 if (_dbus_auth_needs_decoding (transport->auth))
784 /* Does fd passing even make sense with encoded data? */
785 _dbus_assert(!DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport));
787 if (_dbus_string_get_length (&socket_transport->encoded_incoming) > 0)
788 bytes_read = _dbus_string_get_length (&socket_transport->encoded_incoming);
790 bytes_read = _dbus_read_socket (socket_transport->fd,
791 &socket_transport->encoded_incoming,
792 socket_transport->max_bytes_read_per_iteration);
794 saved_errno = _dbus_save_socket_errno ();
796 _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) ==
801 _dbus_message_loader_get_buffer (transport->loader,
806 if (!_dbus_auth_decode_data (transport->auth,
807 &socket_transport->encoded_incoming,
810 _dbus_verbose ("Out of memory decoding incoming data\n");
811 _dbus_message_loader_return_buffer (transport->loader,
818 _dbus_message_loader_return_buffer (transport->loader,
821 _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
822 _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
827 int max_to_read = DBUS_MAXIMUM_MESSAGE_LENGTH;
828 dbus_bool_t may_read_unix_fds = TRUE;
830 _dbus_message_loader_get_buffer (transport->loader,
835 if (max_to_read > socket_transport->max_bytes_read_per_iteration)
836 max_to_read = socket_transport->max_bytes_read_per_iteration;
838 #ifdef HAVE_UNIX_FD_PASSING
839 if (DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport) && may_read_unix_fds)
844 if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
846 _dbus_verbose ("Out of memory reading file descriptors\n");
847 _dbus_message_loader_return_buffer (transport->loader, buffer);
852 bytes_read = _dbus_read_socket_with_unix_fds(socket_transport->fd,
856 saved_errno = _dbus_save_socket_errno ();
858 if (bytes_read >= 0 && n_fds > 0)
859 _dbus_verbose("Read %i unix fds\n", n_fds);
861 _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
866 bytes_read = _dbus_read_socket (socket_transport->fd,
867 buffer, max_to_read);
868 saved_errno = _dbus_save_socket_errno ();
871 _dbus_message_loader_return_buffer (transport->loader,
877 /* EINTR already handled for us */
879 if (_dbus_get_is_errno_enomem (saved_errno))
881 _dbus_verbose ("Out of memory in read()/do_reading()\n");
885 else if (_dbus_get_is_errno_eagain_or_ewouldblock (saved_errno))
889 _dbus_verbose ("Error reading from remote app: %s\n",
890 _dbus_strerror (saved_errno));
891 do_io_error (transport);
895 else if (bytes_read == 0)
897 _dbus_verbose ("Disconnected from remote app\n");
898 do_io_error (transport);
903 _dbus_verbose (" read %d bytes\n", bytes_read);
907 if (!_dbus_transport_queue_messages (transport))
910 _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
914 /* Try reading more data until we get EAGAIN and return, or
915 * exceed max bytes per iteration. If in blocking mode of
916 * course we'll block instead of returning.
929 unix_error_with_read_to_come (DBusTransport *itransport,
933 DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
935 if (!(flags & DBUS_WATCH_HANGUP || flags & DBUS_WATCH_ERROR))
938 /* If we have a read watch enabled ...
939 we -might have data incoming ... => handle the HANGUP there */
940 if (watch != transport->read_watch &&
941 _dbus_watch_get_enabled (transport->read_watch))
948 socket_handle_watch (DBusTransport *transport,
952 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
954 _dbus_assert (watch == socket_transport->read_watch ||
955 watch == socket_transport->write_watch);
956 _dbus_assert (watch != NULL);
958 /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
959 * still be in the buffer and do_reading may need several iteration to read
960 * it all (because of its max_bytes_read_per_iteration limit).
962 if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
964 _dbus_verbose ("Hang up or error on watch\n");
965 _dbus_transport_disconnect (transport);
969 if (watch == socket_transport->read_watch &&
970 (flags & DBUS_WATCH_READABLE))
972 dbus_bool_t auth_finished;
974 _dbus_verbose ("handling read watch %p flags = %x\n",
977 if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
980 /* We don't want to do a read immediately following
981 * a successful authentication. This is so we
982 * have a chance to propagate the authentication
983 * state further up. Specifically, we need to
984 * process any pending data from the auth object.
988 if (!do_reading (transport))
990 _dbus_verbose ("no memory to read\n");
996 _dbus_verbose ("Not reading anything since we just completed the authentication\n");
999 else if (watch == socket_transport->write_watch &&
1000 (flags & DBUS_WATCH_WRITABLE))
1003 _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
1004 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1006 if (!do_authentication (transport, FALSE, TRUE, NULL))
1009 if (!do_writing (transport))
1011 _dbus_verbose ("no memory to write\n");
1015 /* See if we still need the write watch */
1016 check_write_watch (transport);
1018 #ifdef DBUS_ENABLE_VERBOSE_MODE
1021 if (watch == socket_transport->read_watch)
1022 _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
1024 else if (watch == socket_transport->write_watch)
1025 _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
1028 _dbus_verbose ("asked to handle watch %p on fd %" DBUS_SOCKET_FORMAT " that we don't recognize\n",
1029 watch, _dbus_socket_printable (_dbus_watch_get_socket (watch)));
1031 #endif /* DBUS_ENABLE_VERBOSE_MODE */
1037 socket_disconnect (DBusTransport *transport)
1039 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1041 _dbus_verbose ("\n");
1043 free_watches (transport);
1045 _dbus_close_socket (socket_transport->fd, NULL);
1046 _dbus_socket_invalidate (&socket_transport->fd);
1050 socket_connection_set (DBusTransport *transport)
1052 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1054 _dbus_watch_set_handler (socket_transport->write_watch,
1055 _dbus_connection_handle_watch,
1056 transport->connection, NULL);
1058 _dbus_watch_set_handler (socket_transport->read_watch,
1059 _dbus_connection_handle_watch,
1060 transport->connection, NULL);
1062 if (!_dbus_connection_add_watch_unlocked (transport->connection,
1063 socket_transport->write_watch))
1066 if (!_dbus_connection_add_watch_unlocked (transport->connection,
1067 socket_transport->read_watch))
1069 _dbus_connection_remove_watch_unlocked (transport->connection,
1070 socket_transport->write_watch);
1074 check_read_watch (transport);
1075 check_write_watch (transport);
1081 * @todo We need to have a way to wake up the select sleep if
1082 * a new iteration request comes in with a flag (read/write) that
1083 * we're not currently serving. Otherwise a call that just reads
1084 * could block a write call forever (if there are no incoming
1088 socket_do_iteration (DBusTransport *transport,
1090 int timeout_milliseconds)
1092 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1097 _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %" DBUS_SOCKET_FORMAT "\n",
1098 flags & DBUS_ITERATION_DO_READING ? "read" : "",
1099 flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
1100 timeout_milliseconds,
1101 socket_transport->read_watch,
1102 socket_transport->write_watch,
1103 _dbus_socket_printable (socket_transport->fd));
1105 /* the passed in DO_READING/DO_WRITING flags indicate whether to
1106 * read/write messages, but regardless of those we may need to block
1107 * for reading/writing to do auth. But if we do reading for auth,
1108 * we don't want to read any messages yet if not given DO_READING.
1111 poll_fd.fd = _dbus_socket_get_pollable (socket_transport->fd);
1114 if (_dbus_transport_try_to_authenticate (transport))
1116 /* This is kind of a hack; if we have stuff to write, then try
1117 * to avoid the poll. This is probably about a 5% speedup on an
1118 * echo client/server.
1120 * If both reading and writing were requested, we want to avoid this
1121 * since it could have funky effects:
1122 * - both ends spinning waiting for the other one to read
1123 * data so they can finish writing
1124 * - prioritizing all writing ahead of reading
1126 if ((flags & DBUS_ITERATION_DO_WRITING) &&
1127 !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
1128 !transport->disconnected &&
1129 _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1131 do_writing (transport);
1133 if (transport->disconnected ||
1134 !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
1138 /* If we get here, we decided to do the poll() after all */
1139 _dbus_assert (socket_transport->read_watch);
1140 if (flags & DBUS_ITERATION_DO_READING)
1141 poll_fd.events |= _DBUS_POLLIN;
1143 _dbus_assert (socket_transport->write_watch);
1144 if (flags & DBUS_ITERATION_DO_WRITING)
1145 poll_fd.events |= _DBUS_POLLOUT;
1149 DBusAuthState auth_state;
1151 auth_state = _dbus_auth_do_work (transport->auth);
1153 if (transport->receive_credentials_pending ||
1154 auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
1155 poll_fd.events |= _DBUS_POLLIN;
1157 if (transport->send_credentials_pending ||
1158 auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
1159 poll_fd.events |= _DBUS_POLLOUT;
1166 if (flags & DBUS_ITERATION_BLOCK)
1167 poll_timeout = timeout_milliseconds;
1171 /* For blocking selects we drop the connection lock here
1172 * to avoid blocking out connection access during a potentially
1173 * indefinite blocking call. The io path is still protected
1174 * by the io_path_cond condvar, so we won't reenter this.
1176 if (flags & DBUS_ITERATION_BLOCK)
1178 _dbus_verbose ("unlock pre poll\n");
1179 _dbus_connection_unlock (transport->connection);
1183 poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
1184 saved_errno = _dbus_save_socket_errno ();
1186 if (poll_res < 0 && _dbus_get_is_errno_eintr (saved_errno))
1189 if (flags & DBUS_ITERATION_BLOCK)
1191 _dbus_verbose ("lock post poll\n");
1192 _dbus_connection_lock (transport->connection);
1198 poll_fd.revents = 0; /* some concern that posix does not guarantee this;
1199 * valgrind flags it as an error. though it probably
1200 * is guaranteed on linux at least.
1203 if (poll_fd.revents & _DBUS_POLLERR)
1204 do_io_error (transport);
1207 dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
1208 dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
1209 dbus_bool_t authentication_completed;
1211 _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
1212 need_read, need_write);
1213 do_authentication (transport, need_read, need_write,
1214 &authentication_completed);
1216 /* See comment in socket_handle_watch. */
1217 if (authentication_completed)
1220 if (need_read && (flags & DBUS_ITERATION_DO_READING))
1221 do_reading (transport);
1222 if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
1223 do_writing (transport);
1228 _dbus_verbose ("Error from _dbus_poll(): %s\n",
1229 _dbus_strerror (saved_errno));
1235 /* We need to install the write watch only if we did not
1236 * successfully write everything. Note we need to be careful that we
1237 * don't call check_write_watch *before* do_writing, since it's
1238 * inefficient to add the write watch, and we can avoid it most of
1239 * the time since we can write immediately.
1241 * However, we MUST always call check_write_watch(); DBusConnection code
1242 * relies on the fact that running an iteration will notice that
1243 * messages are pending.
1245 check_write_watch (transport);
1247 _dbus_verbose (" ... leaving do_iteration()\n");
1251 socket_live_messages_changed (DBusTransport *transport)
1253 /* See if we should look for incoming messages again */
1254 check_read_watch (transport);
1259 socket_get_socket_fd (DBusTransport *transport,
1262 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1264 *fd_p = socket_transport->fd;
1269 static const DBusTransportVTable socket_vtable = {
1271 socket_handle_watch,
1273 socket_connection_set,
1274 socket_do_iteration,
1275 socket_live_messages_changed,
1276 socket_get_socket_fd
1280 * Creates a new transport for the given socket file descriptor. The file
1281 * descriptor must be nonblocking (use _dbus_set_fd_nonblocking() to
1282 * make it so). This function is shared by various transports that
1283 * boil down to a full duplex file descriptor.
1285 * @param fd the file descriptor.
1286 * @param server_guid non-#NULL if this transport is on the server side of a connection
1287 * @param address the transport's address
1288 * @returns the new transport, or #NULL if no memory.
1291 _dbus_transport_new_for_socket (DBusSocket fd,
1292 const DBusString *server_guid,
1293 const DBusString *address)
1295 DBusTransportSocket *socket_transport;
1297 socket_transport = dbus_new0 (DBusTransportSocket, 1);
1298 if (socket_transport == NULL)
1301 if (!_dbus_string_init (&socket_transport->encoded_outgoing))
1304 if (!_dbus_string_init (&socket_transport->encoded_incoming))
1307 socket_transport->write_watch = _dbus_watch_new (_dbus_socket_get_pollable (fd),
1308 DBUS_WATCH_WRITABLE,
1311 if (socket_transport->write_watch == NULL)
1314 socket_transport->read_watch = _dbus_watch_new (_dbus_socket_get_pollable (fd),
1315 DBUS_WATCH_READABLE,
1318 if (socket_transport->read_watch == NULL)
1321 if (!_dbus_transport_init_base (&socket_transport->base,
1323 server_guid, address))
1326 #ifdef HAVE_UNIX_FD_PASSING
1327 _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
1330 socket_transport->fd = fd;
1331 socket_transport->message_bytes_written = 0;
1333 /* These values should probably be tunable or something. */
1334 socket_transport->max_bytes_read_per_iteration = 2048;
1335 socket_transport->max_bytes_written_per_iteration = 2048;
1337 return (DBusTransport*) socket_transport;
1340 _dbus_watch_invalidate (socket_transport->read_watch);
1341 _dbus_watch_unref (socket_transport->read_watch);
1343 _dbus_watch_invalidate (socket_transport->write_watch);
1344 _dbus_watch_unref (socket_transport->write_watch);
1346 _dbus_string_free (&socket_transport->encoded_incoming);
1348 _dbus_string_free (&socket_transport->encoded_outgoing);
1350 dbus_free (socket_transport);
1355 * Creates a new transport for the given hostname and port.
1356 * If host is NULL, it will default to localhost
1358 * @param host the host to connect to
1359 * @param port the port to connect to
1360 * @param family the address family to connect to
1361 * @param noncefile path to nonce file
1362 * @param error location to store reason for failure.
1363 * @returns a new transport, or #NULL on failure.
1366 _dbus_transport_new_for_tcp_socket (const char *host,
1369 const char *noncefile,
1373 DBusTransport *transport;
1376 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1378 if (!_dbus_string_init (&address))
1380 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1387 if (!_dbus_string_append (&address, noncefile ? "nonce-tcp:" : "tcp:"))
1390 if (!_dbus_string_append (&address, "host=") ||
1391 !_dbus_string_append (&address, host))
1394 if (!_dbus_string_append (&address, ",port=") ||
1395 !_dbus_string_append (&address, port))
1398 if (family != NULL &&
1399 (!_dbus_string_append (&address, ",family=") ||
1400 !_dbus_string_append (&address, family)))
1403 if (noncefile != NULL &&
1404 (!_dbus_string_append (&address, ",noncefile=") ||
1405 !_dbus_string_append (&address, noncefile)))
1408 fd = _dbus_connect_tcp_socket_with_nonce (host, port, family, noncefile, error);
1409 if (!_dbus_socket_is_valid (fd))
1411 _DBUS_ASSERT_ERROR_IS_SET (error);
1412 _dbus_string_free (&address);
1416 _dbus_verbose ("Successfully connected to tcp socket %s:%s\n",
1419 transport = _dbus_transport_new_for_socket (fd, NULL, &address);
1420 _dbus_string_free (&address);
1421 if (transport == NULL)
1423 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1424 _dbus_close_socket (fd, NULL);
1425 _dbus_socket_invalidate (&fd);
1431 _dbus_string_free (&address);
1432 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1437 * Opens a TCP socket transport.
1439 * @param entry the address entry to try opening as a tcp transport.
1440 * @param transport_p return location for the opened transport
1441 * @param error error to be set
1442 * @returns result of the attempt
1444 DBusTransportOpenResult
1445 _dbus_transport_open_socket(DBusAddressEntry *entry,
1446 DBusTransport **transport_p,
1451 dbus_bool_t isNonceTcp;
1453 method = dbus_address_entry_get_method (entry);
1454 _dbus_assert (method != NULL);
1456 isTcp = strcmp (method, "tcp") == 0;
1457 isNonceTcp = strcmp (method, "nonce-tcp") == 0;
1459 if (isTcp || isNonceTcp)
1461 const char *host = dbus_address_entry_get_value (entry, "host");
1462 const char *port = dbus_address_entry_get_value (entry, "port");
1463 const char *family = dbus_address_entry_get_value (entry, "family");
1464 const char *noncefile = dbus_address_entry_get_value (entry, "noncefile");
1466 if ((isNonceTcp == TRUE) != (noncefile != NULL)) {
1467 _dbus_set_bad_address (error, method, "noncefile", NULL);
1468 return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
1473 _dbus_set_bad_address (error, method, "port", NULL);
1474 return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
1477 *transport_p = _dbus_transport_new_for_tcp_socket (host, port, family, noncefile, error);
1478 if (*transport_p == NULL)
1480 _DBUS_ASSERT_ERROR_IS_SET (error);
1481 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
1485 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1486 return DBUS_TRANSPORT_OPEN_OK;
1491 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1492 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;