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