da95d2c286d3909bf3aa3083a76093dde277faca
[platform/upstream/dbus.git] / dbus / dbus-transport.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-transport.c DBusTransport object (internal to D-Bus implementation)
3  *
4  * Copyright (C) 2002, 2003  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
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.
12  *
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.
17  * 
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
21  *
22  */
23
24 #include <config.h>
25 #include "dbus-transport-protected.h"
26 #include "dbus-transport-unix.h"
27 #include "dbus-transport-socket.h"
28 #include "dbus-connection-internal.h"
29 #include "dbus-watch.h"
30 #include "dbus-auth.h"
31 #include "dbus-authorization.h"
32 #include "dbus-address.h"
33 #include "dbus-credentials.h"
34 #include "dbus-mainloop.h"
35 #include "dbus-message.h"
36 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
37 #include "dbus-server-debug-pipe.h"
38 #endif
39
40 /**
41  * @defgroup DBusTransport DBusTransport object
42  * @ingroup  DBusInternals
43  * @brief "Backend" for a DBusConnection.
44  *
45  * Types and functions related to DBusTransport.  A transport is an
46  * abstraction that can send and receive data via various kinds of
47  * network connections or other IPC mechanisms.
48  * 
49  * @{
50  */
51
52 /**
53  * @typedef DBusTransport
54  *
55  * Opaque object representing a way message stream.
56  * DBusTransport abstracts various kinds of actual
57  * transport mechanism, such as different network protocols,
58  * or encryption schemes.
59  */
60
61 static void
62 live_messages_notify (DBusCounter *counter,
63                            void        *user_data)
64 {
65   DBusTransport *transport = user_data;
66
67   _dbus_transport_ref (transport);
68
69 #if 0
70   _dbus_verbose ("Size counter value is now %d\n",
71                  (int) _dbus_counter_get_size_value (counter));
72   _dbus_verbose ("Unix FD counter value is now %d\n",
73                  (int) _dbus_counter_get_unix_fd_value (counter));
74 #endif
75
76   /* disable or re-enable the read watch for the transport if
77    * required.
78    */
79   if (transport->vtable->live_messages_changed)
80     {
81       _dbus_connection_lock (transport->connection);
82       (* transport->vtable->live_messages_changed) (transport);
83       _dbus_connection_unlock (transport->connection);
84     }
85
86   _dbus_transport_unref (transport);
87 }
88
89 /**
90  * Initializes the base class members of DBusTransport.  Chained up to
91  * by subclasses in their constructor.  The server GUID is the
92  * globally unique ID for the server creating this connection
93  * and will be #NULL for the client side of a connection. The GUID
94  * is in hex format.
95  *
96  * @param transport the transport being created.
97  * @param vtable the subclass vtable.
98  * @param server_guid non-#NULL if this transport is on the server side of a connection
99  * @param address the address of the transport
100  * @returns #TRUE on success.
101  */
102 dbus_bool_t
103 _dbus_transport_init_base (DBusTransport             *transport,
104                            const DBusTransportVTable *vtable,
105                            const DBusString          *server_guid,
106                            const DBusString          *address)
107 {
108   DBusMessageLoader *loader;
109   DBusAuth *auth;
110   DBusAuthorization *authorization = NULL; /* non-NULL only if is_server=TRUE */
111   DBusCounter *counter;
112   char *address_copy;
113   DBusCredentials *creds;
114   
115   loader = _dbus_message_loader_new ();
116   if (loader == NULL)
117     return FALSE;
118
119   if (server_guid != NULL)
120     {
121       authorization = _dbus_authorization_new ();
122       if (authorization == NULL)
123         {
124           _dbus_message_loader_unref (loader);
125           return FALSE; /* OOM */
126         }
127
128       auth = _dbus_auth_server_new (server_guid, authorization);
129     }
130   else
131     {
132       auth = _dbus_auth_client_new ();
133     }
134   if (auth == NULL)
135     {
136       if (authorization != NULL)
137         _dbus_authorization_free (authorization);
138       _dbus_message_loader_unref (loader);
139       return FALSE;
140     }
141
142   counter = _dbus_counter_new ();
143   if (counter == NULL)
144     {
145       _dbus_auth_free (auth);
146       if (authorization != NULL)
147         _dbus_authorization_free (authorization);
148       _dbus_message_loader_unref (loader);
149       return FALSE;
150     }  
151
152   creds = _dbus_credentials_new ();
153   if (creds == NULL)
154     {
155       _dbus_counter_unref (counter);
156       _dbus_auth_free (auth);
157       if (authorization != NULL)
158         _dbus_authorization_free (authorization);
159       _dbus_message_loader_unref (loader);
160       return FALSE;
161     }
162   
163   if (server_guid != NULL)
164     {
165       _dbus_assert (address == NULL);
166       address_copy = NULL;
167     }
168   else
169     {
170       _dbus_assert (address != NULL);
171
172       if (!_dbus_string_copy_data (address, &address_copy))
173         {
174           _dbus_credentials_unref (creds);
175           _dbus_counter_unref (counter);
176           _dbus_auth_free (auth);
177           if (authorization != NULL)
178             _dbus_authorization_free (authorization);
179           _dbus_message_loader_unref (loader);
180           return FALSE;
181         }
182     }
183   
184   transport->refcount = 1;
185   transport->vtable = vtable;
186   transport->loader = loader;
187   transport->authorization = authorization;
188   transport->auth = auth;
189   transport->live_messages = counter;
190   transport->authenticated = FALSE;
191   transport->disconnected = FALSE;
192   transport->is_server = (server_guid != NULL);
193   transport->send_credentials_pending = !transport->is_server;
194   transport->receive_credentials_pending = transport->is_server;
195   transport->address = address_copy;
196
197   transport->expected_guid = NULL;
198   
199   /* Try to default to something that won't totally hose the system,
200    * but doesn't impose too much of a limitation.
201    */
202   transport->max_live_messages_size = _DBUS_ONE_MEGABYTE * 63;
203
204   /* On Linux RLIMIT_NOFILE defaults to 1024, so allowing 4096 fds live
205      should be more than enough */
206   transport->max_live_messages_unix_fds = 4096;
207
208   /* credentials read from socket if any */
209   transport->credentials = creds;
210
211   _dbus_counter_set_notify (transport->live_messages,
212                             transport->max_live_messages_size,
213                             transport->max_live_messages_unix_fds,
214                             live_messages_notify,
215                             transport);
216
217   if (transport->address)
218     _dbus_verbose ("Initialized transport on address %s\n", transport->address);
219
220   /* we can have authorization data set only in server mode */
221   _dbus_assert ((transport->is_server && transport->authorization != NULL) ||
222       (!transport->is_server && transport->authorization == NULL));
223
224   return TRUE;
225 }
226
227 /**
228  * Finalizes base class members of DBusTransport.
229  * Chained up to from subclass finalizers.
230  *
231  * @param transport the transport.
232  */
233 void
234 _dbus_transport_finalize_base (DBusTransport *transport)
235 {
236   if (!transport->disconnected)
237     _dbus_transport_disconnect (transport);
238
239   _dbus_message_loader_unref (transport->loader);
240   _dbus_auth_free (transport->auth);
241   if (transport->authorization)
242     _dbus_authorization_free (transport->authorization);
243   _dbus_counter_set_notify (transport->live_messages,
244                             0, 0, NULL, NULL);
245   _dbus_counter_unref (transport->live_messages);
246   dbus_free (transport->address);
247   dbus_free (transport->expected_guid);
248   if (transport->credentials)
249     _dbus_credentials_unref (transport->credentials);
250 }
251
252
253 /**
254  * Verifies if a given D-Bus address is a valid address
255  * by attempting to connect to it. If it is, returns the
256  * opened DBusTransport object. If it isn't, returns #NULL
257  * and sets @p error.
258  *
259  * @param address the address to be checked.
260  * @param error address where an error can be returned.
261  * @returns a new transport, or #NULL on failure.
262  */
263 static DBusTransport*
264 check_address (const char *address, DBusError *error)
265 {
266   DBusAddressEntry **entries;
267   DBusTransport *transport = NULL;
268   int len, i;
269
270   _dbus_assert (address != NULL);
271
272   if (!dbus_parse_address (address, &entries, &len, error))
273     return NULL;              /* not a valid address */
274
275   for (i = 0; i < len; i++)
276     {
277       transport = _dbus_transport_open (entries[i], error);
278       if (transport != NULL)
279         break;
280     }
281
282   dbus_address_entries_free (entries);
283   return transport;
284 }
285
286 /**
287  * Creates a new transport for the "autostart" method.
288  * This creates a client-side of a transport.
289  *
290  * @param scope scope of autolaunch (Windows only)
291  * @param error address where an error can be returned.
292  * @returns a new transport, or #NULL on failure.
293  */
294 static DBusTransport*
295 _dbus_transport_new_for_autolaunch (const char *scope, DBusError *error)
296 {
297   DBusString address;
298   DBusTransport *result = NULL;
299
300   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
301
302   if (!_dbus_string_init (&address))
303     {
304       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
305       return NULL;
306     }
307
308   if (!_dbus_get_autolaunch_address (scope, &address, error))
309     {
310       _DBUS_ASSERT_ERROR_IS_SET (error);
311       goto out;
312     }
313
314   result = check_address (_dbus_string_get_const_data (&address), error);
315   if (result == NULL)
316     _DBUS_ASSERT_ERROR_IS_SET (error);
317   else
318     _DBUS_ASSERT_ERROR_IS_CLEAR (error);
319
320  out:
321   _dbus_string_free (&address);
322   return result;
323 }
324
325 static DBusTransportOpenResult
326 _dbus_transport_open_autolaunch (DBusAddressEntry  *entry,
327                                  DBusTransport    **transport_p,
328                                  DBusError         *error)
329 {
330   const char *method;
331   
332   method = dbus_address_entry_get_method (entry);
333   _dbus_assert (method != NULL);
334
335   if (strcmp (method, "autolaunch") == 0)
336     {
337       const char *scope = dbus_address_entry_get_value (entry, "scope");
338
339       *transport_p = _dbus_transport_new_for_autolaunch (scope, error);
340
341       if (*transport_p == NULL)
342         {
343           _DBUS_ASSERT_ERROR_IS_SET (error);
344           return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
345         }
346       else
347         {
348           _DBUS_ASSERT_ERROR_IS_CLEAR (error);
349           return DBUS_TRANSPORT_OPEN_OK;
350         }      
351     }
352   else
353     {
354       _DBUS_ASSERT_ERROR_IS_CLEAR (error);
355       return DBUS_TRANSPORT_OPEN_NOT_HANDLED;
356     }
357 }
358
359 static const struct {
360   DBusTransportOpenResult (* func) (DBusAddressEntry *entry,
361                                     DBusTransport   **transport_p,
362                                     DBusError        *error);
363 } open_funcs[] = {
364   { _dbus_transport_open_socket },
365   { _dbus_transport_open_platform_specific },
366   { _dbus_transport_open_autolaunch }
367 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
368   , { _dbus_transport_open_debug_pipe }
369 #endif
370 };
371
372 /**
373  * Try to open a new transport for the given address entry.  (This
374  * opens a client-side-of-the-connection transport.)
375  * 
376  * @param entry the address entry
377  * @param error location to store reason for failure.
378  * @returns new transport of #NULL on failure.
379  */
380 DBusTransport*
381 _dbus_transport_open (DBusAddressEntry *entry,
382                       DBusError        *error)
383 {
384   DBusTransport *transport;
385   const char *expected_guid_orig;
386   char *expected_guid;
387   int i;
388   DBusError tmp_error = DBUS_ERROR_INIT;
389
390   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
391   
392   transport = NULL;
393   expected_guid_orig = dbus_address_entry_get_value (entry, "guid");
394   expected_guid = _dbus_strdup (expected_guid_orig);
395
396   if (expected_guid_orig != NULL && expected_guid == NULL)
397     {
398       _DBUS_SET_OOM (error);
399       return NULL;
400     }
401
402   for (i = 0; i < (int) _DBUS_N_ELEMENTS (open_funcs); ++i)
403     {
404       DBusTransportOpenResult result;
405
406       _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
407       result = (* open_funcs[i].func) (entry, &transport, &tmp_error);
408
409       switch (result)
410         {
411         case DBUS_TRANSPORT_OPEN_OK:
412           _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
413           goto out;
414           break;
415         case DBUS_TRANSPORT_OPEN_NOT_HANDLED:
416           _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
417           /* keep going through the loop of open funcs */
418           break;
419         case DBUS_TRANSPORT_OPEN_BAD_ADDRESS:
420           _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
421           goto out;
422           break;
423         case DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT:
424           _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
425           goto out;
426           break;
427         }
428     }
429
430  out:
431   
432   if (transport == NULL)
433     {
434       if (!dbus_error_is_set (&tmp_error))
435         _dbus_set_bad_address (&tmp_error,
436                                NULL, NULL,
437                                "Unknown address type (examples of valid types are \"tcp\" and on UNIX \"unix\")");
438       
439       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
440       dbus_move_error(&tmp_error, error);
441       dbus_free (expected_guid);
442     }
443   else
444     {
445       _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
446
447       /* In the case of autostart the initial guid is NULL
448        * and the autostart transport recursively calls
449        * _dbus_open_transport wich returns a transport
450        * with a guid.  That guid is the definitive one.
451        *
452        * FIXME: if more transports are added they may have
453        * an effect on the expected_guid semantics (i.e. 
454        * expected_guid and transport->expected_guid may
455        * both have values).  This is very unlikely though
456        * we should either throw asserts here for those 
457        * corner cases or refactor the code so it is 
458        * clearer on what is expected and what is not
459        */
460       if(expected_guid)
461         transport->expected_guid = expected_guid;
462     }
463
464   return transport;
465 }
466
467 /**
468  * Increments the reference count for the transport.
469  *
470  * @param transport the transport.
471  * @returns the transport.
472  */
473 DBusTransport *
474 _dbus_transport_ref (DBusTransport *transport)
475 {
476   _dbus_assert (transport->refcount > 0);
477   
478   transport->refcount += 1;
479
480   return transport;
481 }
482
483 /**
484  * Decrements the reference count for the transport.
485  * Disconnects and finalizes the transport if
486  * the reference count reaches zero.
487  *
488  * @param transport the transport.
489  */
490 void
491 _dbus_transport_unref (DBusTransport *transport)
492 {
493   _dbus_assert (transport != NULL);
494   _dbus_assert (transport->refcount > 0);
495   
496   transport->refcount -= 1;
497   if (transport->refcount == 0)
498     {
499       _dbus_verbose ("finalizing\n");
500       
501       _dbus_assert (transport->vtable->finalize != NULL);
502       
503       (* transport->vtable->finalize) (transport);
504     }
505 }
506
507 /**
508  * Closes our end of the connection to a remote application. Further
509  * attempts to use this transport will fail. Only the first call to
510  * _dbus_transport_disconnect() will have an effect.
511  *
512  * @param transport the transport.
513  * 
514  */
515 void
516 _dbus_transport_disconnect (DBusTransport *transport)
517 {
518   _dbus_verbose ("start\n");
519   
520   _dbus_assert (transport->vtable->disconnect != NULL);
521   
522   if (transport->disconnected)
523     return;
524
525   (* transport->vtable->disconnect) (transport);
526   
527   transport->disconnected = TRUE;
528
529   _dbus_verbose ("end\n");
530 }
531
532 /**
533  * Returns #TRUE if the transport has not been disconnected.
534  * Disconnection can result from _dbus_transport_disconnect()
535  * or because the server drops its end of the connection.
536  *
537  * @param transport the transport.
538  * @returns whether we're connected
539  */
540 dbus_bool_t
541 _dbus_transport_get_is_connected (DBusTransport *transport)
542 {
543   return !transport->disconnected;
544 }
545
546 /**
547  * Returns #TRUE if we have been authenticated. It will return #TRUE even if
548  * the transport is now disconnected, but was ever authenticated before
549  * disconnecting.
550  *
551  * This replaces the older _dbus_transport_get_is_authenticated() which
552  * had side-effects.
553  *
554  * @param transport the transport
555  * @returns whether we're authenticated
556  */
557 dbus_bool_t
558 _dbus_transport_peek_is_authenticated (DBusTransport *transport)
559 {
560   return transport->authenticated;
561 }
562
563 /**
564  * Returns #TRUE if we have been authenticated. It will return #TRUE even if
565  * the transport is now disconnected, but was ever authenticated before
566  * disconnecting.
567  *
568  * If we have not finished authenticating, but we have enough buffered input
569  * to finish the job, then this function will do so before it returns.
570  *
571  * This used to be called _dbus_transport_get_is_authenticated(), but that
572  * name seems inappropriate for a function with side-effects.
573  *
574  * @todo we drop connection->mutex when calling the unix_user_function,
575  * and windows_user_function, which may not be safe really.
576  *
577  * @param transport the transport
578  * @returns whether we're authenticated
579  */
580 dbus_bool_t
581 _dbus_transport_try_to_authenticate (DBusTransport *transport)
582 {  
583   if (transport->authenticated)
584     return TRUE;
585   else
586     {
587       dbus_bool_t maybe_authenticated;
588       
589       if (transport->disconnected)
590         return FALSE;
591
592       maybe_authenticated =
593         (!(transport->send_credentials_pending ||
594            transport->receive_credentials_pending));
595
596       if (maybe_authenticated)
597         {
598           switch (_dbus_auth_do_work (transport->auth))
599             {
600             case DBUS_AUTH_STATE_AUTHENTICATED:
601               /* leave as maybe_authenticated */
602               break;
603             default:
604               maybe_authenticated = FALSE;
605             }
606         }
607
608       /* If we're the client, verify the GUID
609        */
610       if (maybe_authenticated && !transport->is_server)
611         {
612           const char *server_guid;
613
614           server_guid = _dbus_auth_get_guid_from_server (transport->auth);
615           _dbus_assert (server_guid != NULL);
616
617           if (transport->expected_guid &&
618               strcmp (transport->expected_guid, server_guid) != 0)
619             {
620               _dbus_verbose ("Client expected GUID '%s' and we got '%s' from the server\n",
621                              transport->expected_guid, server_guid);
622               _dbus_transport_disconnect (transport);
623               return FALSE;
624             }
625         }
626
627       transport->authenticated = maybe_authenticated;
628
629       return maybe_authenticated;
630     }
631 }
632
633 /**
634  * See dbus_connection_get_is_anonymous().
635  *
636  * @param transport the transport
637  * @returns #TRUE if not authenticated or authenticated as anonymous
638  */
639 dbus_bool_t
640 _dbus_transport_get_is_anonymous (DBusTransport *transport)
641 {
642   DBusCredentials *auth_identity;
643   
644   if (!transport->authenticated)
645     return TRUE;
646   
647   auth_identity = _dbus_auth_get_identity (transport->auth);
648
649   if (_dbus_credentials_are_anonymous (auth_identity))
650     return TRUE;
651   else
652     return FALSE;
653 }
654
655 /**
656  * Returns TRUE if the transport supports sending unix fds.
657  *
658  * @param transport the transport
659  * @returns #TRUE if TRUE it is possible to send unix fds across the transport.
660  */
661 dbus_bool_t
662 _dbus_transport_can_pass_unix_fd(DBusTransport *transport)
663 {
664   return DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport);
665 }
666
667 /**
668  * Gets the address of a transport. It will be
669  * #NULL for a server-side transport.
670  *
671  * @param transport the transport
672  * @returns transport's address
673  */
674 const char*
675 _dbus_transport_get_address (DBusTransport *transport)
676 {
677   return transport->address;
678 }
679
680 /**
681  * Gets the id of the server we are connected to (see
682  * dbus_server_get_id()). Only works on client side.
683  *
684  * @param transport the transport
685  * @returns transport's server's id or #NULL if we are the server side
686  */
687 const char*
688 _dbus_transport_get_server_id (DBusTransport *transport)
689 {
690   if (transport->is_server)
691     return NULL;
692   else if (transport->authenticated)
693     return _dbus_auth_get_guid_from_server (transport->auth);
694   else
695     return transport->expected_guid;
696 }
697
698 /**
699  * Handles a watch by reading data, writing data, or disconnecting
700  * the transport, as appropriate for the given condition.
701  *
702  * @param transport the transport.
703  * @param watch the watch.
704  * @param condition the current state of the watched file descriptor.
705  * @returns #FALSE if not enough memory to fully handle the watch
706  */
707 dbus_bool_t
708 _dbus_transport_handle_watch (DBusTransport           *transport,
709                               DBusWatch               *watch,
710                               unsigned int             condition)
711 {
712   dbus_bool_t retval;
713   
714   _dbus_assert (transport->vtable->handle_watch != NULL);
715
716   if (transport->disconnected)
717     return TRUE;
718
719   if (dbus_watch_get_socket (watch) < 0)
720     {
721       _dbus_warn_check_failed ("Tried to handle an invalidated watch; this watch should have been removed\n");
722       return TRUE;
723     }
724   
725   _dbus_watch_sanitize_condition (watch, &condition);
726
727   _dbus_transport_ref (transport);
728   _dbus_watch_ref (watch);
729   retval = (* transport->vtable->handle_watch) (transport, watch, condition);
730   _dbus_watch_unref (watch);
731   _dbus_transport_unref (transport);
732
733   return retval;
734 }
735
736 /**
737  * Sets the connection using this transport. Allows the transport
738  * to add watches to the connection, queue incoming messages,
739  * and pull outgoing messages.
740  *
741  * @param transport the transport.
742  * @param connection the connection.
743  * @returns #FALSE if not enough memory
744  */
745 dbus_bool_t
746 _dbus_transport_set_connection (DBusTransport  *transport,
747                                 DBusConnection *connection)
748 {
749   _dbus_assert (transport->vtable->connection_set != NULL);
750   _dbus_assert (transport->connection == NULL);
751   
752   transport->connection = connection;
753   if (transport->is_server)
754     _dbus_authorization_set_connection (transport->authorization, connection);
755
756   _dbus_transport_ref (transport);
757   if (!(* transport->vtable->connection_set) (transport))
758     transport->connection = NULL;
759   _dbus_transport_unref (transport);
760
761   return transport->connection != NULL;
762 }
763
764 /**
765  * Get the socket file descriptor, if any.
766  *
767  * @param transport the transport
768  * @param fd_p pointer to fill in with the descriptor
769  * @returns #TRUE if a descriptor was available
770  */
771 dbus_bool_t
772 _dbus_transport_get_socket_fd (DBusTransport *transport,
773                                int           *fd_p)
774 {
775   dbus_bool_t retval;
776   
777   if (transport->vtable->get_socket_fd == NULL)
778     return FALSE;
779
780   if (transport->disconnected)
781     return FALSE;
782
783   _dbus_transport_ref (transport);
784
785   retval = (* transport->vtable->get_socket_fd) (transport,
786                                                  fd_p);
787   
788   _dbus_transport_unref (transport);
789
790   return retval;
791 }
792
793 /**
794  * Performs a single poll()/select() on the transport's file
795  * descriptors and then reads/writes data as appropriate,
796  * queueing incoming messages and sending outgoing messages.
797  * This is the backend for _dbus_connection_do_iteration().
798  * See _dbus_connection_do_iteration() for full details.
799  *
800  * @param transport the transport.
801  * @param flags indicates whether to read or write, and whether to block.
802  * @param timeout_milliseconds if blocking, timeout or -1 for no timeout.
803  */
804 void
805 _dbus_transport_do_iteration (DBusTransport  *transport,
806                               unsigned int    flags,
807                               int             timeout_milliseconds)
808 {
809   _dbus_assert (transport->vtable->do_iteration != NULL);
810
811   _dbus_verbose ("Transport iteration flags 0x%x timeout %d connected = %d\n",
812                  flags, timeout_milliseconds, !transport->disconnected);
813   
814   if ((flags & (DBUS_ITERATION_DO_WRITING |
815                 DBUS_ITERATION_DO_READING)) == 0)
816     return; /* Nothing to do */
817
818   if (transport->disconnected)
819     return;
820
821   _dbus_transport_ref (transport);
822   (* transport->vtable->do_iteration) (transport, flags,
823                                        timeout_milliseconds);
824   _dbus_transport_unref (transport);
825
826   _dbus_verbose ("end\n");
827 }
828
829 static dbus_bool_t
830 recover_unused_bytes (DBusTransport *transport)
831 {
832   if (_dbus_auth_needs_decoding (transport->auth))
833     {
834       DBusString plaintext;
835       const DBusString *encoded;
836       DBusString *buffer;
837       int orig_len;
838       
839       if (!_dbus_string_init (&plaintext))
840         goto nomem;
841       
842       _dbus_auth_get_unused_bytes (transport->auth,
843                                    &encoded);
844
845       if (!_dbus_auth_decode_data (transport->auth,
846                                    encoded, &plaintext))
847         {
848           _dbus_string_free (&plaintext);
849           goto nomem;
850         }
851       
852       _dbus_message_loader_get_buffer (transport->loader,
853                                        &buffer);
854       
855       orig_len = _dbus_string_get_length (buffer);
856       
857       if (!_dbus_string_move (&plaintext, 0, buffer,
858                               orig_len))
859         {
860           _dbus_string_free (&plaintext);
861           goto nomem;
862         }
863       
864       _dbus_verbose (" %d unused bytes sent to message loader\n", 
865                      _dbus_string_get_length (buffer) -
866                      orig_len);
867       
868       _dbus_message_loader_return_buffer (transport->loader,
869                                           buffer,
870                                           _dbus_string_get_length (buffer) -
871                                           orig_len);
872
873       _dbus_auth_delete_unused_bytes (transport->auth);
874       
875       _dbus_string_free (&plaintext);
876     }
877   else
878     {
879       const DBusString *bytes;
880       DBusString *buffer;
881       int orig_len;
882       dbus_bool_t succeeded;
883
884       _dbus_message_loader_get_buffer (transport->loader,
885                                        &buffer);
886                 
887       orig_len = _dbus_string_get_length (buffer);
888                 
889       _dbus_auth_get_unused_bytes (transport->auth,
890                                    &bytes);
891
892       succeeded = TRUE;
893       if (!_dbus_string_copy (bytes, 0, buffer, _dbus_string_get_length (buffer)))
894         succeeded = FALSE;
895       
896       _dbus_verbose (" %d unused bytes sent to message loader\n", 
897                      _dbus_string_get_length (buffer) -
898                      orig_len);
899       
900       _dbus_message_loader_return_buffer (transport->loader,
901                                           buffer,
902                                           _dbus_string_get_length (buffer) -
903                                           orig_len);
904
905       if (succeeded)
906         _dbus_auth_delete_unused_bytes (transport->auth);
907       else
908         goto nomem;
909     }
910
911   return TRUE;
912
913  nomem:
914   _dbus_verbose ("Not enough memory to transfer unused bytes from auth conversation\n");
915   return FALSE;
916 }
917
918 /**
919  * Reports our current dispatch status (whether there's buffered
920  * data to be queued as messages, or not, or we need memory).
921  *
922  * @param transport the transport
923  * @returns current status
924  */
925 DBusDispatchStatus
926 _dbus_transport_get_dispatch_status (DBusTransport *transport)
927 {
928   if (_dbus_counter_get_size_value (transport->live_messages) >= transport->max_live_messages_size ||
929       _dbus_counter_get_unix_fd_value (transport->live_messages) >= transport->max_live_messages_unix_fds)
930     return DBUS_DISPATCH_COMPLETE; /* complete for now */
931
932   if (!_dbus_transport_try_to_authenticate (transport))
933     {
934       if (_dbus_auth_do_work (transport->auth) ==
935           DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
936         return DBUS_DISPATCH_NEED_MEMORY;
937       else if (!_dbus_transport_try_to_authenticate (transport))
938         return DBUS_DISPATCH_COMPLETE;
939     }
940
941   if (!transport->unused_bytes_recovered &&
942       !recover_unused_bytes (transport))
943     return DBUS_DISPATCH_NEED_MEMORY;
944
945   transport->unused_bytes_recovered = TRUE;
946   
947   if (!_dbus_message_loader_queue_messages (transport->loader))
948     return DBUS_DISPATCH_NEED_MEMORY;
949
950   if (_dbus_message_loader_peek_message (transport->loader) != NULL)
951     return DBUS_DISPATCH_DATA_REMAINS;
952   else
953     return DBUS_DISPATCH_COMPLETE;
954 }
955
956 /**
957  * Processes data we've read while handling a watch, potentially
958  * converting some of it to messages and queueing those messages on
959  * the connection.
960  *
961  * @param transport the transport
962  * @returns #TRUE if we had enough memory to queue all messages
963  */
964 dbus_bool_t
965 _dbus_transport_queue_messages (DBusTransport *transport)
966 {
967   DBusDispatchStatus status;
968
969 #if 0
970   _dbus_verbose ("_dbus_transport_queue_messages()\n");
971 #endif
972   
973   /* Queue any messages */
974   while ((status = _dbus_transport_get_dispatch_status (transport)) == DBUS_DISPATCH_DATA_REMAINS)
975     {
976       DBusMessage *message;
977       DBusList *link;
978
979       link = _dbus_message_loader_pop_message_link (transport->loader);
980       _dbus_assert (link != NULL);
981       
982       message = link->data;
983       
984       _dbus_verbose ("queueing received message %p\n", message);
985
986       if (!_dbus_message_add_counter (message, transport->live_messages))
987         {
988           _dbus_message_loader_putback_message_link (transport->loader,
989                                                      link);
990           status = DBUS_DISPATCH_NEED_MEMORY;
991           break;
992         }
993       else
994         {
995           /* We didn't call the notify function when we added the counter, so
996            * catch up now. Since we have the connection's lock, it's desirable
997            * that we bypass the notify function and call this virtual method
998            * directly. */
999           if (transport->vtable->live_messages_changed)
1000             (* transport->vtable->live_messages_changed) (transport);
1001
1002           /* pass ownership of link and message ref to connection */
1003           _dbus_connection_queue_received_message_link (transport->connection,
1004                                                         link);
1005         }
1006     }
1007
1008   if (_dbus_message_loader_get_is_corrupted (transport->loader))
1009     {
1010       _dbus_verbose ("Corrupted message stream, disconnecting\n");
1011       _dbus_transport_disconnect (transport);
1012     }
1013
1014   return status != DBUS_DISPATCH_NEED_MEMORY;
1015 }
1016
1017 /**
1018  * See dbus_connection_set_max_message_size().
1019  *
1020  * @param transport the transport
1021  * @param size the max size of a single message
1022  */
1023 void
1024 _dbus_transport_set_max_message_size (DBusTransport  *transport,
1025                                       long            size)
1026 {
1027   _dbus_message_loader_set_max_message_size (transport->loader, size);
1028 }
1029
1030 /**
1031  * See dbus_connection_set_max_message_unix_fds().
1032  *
1033  * @param transport the transport
1034  * @param n the max number of unix fds of a single message
1035  */
1036 void
1037 _dbus_transport_set_max_message_unix_fds (DBusTransport  *transport,
1038                                           long            n)
1039 {
1040   _dbus_message_loader_set_max_message_unix_fds (transport->loader, n);
1041 }
1042
1043 /**
1044  * See dbus_connection_get_max_message_size().
1045  *
1046  * @param transport the transport
1047  * @returns max message size
1048  */
1049 long
1050 _dbus_transport_get_max_message_size (DBusTransport  *transport)
1051 {
1052   return _dbus_message_loader_get_max_message_size (transport->loader);
1053 }
1054
1055 /**
1056  * See dbus_connection_get_max_message_unix_fds().
1057  *
1058  * @param transport the transport
1059  * @returns max message unix fds
1060  */
1061 long
1062 _dbus_transport_get_max_message_unix_fds (DBusTransport  *transport)
1063 {
1064   return _dbus_message_loader_get_max_message_unix_fds (transport->loader);
1065 }
1066
1067 /**
1068  * See dbus_connection_set_max_received_size().
1069  *
1070  * @param transport the transport
1071  * @param size the max size of all incoming messages
1072  */
1073 void
1074 _dbus_transport_set_max_received_size (DBusTransport  *transport,
1075                                        long            size)
1076 {
1077   transport->max_live_messages_size = size;
1078   _dbus_counter_set_notify (transport->live_messages,
1079                             transport->max_live_messages_size,
1080                             transport->max_live_messages_unix_fds,
1081                             live_messages_notify,
1082                             transport);
1083 }
1084
1085 /**
1086  * See dbus_connection_set_max_received_unix_fds().
1087  *
1088  * @param transport the transport
1089  * @param n the max unix fds of all incoming messages
1090  */
1091 void
1092 _dbus_transport_set_max_received_unix_fds (DBusTransport  *transport,
1093                                            long            n)
1094 {
1095   transport->max_live_messages_unix_fds = n;
1096   _dbus_counter_set_notify (transport->live_messages,
1097                             transport->max_live_messages_size,
1098                             transport->max_live_messages_unix_fds,
1099                             live_messages_notify,
1100                             transport);
1101 }
1102
1103 /**
1104  * See dbus_connection_get_max_received_size().
1105  *
1106  * @param transport the transport
1107  * @returns max bytes for all live messages
1108  */
1109 long
1110 _dbus_transport_get_max_received_size (DBusTransport  *transport)
1111 {
1112   return transport->max_live_messages_size;
1113 }
1114
1115 /**
1116  * See dbus_connection_set_max_received_unix_fds().
1117  *
1118  * @param transport the transport
1119  * @returns max unix fds for all live messages
1120  */
1121 long
1122 _dbus_transport_get_max_received_unix_fds (DBusTransport  *transport)
1123 {
1124   return transport->max_live_messages_unix_fds;
1125 }
1126
1127 /**
1128  * See dbus_connection_get_unix_user().
1129  *
1130  * @param transport the transport
1131  * @param uid return location for the user ID
1132  * @returns #TRUE if uid is filled in with a valid user ID
1133  */
1134 dbus_bool_t
1135 _dbus_transport_get_unix_user (DBusTransport *transport,
1136                                unsigned long *uid)
1137 {
1138   DBusCredentials *auth_identity;
1139
1140   *uid = _DBUS_INT32_MAX; /* better than some root or system user in
1141                            * case of bugs in the caller. Caller should
1142                            * never use this value on purpose, however.
1143                            */
1144   
1145   if (!transport->authenticated)
1146     return FALSE;
1147   
1148   auth_identity = _dbus_auth_get_identity (transport->auth);
1149
1150   if (_dbus_credentials_include (auth_identity,
1151                                  DBUS_CREDENTIAL_UNIX_USER_ID))
1152     {
1153       *uid = _dbus_credentials_get_unix_uid (auth_identity);
1154       return TRUE;
1155     }
1156   else
1157     return FALSE;
1158 }
1159
1160 /**
1161  * See dbus_connection_get_unix_process_id().
1162  *
1163  * @param transport the transport
1164  * @param pid return location for the process ID
1165  * @returns #TRUE if uid is filled in with a valid process ID
1166  */
1167 dbus_bool_t
1168 _dbus_transport_get_unix_process_id (DBusTransport *transport,
1169                                      unsigned long *pid)
1170 {
1171   DBusCredentials *auth_identity;
1172
1173   *pid = DBUS_PID_UNSET; /* Caller should never use this value on purpose,
1174                           * but we set it to a safe number, INT_MAX,
1175                           * just to root out possible bugs in bad callers.
1176                           */
1177   
1178   if (!transport->authenticated)
1179     return FALSE;
1180   
1181   auth_identity = _dbus_auth_get_identity (transport->auth);
1182
1183   if (_dbus_credentials_include (auth_identity,
1184                                  DBUS_CREDENTIAL_UNIX_PROCESS_ID))
1185     {
1186       *pid = _dbus_credentials_get_pid (auth_identity);
1187       return TRUE;
1188     }
1189   else
1190     return FALSE;
1191 }
1192
1193 /**
1194  * See dbus_connection_get_adt_audit_session_data().
1195  *
1196  * @param transport the transport
1197  * @param data return location for the ADT audit data 
1198  * @param data_size return length of audit data
1199  * @returns #TRUE if audit data is filled in with a valid ucred
1200  */
1201 dbus_bool_t
1202 _dbus_transport_get_adt_audit_session_data (DBusTransport      *transport,
1203                                             void              **data,
1204                                             int                *data_size)
1205 {
1206   DBusCredentials *auth_identity;
1207
1208   *data = NULL;
1209   *data_size = 0;
1210   
1211   if (!transport->authenticated)
1212     return FALSE;
1213   
1214   auth_identity = _dbus_auth_get_identity (transport->auth);
1215
1216   if (_dbus_credentials_include (auth_identity,
1217                                  DBUS_CREDENTIAL_ADT_AUDIT_DATA_ID))
1218     {
1219       *data = (void *) _dbus_credentials_get_adt_audit_data (auth_identity);
1220       *data_size = _dbus_credentials_get_adt_audit_data_size (auth_identity);
1221       return TRUE;
1222     }
1223   else
1224     return FALSE;
1225 }
1226
1227 /**
1228  * See dbus_connection_set_unix_user_function().
1229  *
1230  * @param transport the transport
1231  * @param function the predicate
1232  * @param data data to pass to the predicate
1233  * @param free_data_function function to free the data
1234  * @param old_data the old user data to be freed
1235  * @param old_free_data_function old free data function to free it with
1236  */
1237 inline void
1238 _dbus_transport_set_unix_user_function (DBusTransport             *transport,
1239                                         DBusAllowUnixUserFunction  function,
1240                                         void                      *data,
1241                                         DBusFreeFunction           free_data_function,
1242                                         void                     **old_data,
1243                                         DBusFreeFunction          *old_free_data_function)
1244 {
1245   if (transport->is_server)
1246     _dbus_authorization_set_unix_authorization_callback (transport->authorization, function,
1247         data, free_data_function, old_data, old_free_data_function);
1248 }
1249
1250 /**
1251  * See dbus_connection_get_windows_user().
1252  *
1253  * @param transport the transport
1254  * @param windows_sid_p return location for the user ID
1255  * @returns #TRUE if user is available; the returned value may still be #NULL if no memory to copy it
1256  */
1257 dbus_bool_t
1258 _dbus_transport_get_windows_user (DBusTransport              *transport,
1259                                   char                      **windows_sid_p)
1260 {
1261   DBusCredentials *auth_identity;
1262
1263   *windows_sid_p = NULL;
1264   
1265   if (!transport->authenticated)
1266     return FALSE;
1267   
1268   auth_identity = _dbus_auth_get_identity (transport->auth);
1269
1270   if (_dbus_credentials_include (auth_identity,
1271                                  DBUS_CREDENTIAL_WINDOWS_SID))
1272     {
1273       /* If no memory, we are supposed to return TRUE and set NULL */
1274       *windows_sid_p = _dbus_strdup (_dbus_credentials_get_windows_sid (auth_identity));
1275
1276       return TRUE;
1277     }
1278   else
1279     return FALSE;
1280 }
1281
1282 /**
1283  * See dbus_connection_set_windows_user_function().
1284  *
1285  * @param transport the transport
1286  * @param function the predicate
1287  * @param data data to pass to the predicate
1288  * @param free_data_function function to free the data
1289  * @param old_data the old user data to be freed
1290  * @param old_free_data_function old free data function to free it with
1291  */
1292
1293 inline void
1294 _dbus_transport_set_windows_user_function (DBusTransport              *transport,
1295                                            DBusAllowWindowsUserFunction   function,
1296                                            void                       *data,
1297                                            DBusFreeFunction            free_data_function,
1298                                            void                      **old_data,
1299                                            DBusFreeFunction           *old_free_data_function)
1300 {
1301   if (transport->is_server)
1302     _dbus_authorization_set_windows_authorization_callback (transport->authorization, function,
1303         data, free_data_function, old_data, old_free_data_function);
1304 }
1305
1306 /**
1307  * Sets the SASL authentication mechanisms supported by this transport.
1308  *
1309  * @param transport the transport
1310  * @param mechanisms the #NULL-terminated array of mechanisms
1311  *
1312  * @returns #FALSE if no memory
1313  */
1314 dbus_bool_t
1315 _dbus_transport_set_auth_mechanisms (DBusTransport  *transport,
1316                                      const char    **mechanisms)
1317 {
1318   return _dbus_auth_set_mechanisms (transport->auth, mechanisms);
1319 }
1320
1321 /**
1322  * See dbus_connection_set_allow_anonymous()
1323  *
1324  * @param transport the transport
1325  * @param value #TRUE to allow anonymous connection
1326  */
1327 inline void
1328 _dbus_transport_set_allow_anonymous (DBusTransport              *transport,
1329                                      dbus_bool_t                 value)
1330 {
1331   if (transport->is_server)
1332     _dbus_authorization_set_allow_anonymous (transport->authorization, value);
1333 }
1334
1335 #ifdef DBUS_ENABLE_STATS
1336 void
1337 _dbus_transport_get_stats (DBusTransport  *transport,
1338                            dbus_uint32_t  *queue_bytes,
1339                            dbus_uint32_t  *queue_fds,
1340                            dbus_uint32_t  *peak_queue_bytes,
1341                            dbus_uint32_t  *peak_queue_fds)
1342 {
1343   if (queue_bytes != NULL)
1344     *queue_bytes = _dbus_counter_get_size_value (transport->live_messages);
1345
1346   if (queue_fds != NULL)
1347     *queue_fds = _dbus_counter_get_unix_fd_value (transport->live_messages);
1348
1349   if (peak_queue_bytes != NULL)
1350     *peak_queue_bytes = _dbus_counter_get_peak_size_value (transport->live_messages);
1351
1352   if (peak_queue_fds != NULL)
1353     *peak_queue_fds = _dbus_counter_get_peak_unix_fd_value (transport->live_messages);
1354 }
1355 #endif /* DBUS_ENABLE_STATS */
1356
1357 /** @} */