Revert "Actually use DBusAuthorization in DBusAuth EXTERNAL mech"
[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);
129     }
130   else
131     {
132       auth = _dbus_auth_client_new ();
133     }
134   if (auth == NULL)
135     {
136       if (authorization != NULL)
137         _dbus_authorization_unref (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_unref (auth);
146       if (authorization != NULL)
147         _dbus_authorization_unref (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_unref (auth);
157       if (authorization != NULL)
158         _dbus_authorization_unref (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_unref (auth);
177           if (authorization != NULL)
178             _dbus_authorization_unref (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_unref (transport->auth);
241   if (transport->authorization)
242     _dbus_authorization_unref (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       /* paranoia ref since we call user callbacks sometimes */
593       _dbus_connection_ref_unlocked (transport->connection);
594       
595       maybe_authenticated =
596         (!(transport->send_credentials_pending ||
597            transport->receive_credentials_pending));
598
599       if (maybe_authenticated)
600         {
601           switch (_dbus_auth_do_work (transport->auth))
602             {
603             case DBUS_AUTH_STATE_AUTHENTICATED:
604               /* leave as maybe_authenticated */
605               break;
606             default:
607               maybe_authenticated = FALSE;
608             }
609         }
610
611       /* If we're the client, verify the GUID
612        */
613       if (maybe_authenticated && !transport->is_server)
614         {
615           const char *server_guid;
616
617           server_guid = _dbus_auth_get_guid_from_server (transport->auth);
618           _dbus_assert (server_guid != NULL);
619
620           if (transport->expected_guid &&
621               strcmp (transport->expected_guid, server_guid) != 0)
622             {
623               _dbus_verbose ("Client expected GUID '%s' and we got '%s' from the server\n",
624                              transport->expected_guid, server_guid);
625               _dbus_transport_disconnect (transport);
626               _dbus_connection_unref_unlocked (transport->connection);
627               return FALSE;
628             }
629         }
630
631       /* If we're the server, see if we want to allow this identity to proceed.
632        */
633       if (maybe_authenticated && transport->is_server)
634         {
635           DBusCredentials *auth_identity;
636
637           auth_identity = _dbus_auth_get_identity (transport->auth);
638           _dbus_assert (auth_identity != NULL);
639           
640           /* If we have an authenticated user, delegate deciding whether auth
641            * credentials are good enough to the app */
642           if (!_dbus_authorization_do_authorization (transport->authorization, auth_identity))
643             {
644               _dbus_transport_disconnect (transport);
645               maybe_authenticated = FALSE;
646             }
647         }
648
649       transport->authenticated = maybe_authenticated;
650
651       _dbus_connection_unref_unlocked (transport->connection);
652       return maybe_authenticated;
653     }
654 }
655
656 /**
657  * See dbus_connection_get_is_anonymous().
658  *
659  * @param transport the transport
660  * @returns #TRUE if not authenticated or authenticated as anonymous
661  */
662 dbus_bool_t
663 _dbus_transport_get_is_anonymous (DBusTransport *transport)
664 {
665   DBusCredentials *auth_identity;
666   
667   if (!transport->authenticated)
668     return TRUE;
669   
670   auth_identity = _dbus_auth_get_identity (transport->auth);
671
672   if (_dbus_credentials_are_anonymous (auth_identity))
673     return TRUE;
674   else
675     return FALSE;
676 }
677
678 /**
679  * Returns TRUE if the transport supports sending unix fds.
680  *
681  * @param transport the transport
682  * @returns #TRUE if TRUE it is possible to send unix fds across the transport.
683  */
684 dbus_bool_t
685 _dbus_transport_can_pass_unix_fd(DBusTransport *transport)
686 {
687   return DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport);
688 }
689
690 /**
691  * Gets the address of a transport. It will be
692  * #NULL for a server-side transport.
693  *
694  * @param transport the transport
695  * @returns transport's address
696  */
697 const char*
698 _dbus_transport_get_address (DBusTransport *transport)
699 {
700   return transport->address;
701 }
702
703 /**
704  * Gets the id of the server we are connected to (see
705  * dbus_server_get_id()). Only works on client side.
706  *
707  * @param transport the transport
708  * @returns transport's server's id or #NULL if we are the server side
709  */
710 const char*
711 _dbus_transport_get_server_id (DBusTransport *transport)
712 {
713   if (transport->is_server)
714     return NULL;
715   else if (transport->authenticated)
716     return _dbus_auth_get_guid_from_server (transport->auth);
717   else
718     return transport->expected_guid;
719 }
720
721 /**
722  * Handles a watch by reading data, writing data, or disconnecting
723  * the transport, as appropriate for the given condition.
724  *
725  * @param transport the transport.
726  * @param watch the watch.
727  * @param condition the current state of the watched file descriptor.
728  * @returns #FALSE if not enough memory to fully handle the watch
729  */
730 dbus_bool_t
731 _dbus_transport_handle_watch (DBusTransport           *transport,
732                               DBusWatch               *watch,
733                               unsigned int             condition)
734 {
735   dbus_bool_t retval;
736   
737   _dbus_assert (transport->vtable->handle_watch != NULL);
738
739   if (transport->disconnected)
740     return TRUE;
741
742   if (dbus_watch_get_socket (watch) < 0)
743     {
744       _dbus_warn_check_failed ("Tried to handle an invalidated watch; this watch should have been removed\n");
745       return TRUE;
746     }
747   
748   _dbus_watch_sanitize_condition (watch, &condition);
749
750   _dbus_transport_ref (transport);
751   _dbus_watch_ref (watch);
752   retval = (* transport->vtable->handle_watch) (transport, watch, condition);
753   _dbus_watch_unref (watch);
754   _dbus_transport_unref (transport);
755
756   return retval;
757 }
758
759 /**
760  * Sets the connection using this transport. Allows the transport
761  * to add watches to the connection, queue incoming messages,
762  * and pull outgoing messages.
763  *
764  * @param transport the transport.
765  * @param connection the connection.
766  * @returns #FALSE if not enough memory
767  */
768 dbus_bool_t
769 _dbus_transport_set_connection (DBusTransport  *transport,
770                                 DBusConnection *connection)
771 {
772   _dbus_assert (transport->vtable->connection_set != NULL);
773   _dbus_assert (transport->connection == NULL);
774   
775   transport->connection = connection;
776   if (transport->is_server)
777     _dbus_authorization_set_connection (transport->authorization, connection);
778
779   _dbus_transport_ref (transport);
780   if (!(* transport->vtable->connection_set) (transport))
781     transport->connection = NULL;
782   _dbus_transport_unref (transport);
783
784   return transport->connection != NULL;
785 }
786
787 /**
788  * Get the socket file descriptor, if any.
789  *
790  * @param transport the transport
791  * @param fd_p pointer to fill in with the descriptor
792  * @returns #TRUE if a descriptor was available
793  */
794 dbus_bool_t
795 _dbus_transport_get_socket_fd (DBusTransport *transport,
796                                int           *fd_p)
797 {
798   dbus_bool_t retval;
799   
800   if (transport->vtable->get_socket_fd == NULL)
801     return FALSE;
802
803   if (transport->disconnected)
804     return FALSE;
805
806   _dbus_transport_ref (transport);
807
808   retval = (* transport->vtable->get_socket_fd) (transport,
809                                                  fd_p);
810   
811   _dbus_transport_unref (transport);
812
813   return retval;
814 }
815
816 /**
817  * Performs a single poll()/select() on the transport's file
818  * descriptors and then reads/writes data as appropriate,
819  * queueing incoming messages and sending outgoing messages.
820  * This is the backend for _dbus_connection_do_iteration().
821  * See _dbus_connection_do_iteration() for full details.
822  *
823  * @param transport the transport.
824  * @param flags indicates whether to read or write, and whether to block.
825  * @param timeout_milliseconds if blocking, timeout or -1 for no timeout.
826  */
827 void
828 _dbus_transport_do_iteration (DBusTransport  *transport,
829                               unsigned int    flags,
830                               int             timeout_milliseconds)
831 {
832   _dbus_assert (transport->vtable->do_iteration != NULL);
833
834   _dbus_verbose ("Transport iteration flags 0x%x timeout %d connected = %d\n",
835                  flags, timeout_milliseconds, !transport->disconnected);
836   
837   if ((flags & (DBUS_ITERATION_DO_WRITING |
838                 DBUS_ITERATION_DO_READING)) == 0)
839     return; /* Nothing to do */
840
841   if (transport->disconnected)
842     return;
843
844   _dbus_transport_ref (transport);
845   (* transport->vtable->do_iteration) (transport, flags,
846                                        timeout_milliseconds);
847   _dbus_transport_unref (transport);
848
849   _dbus_verbose ("end\n");
850 }
851
852 static dbus_bool_t
853 recover_unused_bytes (DBusTransport *transport)
854 {
855   if (_dbus_auth_needs_decoding (transport->auth))
856     {
857       DBusString plaintext;
858       const DBusString *encoded;
859       DBusString *buffer;
860       int orig_len;
861       
862       if (!_dbus_string_init (&plaintext))
863         goto nomem;
864       
865       _dbus_auth_get_unused_bytes (transport->auth,
866                                    &encoded);
867
868       if (!_dbus_auth_decode_data (transport->auth,
869                                    encoded, &plaintext))
870         {
871           _dbus_string_free (&plaintext);
872           goto nomem;
873         }
874       
875       _dbus_message_loader_get_buffer (transport->loader,
876                                        &buffer);
877       
878       orig_len = _dbus_string_get_length (buffer);
879       
880       if (!_dbus_string_move (&plaintext, 0, buffer,
881                               orig_len))
882         {
883           _dbus_string_free (&plaintext);
884           goto nomem;
885         }
886       
887       _dbus_verbose (" %d unused bytes sent to message loader\n", 
888                      _dbus_string_get_length (buffer) -
889                      orig_len);
890       
891       _dbus_message_loader_return_buffer (transport->loader,
892                                           buffer,
893                                           _dbus_string_get_length (buffer) -
894                                           orig_len);
895
896       _dbus_auth_delete_unused_bytes (transport->auth);
897       
898       _dbus_string_free (&plaintext);
899     }
900   else
901     {
902       const DBusString *bytes;
903       DBusString *buffer;
904       int orig_len;
905       dbus_bool_t succeeded;
906
907       _dbus_message_loader_get_buffer (transport->loader,
908                                        &buffer);
909                 
910       orig_len = _dbus_string_get_length (buffer);
911                 
912       _dbus_auth_get_unused_bytes (transport->auth,
913                                    &bytes);
914
915       succeeded = TRUE;
916       if (!_dbus_string_copy (bytes, 0, buffer, _dbus_string_get_length (buffer)))
917         succeeded = FALSE;
918       
919       _dbus_verbose (" %d unused bytes sent to message loader\n", 
920                      _dbus_string_get_length (buffer) -
921                      orig_len);
922       
923       _dbus_message_loader_return_buffer (transport->loader,
924                                           buffer,
925                                           _dbus_string_get_length (buffer) -
926                                           orig_len);
927
928       if (succeeded)
929         _dbus_auth_delete_unused_bytes (transport->auth);
930       else
931         goto nomem;
932     }
933
934   return TRUE;
935
936  nomem:
937   _dbus_verbose ("Not enough memory to transfer unused bytes from auth conversation\n");
938   return FALSE;
939 }
940
941 /**
942  * Reports our current dispatch status (whether there's buffered
943  * data to be queued as messages, or not, or we need memory).
944  *
945  * @param transport the transport
946  * @returns current status
947  */
948 DBusDispatchStatus
949 _dbus_transport_get_dispatch_status (DBusTransport *transport)
950 {
951   if (_dbus_counter_get_size_value (transport->live_messages) >= transport->max_live_messages_size ||
952       _dbus_counter_get_unix_fd_value (transport->live_messages) >= transport->max_live_messages_unix_fds)
953     return DBUS_DISPATCH_COMPLETE; /* complete for now */
954
955   if (!_dbus_transport_try_to_authenticate (transport))
956     {
957       if (_dbus_auth_do_work (transport->auth) ==
958           DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
959         return DBUS_DISPATCH_NEED_MEMORY;
960       else if (!_dbus_transport_try_to_authenticate (transport))
961         return DBUS_DISPATCH_COMPLETE;
962     }
963
964   if (!transport->unused_bytes_recovered &&
965       !recover_unused_bytes (transport))
966     return DBUS_DISPATCH_NEED_MEMORY;
967
968   transport->unused_bytes_recovered = TRUE;
969   
970   if (!_dbus_message_loader_queue_messages (transport->loader))
971     return DBUS_DISPATCH_NEED_MEMORY;
972
973   if (_dbus_message_loader_peek_message (transport->loader) != NULL)
974     return DBUS_DISPATCH_DATA_REMAINS;
975   else
976     return DBUS_DISPATCH_COMPLETE;
977 }
978
979 /**
980  * Processes data we've read while handling a watch, potentially
981  * converting some of it to messages and queueing those messages on
982  * the connection.
983  *
984  * @param transport the transport
985  * @returns #TRUE if we had enough memory to queue all messages
986  */
987 dbus_bool_t
988 _dbus_transport_queue_messages (DBusTransport *transport)
989 {
990   DBusDispatchStatus status;
991
992 #if 0
993   _dbus_verbose ("_dbus_transport_queue_messages()\n");
994 #endif
995   
996   /* Queue any messages */
997   while ((status = _dbus_transport_get_dispatch_status (transport)) == DBUS_DISPATCH_DATA_REMAINS)
998     {
999       DBusMessage *message;
1000       DBusList *link;
1001
1002       link = _dbus_message_loader_pop_message_link (transport->loader);
1003       _dbus_assert (link != NULL);
1004       
1005       message = link->data;
1006       
1007       _dbus_verbose ("queueing received message %p\n", message);
1008
1009       if (!_dbus_message_add_counter (message, transport->live_messages))
1010         {
1011           _dbus_message_loader_putback_message_link (transport->loader,
1012                                                      link);
1013           status = DBUS_DISPATCH_NEED_MEMORY;
1014           break;
1015         }
1016       else
1017         {
1018           /* We didn't call the notify function when we added the counter, so
1019            * catch up now. Since we have the connection's lock, it's desirable
1020            * that we bypass the notify function and call this virtual method
1021            * directly. */
1022           if (transport->vtable->live_messages_changed)
1023             (* transport->vtable->live_messages_changed) (transport);
1024
1025           /* pass ownership of link and message ref to connection */
1026           _dbus_connection_queue_received_message_link (transport->connection,
1027                                                         link);
1028         }
1029     }
1030
1031   if (_dbus_message_loader_get_is_corrupted (transport->loader))
1032     {
1033       _dbus_verbose ("Corrupted message stream, disconnecting\n");
1034       _dbus_transport_disconnect (transport);
1035     }
1036
1037   return status != DBUS_DISPATCH_NEED_MEMORY;
1038 }
1039
1040 /**
1041  * See dbus_connection_set_max_message_size().
1042  *
1043  * @param transport the transport
1044  * @param size the max size of a single message
1045  */
1046 void
1047 _dbus_transport_set_max_message_size (DBusTransport  *transport,
1048                                       long            size)
1049 {
1050   _dbus_message_loader_set_max_message_size (transport->loader, size);
1051 }
1052
1053 /**
1054  * See dbus_connection_set_max_message_unix_fds().
1055  *
1056  * @param transport the transport
1057  * @param n the max number of unix fds of a single message
1058  */
1059 void
1060 _dbus_transport_set_max_message_unix_fds (DBusTransport  *transport,
1061                                           long            n)
1062 {
1063   _dbus_message_loader_set_max_message_unix_fds (transport->loader, n);
1064 }
1065
1066 /**
1067  * See dbus_connection_get_max_message_size().
1068  *
1069  * @param transport the transport
1070  * @returns max message size
1071  */
1072 long
1073 _dbus_transport_get_max_message_size (DBusTransport  *transport)
1074 {
1075   return _dbus_message_loader_get_max_message_size (transport->loader);
1076 }
1077
1078 /**
1079  * See dbus_connection_get_max_message_unix_fds().
1080  *
1081  * @param transport the transport
1082  * @returns max message unix fds
1083  */
1084 long
1085 _dbus_transport_get_max_message_unix_fds (DBusTransport  *transport)
1086 {
1087   return _dbus_message_loader_get_max_message_unix_fds (transport->loader);
1088 }
1089
1090 /**
1091  * See dbus_connection_set_max_received_size().
1092  *
1093  * @param transport the transport
1094  * @param size the max size of all incoming messages
1095  */
1096 void
1097 _dbus_transport_set_max_received_size (DBusTransport  *transport,
1098                                        long            size)
1099 {
1100   transport->max_live_messages_size = size;
1101   _dbus_counter_set_notify (transport->live_messages,
1102                             transport->max_live_messages_size,
1103                             transport->max_live_messages_unix_fds,
1104                             live_messages_notify,
1105                             transport);
1106 }
1107
1108 /**
1109  * See dbus_connection_set_max_received_unix_fds().
1110  *
1111  * @param transport the transport
1112  * @param n the max unix fds of all incoming messages
1113  */
1114 void
1115 _dbus_transport_set_max_received_unix_fds (DBusTransport  *transport,
1116                                            long            n)
1117 {
1118   transport->max_live_messages_unix_fds = n;
1119   _dbus_counter_set_notify (transport->live_messages,
1120                             transport->max_live_messages_size,
1121                             transport->max_live_messages_unix_fds,
1122                             live_messages_notify,
1123                             transport);
1124 }
1125
1126 /**
1127  * See dbus_connection_get_max_received_size().
1128  *
1129  * @param transport the transport
1130  * @returns max bytes for all live messages
1131  */
1132 long
1133 _dbus_transport_get_max_received_size (DBusTransport  *transport)
1134 {
1135   return transport->max_live_messages_size;
1136 }
1137
1138 /**
1139  * See dbus_connection_set_max_received_unix_fds().
1140  *
1141  * @param transport the transport
1142  * @returns max unix fds for all live messages
1143  */
1144 long
1145 _dbus_transport_get_max_received_unix_fds (DBusTransport  *transport)
1146 {
1147   return transport->max_live_messages_unix_fds;
1148 }
1149
1150 /**
1151  * See dbus_connection_get_unix_user().
1152  *
1153  * @param transport the transport
1154  * @param uid return location for the user ID
1155  * @returns #TRUE if uid is filled in with a valid user ID
1156  */
1157 dbus_bool_t
1158 _dbus_transport_get_unix_user (DBusTransport *transport,
1159                                unsigned long *uid)
1160 {
1161   DBusCredentials *auth_identity;
1162
1163   *uid = _DBUS_INT32_MAX; /* better than some root or system user in
1164                            * case of bugs in the caller. Caller should
1165                            * never use this value on purpose, however.
1166                            */
1167   
1168   if (!transport->authenticated)
1169     return FALSE;
1170   
1171   auth_identity = _dbus_auth_get_identity (transport->auth);
1172
1173   if (_dbus_credentials_include (auth_identity,
1174                                  DBUS_CREDENTIAL_UNIX_USER_ID))
1175     {
1176       *uid = _dbus_credentials_get_unix_uid (auth_identity);
1177       return TRUE;
1178     }
1179   else
1180     return FALSE;
1181 }
1182
1183 /**
1184  * See dbus_connection_get_unix_process_id().
1185  *
1186  * @param transport the transport
1187  * @param pid return location for the process ID
1188  * @returns #TRUE if uid is filled in with a valid process ID
1189  */
1190 dbus_bool_t
1191 _dbus_transport_get_unix_process_id (DBusTransport *transport,
1192                                      unsigned long *pid)
1193 {
1194   DBusCredentials *auth_identity;
1195
1196   *pid = DBUS_PID_UNSET; /* Caller should never use this value on purpose,
1197                           * but we set it to a safe number, INT_MAX,
1198                           * just to root out possible bugs in bad callers.
1199                           */
1200   
1201   if (!transport->authenticated)
1202     return FALSE;
1203   
1204   auth_identity = _dbus_auth_get_identity (transport->auth);
1205
1206   if (_dbus_credentials_include (auth_identity,
1207                                  DBUS_CREDENTIAL_UNIX_PROCESS_ID))
1208     {
1209       *pid = _dbus_credentials_get_pid (auth_identity);
1210       return TRUE;
1211     }
1212   else
1213     return FALSE;
1214 }
1215
1216 /**
1217  * See dbus_connection_get_adt_audit_session_data().
1218  *
1219  * @param transport the transport
1220  * @param data return location for the ADT audit data 
1221  * @param data_size return length of audit data
1222  * @returns #TRUE if audit data is filled in with a valid ucred
1223  */
1224 dbus_bool_t
1225 _dbus_transport_get_adt_audit_session_data (DBusTransport      *transport,
1226                                             void              **data,
1227                                             int                *data_size)
1228 {
1229   DBusCredentials *auth_identity;
1230
1231   *data = NULL;
1232   *data_size = 0;
1233   
1234   if (!transport->authenticated)
1235     return FALSE;
1236   
1237   auth_identity = _dbus_auth_get_identity (transport->auth);
1238
1239   if (_dbus_credentials_include (auth_identity,
1240                                  DBUS_CREDENTIAL_ADT_AUDIT_DATA_ID))
1241     {
1242       *data = (void *) _dbus_credentials_get_adt_audit_data (auth_identity);
1243       *data_size = _dbus_credentials_get_adt_audit_data_size (auth_identity);
1244       return TRUE;
1245     }
1246   else
1247     return FALSE;
1248 }
1249
1250 /**
1251  * See dbus_connection_set_unix_user_function().
1252  *
1253  * @param transport the transport
1254  * @param function the predicate
1255  * @param data data to pass to the predicate
1256  * @param free_data_function function to free the data
1257  * @param old_data the old user data to be freed
1258  * @param old_free_data_function old free data function to free it with
1259  */
1260 inline void
1261 _dbus_transport_set_unix_user_function (DBusTransport             *transport,
1262                                         DBusAllowUnixUserFunction  function,
1263                                         void                      *data,
1264                                         DBusFreeFunction           free_data_function,
1265                                         void                     **old_data,
1266                                         DBusFreeFunction          *old_free_data_function)
1267 {
1268   if (transport->is_server)
1269     _dbus_authorization_set_unix_authorization_callback (transport->authorization, function,
1270         data, free_data_function, old_data, old_free_data_function);
1271 }
1272
1273 /**
1274  * See dbus_connection_get_windows_user().
1275  *
1276  * @param transport the transport
1277  * @param windows_sid_p return location for the user ID
1278  * @returns #TRUE if user is available; the returned value may still be #NULL if no memory to copy it
1279  */
1280 dbus_bool_t
1281 _dbus_transport_get_windows_user (DBusTransport              *transport,
1282                                   char                      **windows_sid_p)
1283 {
1284   DBusCredentials *auth_identity;
1285
1286   *windows_sid_p = NULL;
1287   
1288   if (!transport->authenticated)
1289     return FALSE;
1290   
1291   auth_identity = _dbus_auth_get_identity (transport->auth);
1292
1293   if (_dbus_credentials_include (auth_identity,
1294                                  DBUS_CREDENTIAL_WINDOWS_SID))
1295     {
1296       /* If no memory, we are supposed to return TRUE and set NULL */
1297       *windows_sid_p = _dbus_strdup (_dbus_credentials_get_windows_sid (auth_identity));
1298
1299       return TRUE;
1300     }
1301   else
1302     return FALSE;
1303 }
1304
1305 /**
1306  * See dbus_connection_set_windows_user_function().
1307  *
1308  * @param transport the transport
1309  * @param function the predicate
1310  * @param data data to pass to the predicate
1311  * @param free_data_function function to free the data
1312  * @param old_data the old user data to be freed
1313  * @param old_free_data_function old free data function to free it with
1314  */
1315
1316 inline void
1317 _dbus_transport_set_windows_user_function (DBusTransport              *transport,
1318                                            DBusAllowWindowsUserFunction   function,
1319                                            void                       *data,
1320                                            DBusFreeFunction            free_data_function,
1321                                            void                      **old_data,
1322                                            DBusFreeFunction           *old_free_data_function)
1323 {
1324   if (transport->is_server)
1325     _dbus_authorization_set_windows_authorization_callback (transport->authorization, function,
1326         data, free_data_function, old_data, old_free_data_function);
1327 }
1328
1329 /**
1330  * Sets the SASL authentication mechanisms supported by this transport.
1331  *
1332  * @param transport the transport
1333  * @param mechanisms the #NULL-terminated array of mechanisms
1334  *
1335  * @returns #FALSE if no memory
1336  */
1337 dbus_bool_t
1338 _dbus_transport_set_auth_mechanisms (DBusTransport  *transport,
1339                                      const char    **mechanisms)
1340 {
1341   return _dbus_auth_set_mechanisms (transport->auth, mechanisms);
1342 }
1343
1344 /**
1345  * See dbus_connection_set_allow_anonymous()
1346  *
1347  * @param transport the transport
1348  * @param value #TRUE to allow anonymous connection
1349  */
1350 inline void
1351 _dbus_transport_set_allow_anonymous (DBusTransport              *transport,
1352                                      dbus_bool_t                 value)
1353 {
1354   if (transport->is_server)
1355     _dbus_authorization_set_allow_anonymous (transport->authorization, value);
1356 }
1357
1358 #ifdef DBUS_ENABLE_STATS
1359 void
1360 _dbus_transport_get_stats (DBusTransport  *transport,
1361                            dbus_uint32_t  *queue_bytes,
1362                            dbus_uint32_t  *queue_fds,
1363                            dbus_uint32_t  *peak_queue_bytes,
1364                            dbus_uint32_t  *peak_queue_fds)
1365 {
1366   if (queue_bytes != NULL)
1367     *queue_bytes = _dbus_counter_get_size_value (transport->live_messages);
1368
1369   if (queue_fds != NULL)
1370     *queue_fds = _dbus_counter_get_unix_fd_value (transport->live_messages);
1371
1372   if (peak_queue_bytes != NULL)
1373     *peak_queue_bytes = _dbus_counter_get_peak_size_value (transport->live_messages);
1374
1375   if (peak_queue_fds != NULL)
1376     *peak_queue_fds = _dbus_counter_get_peak_unix_fd_value (transport->live_messages);
1377 }
1378 #endif /* DBUS_ENABLE_STATS */
1379
1380 /** @} */