2003-02-02 Anders Carlsson <andersca@codefactory.se>
[platform/upstream/dbus.git] / dbus / dbus-transport.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
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 1.2
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #include "dbus-transport-protected.h"
25 #include "dbus-transport-unix.h"
26 #include "dbus-connection-internal.h"
27 #include "dbus-watch.h"
28 #include "dbus-auth.h"
29 #include "dbus-address.h"
30 #ifdef DBUS_BUILD_TESTS
31 #include "dbus-transport-debug.h"
32 #endif
33
34 /**
35  * @defgroup DBusTransport DBusTransport object
36  * @ingroup  DBusInternals
37  * @brief "Backend" for a DBusConnection.
38  *
39  * Types and functions related to DBusTransport.  A transport is an
40  * abstraction that can send and receive data via various kinds of
41  * network connections or other IPC mechanisms.
42  * 
43  * @{
44  */
45
46 /**
47  * @typedef DBusTransport
48  *
49  * Opaque object representing a way message stream.
50  * DBusTransport abstracts various kinds of actual
51  * transport mechanism, such as different network protocols,
52  * or encryption schemes.
53  */
54
55 /**
56  * Refs a transport and associated connection for reentrancy.
57  *
58  * @todo this macro reflects a design mistake, which is that the
59  * transport has a pointer to its connection. Ownership should move in
60  * only one direction; the connection should push/pull from the
61  * transport, rather than vice versa. Then the connection would take
62  * care of referencing itself when needed.
63  */
64 #define DBUS_TRANSPORT_HOLD_REF(t) \
65   _dbus_transport_ref (t); if ((t)->connection) dbus_connection_ref ((t)->connection)
66
67 /**
68  * Inverse of DBUS_TRANSPORT_HOLD_REF().
69  */
70 #define DBUS_TRANSPORT_RELEASE_REF(t) \
71   if ((t)->connection) dbus_connection_unref ((t)->connection); _dbus_transport_unref (t)
72
73 static void
74 live_messages_size_notify (DBusCounter *counter,
75                            void        *user_data)
76 {
77   DBusTransport *transport = user_data;
78
79   DBUS_TRANSPORT_HOLD_REF (transport);
80
81 #if 0
82   _dbus_verbose ("Counter value is now %d\n",
83                  (int) _dbus_counter_get_value (counter));
84 #endif
85   
86   /* disable or re-enable the read watch for the transport if
87    * required.
88    */
89   if (* transport->vtable->live_messages_changed)
90     (* transport->vtable->live_messages_changed) (transport);
91
92   DBUS_TRANSPORT_RELEASE_REF (transport);
93 }
94
95 /**
96  * Initializes the base class members of DBusTransport.
97  * Chained up to by subclasses in their constructor.
98  *
99  * @param transport the transport being created.
100  * @param vtable the subclass vtable.
101  * @param server #TRUE if this transport is on the server side of a connection
102  * @returns #TRUE on success.
103  */
104 dbus_bool_t
105 _dbus_transport_init_base (DBusTransport             *transport,
106                            const DBusTransportVTable *vtable,
107                            dbus_bool_t                server)
108 {
109   DBusMessageLoader *loader;
110   DBusAuth *auth;
111   DBusCounter *counter;
112   
113   loader = _dbus_message_loader_new ();
114   if (loader == NULL)
115     return FALSE;
116   
117   if (server)
118     auth = _dbus_auth_server_new ();
119   else
120     auth = _dbus_auth_client_new ();
121   if (auth == NULL)
122     {
123       _dbus_message_loader_unref (loader);
124       return FALSE;
125     }
126
127   counter = _dbus_counter_new ();
128   if (counter == NULL)
129     {
130       _dbus_auth_unref (auth);
131       _dbus_message_loader_unref (loader);
132       return FALSE;
133     }
134   
135   transport->refcount = 1;
136   transport->vtable = vtable;
137   transport->loader = loader;
138   transport->auth = auth;
139   transport->live_messages_size = counter;
140   transport->authenticated = FALSE;
141   transport->messages_need_sending = FALSE;
142   transport->disconnected = FALSE;
143   transport->send_credentials_pending = !server;
144   transport->receive_credentials_pending = server;
145   transport->is_server = server;
146
147   /* Try to default to something that won't totally hose the system,
148    * but doesn't impose too much of a limitation.
149    */
150   transport->max_live_messages_size = _DBUS_ONE_MEGABYTE * 63;
151   
152   transport->credentials.pid = -1;
153   transport->credentials.uid = -1;
154   transport->credentials.gid = -1;
155
156   _dbus_counter_set_notify (transport->live_messages_size,
157                             transport->max_live_messages_size,
158                             live_messages_size_notify,
159                             transport);
160   
161   return TRUE;
162 }
163
164 /**
165  * Finalizes base class members of DBusTransport.
166  * Chained up to from subclass finalizers.
167  *
168  * @param transport the transport.
169  */
170 void
171 _dbus_transport_finalize_base (DBusTransport *transport)
172 {
173   if (!transport->disconnected)
174     _dbus_transport_disconnect (transport);
175   
176   _dbus_message_loader_unref (transport->loader);
177   _dbus_auth_unref (transport->auth);
178   _dbus_counter_set_notify (transport->live_messages_size,
179                             0, NULL, NULL);
180   _dbus_counter_unref (transport->live_messages_size);
181 }
182
183 /**
184  * Opens a new transport for the given address.  (This opens a
185  * client-side-of-the-connection transport.)
186  *
187  * @todo error messages on bad address could really be better.
188  * DBusResultCode is a bit limiting here.
189  * 
190  * @param address the address.
191  * @param result location to store reason for failure.
192  * @returns new transport of #NULL on failure.
193  */
194 DBusTransport*
195 _dbus_transport_open (const char     *address,
196                       DBusResultCode *result)
197 {
198   DBusTransport *transport;
199   DBusAddressEntry **entries;
200   int len, i;
201   
202   if (!dbus_parse_address (address, &entries, &len, result))
203     return NULL;
204
205   transport = NULL;
206   
207   for (i = 0; i < len; i++)
208     {
209       const char *method = dbus_address_entry_get_method (entries[i]);
210
211       if (strcmp (method, "unix") == 0)
212         {
213           const char *path = dbus_address_entry_get_value (entries[i], "path");
214
215           if (path == NULL)
216             goto bad_address;
217
218           transport = _dbus_transport_new_for_domain_socket (path, FALSE, result);
219         }
220 #ifdef DBUS_BUILD_TESTS
221       else if (strcmp (method, "debug") == 0)
222         {
223           const char *name = dbus_address_entry_get_value (entries[i], "name");
224
225           if (name == NULL)
226             goto bad_address;
227
228           transport = _dbus_transport_debug_client_new (name, result);
229         }
230 #endif      
231       else
232         goto bad_address;
233
234       if (transport)
235         break;    
236     }
237   
238   dbus_address_entries_free (entries);
239   return transport;
240
241  bad_address:
242   dbus_address_entries_free (entries);
243   dbus_set_result (result, DBUS_RESULT_BAD_ADDRESS);
244
245   return NULL;
246 }
247
248 /**
249  * Increments the reference count for the transport.
250  *
251  * @param transport the transport.
252  */
253 void
254 _dbus_transport_ref (DBusTransport *transport)
255 {
256   transport->refcount += 1;
257 }
258
259 /**
260  * Decrements the reference count for the transport.
261  * Disconnects and finalizes the transport if
262  * the reference count reaches zero.
263  *
264  * @param transport the transport.
265  */
266 void
267 _dbus_transport_unref (DBusTransport *transport)
268 {
269   _dbus_assert (transport != NULL);
270   _dbus_assert (transport->refcount > 0);
271
272   transport->refcount -= 1;
273   if (transport->refcount == 0)
274     {
275       _dbus_assert (transport->vtable->finalize != NULL);
276       
277       (* transport->vtable->finalize) (transport);
278     }
279 }
280
281 /**
282  * Closes our end of the connection to a remote application. Further
283  * attempts to use this transport will fail. Only the first call to
284  * _dbus_transport_disconnect() will have an effect.
285  *
286  * @param transport the transport.
287  * 
288  */
289 void
290 _dbus_transport_disconnect (DBusTransport *transport)
291 {
292   _dbus_assert (transport->vtable->disconnect != NULL);
293
294   if (transport->disconnected)
295     return;
296
297   DBUS_TRANSPORT_HOLD_REF (transport);
298   (* transport->vtable->disconnect) (transport);
299   
300   transport->disconnected = TRUE;
301
302   _dbus_connection_notify_disconnected (transport->connection);
303   
304   DBUS_TRANSPORT_RELEASE_REF (transport);
305 }
306
307 /**
308  * Returns #TRUE if the transport has not been disconnected.
309  * Disconnection can result from _dbus_transport_disconnect()
310  * or because the server drops its end of the connection.
311  *
312  * @param transport the transport.
313  * @returns whether we're connected
314  */
315 dbus_bool_t
316 _dbus_transport_get_is_connected (DBusTransport *transport)
317 {
318   return !transport->disconnected;
319 }
320
321 /**
322  * Returns #TRUE if we have been authenticated.  Will return #TRUE
323  * even if the transport is disconnected.
324  *
325  * @param transport the transport
326  * @returns whether we're authenticated
327  */
328 dbus_bool_t
329 _dbus_transport_get_is_authenticated (DBusTransport *transport)
330 {  
331   if (transport->authenticated)
332     return TRUE;
333   else
334     {
335       if (transport->disconnected)
336         return FALSE;
337       
338       transport->authenticated =
339         (!(transport->send_credentials_pending ||
340            transport->receive_credentials_pending)) &&
341         _dbus_auth_do_work (transport->auth) == DBUS_AUTH_STATE_AUTHENTICATED;
342
343       /* If we've authenticated as some identity, check that the auth
344        * identity is the same as our own identity.  In the future, we
345        * may have API allowing applications to specify how this is
346        * done, for example they may allow connection as any identity,
347        * but then impose restrictions on certain identities.
348        * Or they may give certain identities extra privileges.
349        */
350       
351       if (transport->authenticated && transport->is_server)
352         {
353           DBusCredentials auth_identity;
354           DBusCredentials our_identity;
355
356           _dbus_credentials_from_current_process (&our_identity);
357           _dbus_auth_get_identity (transport->auth, &auth_identity);
358           
359           if (!_dbus_credentials_match (&our_identity,
360                                         &auth_identity))
361             {
362               _dbus_verbose ("Client authorized as UID %d but our UID is %d, disconnecting\n",
363                              auth_identity.uid, our_identity.uid);
364               _dbus_transport_disconnect (transport);
365               return FALSE;
366             }
367           else
368             {
369               _dbus_verbose ("Client authorized as UID %d matching our UID %d\n",
370                              auth_identity.uid, our_identity.uid);
371             }
372         }
373       
374       return transport->authenticated;
375     }
376 }
377
378 /**
379  * Handles a watch by reading data, writing data, or disconnecting
380  * the transport, as appropriate for the given condition.
381  *
382  * @param transport the transport.
383  * @param watch the watch.
384  * @param condition the current state of the watched file descriptor.
385  */
386 void
387 _dbus_transport_handle_watch (DBusTransport           *transport,
388                               DBusWatch               *watch,
389                               unsigned int             condition)
390 {
391   _dbus_assert (transport->vtable->handle_watch != NULL);
392
393   if (transport->disconnected)
394     return;
395
396   if (dbus_watch_get_fd (watch) < 0)
397     {
398       _dbus_warn ("Tried to handle an invalidated watch; this watch should have been removed\n");
399       return;
400     }
401   
402   _dbus_watch_sanitize_condition (watch, &condition);
403
404   DBUS_TRANSPORT_HOLD_REF (transport);
405   _dbus_watch_ref (watch);
406   (* transport->vtable->handle_watch) (transport, watch, condition);
407   _dbus_watch_unref (watch);
408   DBUS_TRANSPORT_RELEASE_REF (transport);
409 }
410
411 /**
412  * Sets the connection using this transport. Allows the transport
413  * to add watches to the connection, queue incoming messages,
414  * and pull outgoing messages.
415  *
416  * @param transport the transport.
417  * @param connection the connection.
418  */
419 void
420 _dbus_transport_set_connection (DBusTransport  *transport,
421                                 DBusConnection *connection)
422 {
423   _dbus_assert (transport->vtable->connection_set != NULL);
424   _dbus_assert (transport->connection == NULL);
425   
426   transport->connection = connection;
427
428   DBUS_TRANSPORT_HOLD_REF (transport);
429   (* transport->vtable->connection_set) (transport);
430   DBUS_TRANSPORT_RELEASE_REF (transport);
431 }
432
433 /**
434  * Notifies the transport when the outgoing message queue goes from
435  * empty to non-empty or vice versa. Typically causes the transport to
436  * add or remove its DBUS_WATCH_WRITABLE watch.
437  *
438  * @param transport the transport.
439  * @param queue_length the length of the outgoing message queue.
440  *
441  */
442 void
443 _dbus_transport_messages_pending (DBusTransport  *transport,
444                                   int             queue_length)
445 {
446   _dbus_assert (transport->vtable->messages_pending != NULL);
447
448   if (transport->disconnected)
449     return;
450
451   transport->messages_need_sending = queue_length > 0;
452
453   DBUS_TRANSPORT_HOLD_REF (transport);
454   (* transport->vtable->messages_pending) (transport,
455                                            queue_length);
456   DBUS_TRANSPORT_RELEASE_REF (transport);
457 }
458
459 /**
460  * Performs a single poll()/select() on the transport's file
461  * descriptors and then reads/writes data as appropriate,
462  * queueing incoming messages and sending outgoing messages.
463  * This is the backend for _dbus_connection_do_iteration().
464  * See _dbus_connection_do_iteration() for full details.
465  *
466  * @param transport the transport.
467  * @param flags indicates whether to read or write, and whether to block.
468  * @param timeout_milliseconds if blocking, timeout or -1 for no timeout.
469  */
470 void
471 _dbus_transport_do_iteration (DBusTransport  *transport,
472                               unsigned int    flags,
473                               int             timeout_milliseconds)
474 {
475   _dbus_assert (transport->vtable->do_iteration != NULL);
476
477   if ((flags & (DBUS_ITERATION_DO_WRITING |
478                 DBUS_ITERATION_DO_READING)) == 0)
479     return; /* Nothing to do */
480
481   if (transport->disconnected)
482     return;
483
484   DBUS_TRANSPORT_HOLD_REF (transport);
485   (* transport->vtable->do_iteration) (transport, flags,
486                                        timeout_milliseconds);
487   DBUS_TRANSPORT_RELEASE_REF (transport);
488 }
489
490 /**
491  * See dbus_connection_set_max_message_size().
492  *
493  * @param transport the transport
494  * @param size the max size of a single message
495  */
496 void
497 _dbus_transport_set_max_message_size (DBusTransport  *transport,
498                                       long            size)
499 {
500   _dbus_message_loader_set_max_message_size (transport->loader, size);
501 }
502
503 /**
504  * See dbus_connection_get_max_message_size().
505  *
506  * @param transport the transport
507  * @returns max message size
508  */
509 long
510 _dbus_transport_get_max_message_size (DBusTransport  *transport)
511 {
512   return _dbus_message_loader_get_max_message_size (transport->loader);
513 }
514
515 /**
516  * See dbus_connection_set_max_live_messages_size().
517  *
518  * @param transport the transport
519  * @param size the max size of all incoming messages
520  */
521 void
522 _dbus_transport_set_max_live_messages_size (DBusTransport  *transport,
523                                             long            size)
524 {
525   transport->max_live_messages_size = size;
526   _dbus_counter_set_notify (transport->live_messages_size,
527                             transport->max_live_messages_size,
528                             live_messages_size_notify,
529                             transport);
530 }
531
532
533 /**
534  * See dbus_connection_get_max_live_messages_size().
535  *
536  * @param transport the transport
537  * @returns max bytes for all live messages
538  */
539 long
540 _dbus_transport_get_max_live_messages_size (DBusTransport  *transport)
541 {
542   return transport->max_live_messages_size;
543 }
544
545 /** @} */