2002-11-24 Havoc Pennington <hp@pobox.com>
[platform/upstream/dbus.git] / dbus / dbus-connection.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-connection.c DBusConnection object
3  *
4  * Copyright (C) 2002  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-connection.h"
25 #include "dbus-list.h"
26 #include "dbus-transport.h"
27 #include "dbus-watch.h"
28 #include "dbus-connection-internal.h"
29 #include "dbus-list.h"
30
31 /**
32  * @defgroup DBusConnection DBusConnection
33  * @ingroup  DBus
34  * @brief Connection to another application
35  *
36  * A DBusConnection represents a connection to another
37  * application. Messages can be sent and received via this connection.
38  *
39  * The connection maintains a queue of incoming messages and a queue
40  * of outgoing messages. dbus_connection_pop_message() and friends
41  * can be used to read incoming messages from the queue.
42  * Outgoing messages are automatically discarded as they are
43  * written to the network.
44  *
45  * In brief a DBusConnection is a message queue associated with some
46  * message transport mechanism such as a socket.
47  * 
48  */
49
50 /**
51  * @defgroup DBusConnectionInternals DBusConnection implementation details
52  * @ingroup  DBusInternals
53  * @brief Implementation details of DBusConnection
54  *
55  * @{
56  */
57
58 /**
59  * Implementation details of DBusConnection. All fields are private.
60  */
61 struct DBusConnection
62 {
63   int refcount; /**< Reference count. */
64
65   DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
66   DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
67
68   int n_outgoing;              /**< Length of outgoing queue. */
69   int n_incoming;              /**< Length of incoming queue. */
70   
71   DBusTransport *transport;    /**< Object that sends/receives messages over network. */
72   DBusWatchList *watches;      /**< Stores active watches. */
73   
74   DBusConnectionErrorFunction error_function; /**< Callback for errors. */
75   void *error_data;                           /**< Data for error callback. */
76   DBusFreeFunction error_free_data_function;  /**< Free function for error callback data. */
77 };
78
79 /**
80  * Adds a message to the incoming message queue, returning #FALSE
81  * if there's insufficient memory to queue the message.
82  *
83  * @param connection the connection.
84  * @param message the message to queue.
85  * @returns #TRUE on success.
86  */
87 dbus_bool_t
88 _dbus_connection_queue_received_message (DBusConnection *connection,
89                                          DBusMessage    *message)
90 {
91   if (!_dbus_list_append (&connection->incoming_messages,
92                           message))
93     return FALSE;
94
95   dbus_message_ref (message);
96   connection->n_incoming += 1;
97
98   return TRUE;
99 }
100
101 /**
102  * Checks whether there are messages in the outgoing message queue.
103  *
104  * @param connection the connection.
105  * @returns #TRUE if the outgoing queue is non-empty.
106  */
107 dbus_bool_t
108 _dbus_connection_have_messages_to_send (DBusConnection *connection)
109 {
110   return connection->outgoing_messages != NULL;
111 }
112
113 /**
114  * Gets the next outgoing message. The message remanins in the
115  * queue, and the caller does not own a reference to it.
116  *
117  * @param connection the connection.
118  * @returns the message to be sent.
119  */ 
120 DBusMessage*
121 _dbus_connection_get_message_to_send (DBusConnection *connection)
122 {
123   return _dbus_list_get_last (&connection->outgoing_messages);
124 }
125
126 /**
127  * Notifies the connection that a message has been sent, so the
128  * message can be removed from the outgoing queue.
129  *
130  * @param connection the connection.
131  * @param message the message that was sent.
132  */
133 void
134 _dbus_connection_message_sent (DBusConnection *connection,
135                                DBusMessage    *message)
136 {
137   _dbus_assert (message == _dbus_list_get_last (&connection->outgoing_messages));
138   _dbus_list_pop_last (&connection->outgoing_messages);
139   dbus_message_unref (message);
140   
141   connection->n_outgoing -= 1;
142   if (connection->n_outgoing == 0)
143     _dbus_transport_messages_pending (connection->transport,
144                                       connection->n_outgoing);  
145 }
146
147 /**
148  * Adds a watch using the connection's DBusAddWatchFunction if
149  * available. Otherwise records the watch to be added when said
150  * function is available. Also re-adds the watch if the
151  * DBusAddWatchFunction changes. May fail due to lack of memory.
152  *
153  * @param connection the connection.
154  * @param watch the watch to add.
155  * @returns #TRUE on success.
156  */
157 dbus_bool_t
158 _dbus_connection_add_watch (DBusConnection *connection,
159                             DBusWatch      *watch)
160 {
161   return _dbus_watch_list_add_watch (connection->watches,
162                                      watch);
163   
164   return TRUE;
165 }
166
167 /**
168  * Removes a watch using the connection's DBusRemoveWatchFunction
169  * if available. It's an error to call this function on a watch
170  * that was not previously added.
171  *
172  * @param connection the connection.
173  * @param watch the watch to remove.
174  */
175 void
176 _dbus_connection_remove_watch (DBusConnection *connection,
177                                DBusWatch      *watch)
178 {
179   _dbus_watch_list_remove_watch (connection->watches,
180                                  watch);
181 }
182
183 static void
184 handle_error (DBusConnection *connection,
185               DBusResultCode  result)
186 {
187   if (result != DBUS_RESULT_SUCCESS &&
188       connection->error_function != NULL)
189     {
190       dbus_connection_ref (connection);
191       (* connection->error_function) (connection, result,
192                                       connection->error_data);
193       dbus_connection_unref (connection);
194     }
195 }
196
197 static void
198 set_result_handled (DBusConnection *connection,
199                     DBusResultCode *result_address,
200                     DBusResultCode  result)
201 {
202   dbus_set_result (result_address, result);
203   handle_error (connection, result);
204 }
205
206 /**
207  * Reports a transport error to the connection. Typically
208  * results in an application error callback being invoked.
209  *
210  * @param connection the connection.
211  * @param result_code the error code.
212  */
213 void
214 _dbus_connection_transport_error (DBusConnection *connection,
215                                   DBusResultCode  result_code)
216 {
217   handle_error (connection, result_code);
218 }
219
220 /**
221  * Queues incoming messages and sends outgoing messages for this
222  * connection, optionally blocking in the process. Each call to
223  * _dbus_connection_do_iteration() will call select() or poll() one
224  * time and then read or write data if possible.
225  *
226  * The purpose of this function is to be able to flush outgoing
227  * messages or queue up incoming messages without returning
228  * control to the application and causing reentrancy weirdness.
229  *
230  * The flags parameter allows you to specify whether to
231  * read incoming messages, write outgoing messages, or both,
232  * and whether to block if no immediate action is possible.
233  *
234  * The timeout_milliseconds parameter does nothing unless the
235  * iteration is blocking.
236  *
237  * If there are no outgoing messages and DBUS_ITERATION_DO_READING
238  * wasn't specified, then it's impossible to block, even if
239  * you specify DBUS_ITERATION_BLOCK; in that case the function
240  * returns immediately.
241  * 
242  * @param connection the connection.
243  * @param flags iteration flags.
244  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
245  */
246 void
247 _dbus_connection_do_iteration (DBusConnection *connection,
248                                unsigned int    flags,
249                                int             timeout_milliseconds)
250 {
251   if (connection->n_outgoing == 0)
252     flags &= ~DBUS_ITERATION_DO_WRITING;
253   
254   _dbus_transport_do_iteration (connection->transport,
255                                 flags, timeout_milliseconds);
256 }
257
258 /**
259  * Creates a new connection for the given transport.  A transport
260  * represents a message stream that uses some concrete mechanism, such
261  * as UNIX domain sockets. May return #NULL if insufficient
262  * memory exists to create the connection.
263  *
264  * @param transport the transport.
265  * @returns the new connection, or #NULL on failure.
266  */
267 DBusConnection*
268 _dbus_connection_new_for_transport (DBusTransport *transport)
269 {
270   DBusConnection *connection;
271   DBusWatchList *watch_list;
272   
273   watch_list = NULL;
274   connection = NULL;
275   
276   watch_list = _dbus_watch_list_new ();
277   if (watch_list == NULL)
278     goto error;
279   
280   connection = dbus_new0 (DBusConnection, 1);
281   if (connection == NULL)
282     goto error;
283   
284   connection->refcount = 1;
285   connection->transport = transport;
286   connection->watches = watch_list;
287
288   _dbus_transport_ref (transport);
289   _dbus_transport_set_connection (transport, connection);
290   
291   return connection;
292   
293  error:
294
295   _dbus_assert (connection == NULL);  
296
297   if (watch_list)
298     _dbus_watch_list_free (watch_list);
299   
300   return NULL;
301 }
302
303 /** @} */
304
305 /**
306  * @addtogroup DBusConnection
307  *
308  * @{
309  */
310
311 /**
312  * Opens a new connection to a remote address.
313  *
314  * @todo specify what the address parameter is. Right now
315  * it's just the name of a UNIX domain socket. It should be
316  * something more complex that encodes which transport to use.
317  *
318  * If the open fails, the function returns #NULL, and provides
319  * a reason for the failure in the result parameter. Pass
320  * #NULL for the result parameter if you aren't interested
321  * in the reason for failure.
322  * 
323  * @param address the address.
324  * @param result address where a result code can be returned.
325  * @returns new connection, or #NULL on failure.
326  */
327 DBusConnection*
328 dbus_connection_open (const char     *address,
329                       DBusResultCode *result)
330 {
331   DBusConnection *connection;
332   DBusTransport *transport;
333   
334   transport = _dbus_transport_open (address, result);
335   if (transport == NULL)
336     return NULL;
337   
338   connection = _dbus_connection_new_for_transport (transport);
339
340   _dbus_transport_unref (transport);
341   
342   if (connection == NULL)
343     {
344       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
345       return NULL;
346     }
347   
348   return connection;
349 }
350
351 /**
352  * Increments the reference count of a DBusConnection.
353  *
354  * @param connection the connection.
355  */
356 void
357 dbus_connection_ref (DBusConnection *connection)
358 {
359   connection->refcount += 1;
360 }
361
362 /**
363  * Decrements the reference count of a DBusConnection, and finalizes
364  * it if the count reaches zero.  If a connection is still connected
365  * when it's finalized, it will be disconnected (that is, associated
366  * file handles will be closed).
367  *
368  * @param connection the connection.
369  */
370 void
371 dbus_connection_unref (DBusConnection *connection)
372 {
373   _dbus_assert (connection != NULL);
374   _dbus_assert (connection->refcount > 0);
375   
376   connection->refcount -= 1;
377   if (connection->refcount == 0)
378     {
379       /* free error data as a side effect */
380       dbus_connection_set_error_function (connection,
381                                           NULL, NULL, NULL);
382
383       _dbus_watch_list_free (connection->watches);
384       
385       _dbus_list_foreach (&connection->outgoing_messages,
386                           (DBusForeachFunction) dbus_message_unref,
387                           NULL);
388       _dbus_list_clear (&connection->outgoing_messages);
389
390       _dbus_list_foreach (&connection->incoming_messages,
391                           (DBusForeachFunction) dbus_message_unref,
392                           NULL);
393       _dbus_list_clear (&connection->incoming_messages);
394       
395       _dbus_transport_unref (connection->transport);
396       
397       dbus_free (connection);
398     }
399 }
400
401 /**
402  * Closes the connection, so no further data can be sent or received.
403  * Any further attempts to send data will result in errors.  This
404  * function does not affect the connection's reference count.  It's
405  * safe to disconnect a connection more than once; all calls after the
406  * first do nothing. It's impossible to "reconnect" a connection, a
407  * new connection must be created.
408  *
409  * @param connection the connection.
410  */
411 void
412 dbus_connection_disconnect (DBusConnection *connection)
413 {
414   _dbus_transport_disconnect (connection->transport);
415 }
416
417 /**
418  * Gets whether the connection is currently connected.  All
419  * connections are connected when they are opened.  A connection may
420  * become disconnected when the remote application closes its end, or
421  * exits; a connection may also be disconnected with
422  * dbus_connection_disconnect().
423  *
424  * @param connection the connection.
425  * @returns #TRUE if the connection is still alive.
426  */
427 dbus_bool_t
428 dbus_connection_get_is_connected (DBusConnection *connection)
429 {
430   return _dbus_transport_get_is_connected (connection->transport);
431 }
432
433 /**
434  * Adds a message to the outgoing message queue. Does not block to
435  * write the message to the network; that happens asynchronously. to
436  * force the message to be written, call dbus_connection_flush().
437  *
438  * If the function fails, it returns #FALSE and returns the
439  * reason for failure via the result parameter.
440  * The result parameter can be #NULL if you aren't interested
441  * in the reason for the failure.
442  * 
443  * @param connection the connection.
444  * @param message the message to write.
445  * @param result address where result code can be placed.
446  * @returns #TRUE on success.
447  */
448 dbus_bool_t
449 dbus_connection_send_message (DBusConnection *connection,
450                               DBusMessage    *message,
451                               DBusResultCode *result)
452 {  
453   if (!_dbus_list_prepend (&connection->outgoing_messages,
454                            message))
455     {
456       set_result_handled (connection, result, DBUS_RESULT_NO_MEMORY);
457       return FALSE;
458     }
459
460   dbus_message_ref (message);
461   connection->n_outgoing += 1;
462
463   _dbus_message_lock (message);
464   
465   if (connection->n_outgoing == 1)
466     _dbus_transport_messages_pending (connection->transport,
467                                       connection->n_outgoing);
468 }
469
470 /**
471  * Blocks until the outgoing message queue is empty.
472  *
473  * @param connection the connection.
474  */
475 void
476 dbus_connection_flush (DBusConnection *connection)
477 {
478   while (connection->n_outgoing > 0)
479     _dbus_connection_do_iteration (connection,
480                                    DBUS_ITERATION_DO_WRITING |
481                                    DBUS_ITERATION_BLOCK,
482                                    -1);
483 }
484
485 /**
486  * Gets the number of messages in the incoming message queue.
487  *
488  * @param connection the connection.
489  * @returns the number of messages in the queue.
490  */
491 int
492 dbus_connection_get_n_messages (DBusConnection *connection)
493 {
494   return connection->n_incoming;
495 }
496
497 /**
498  * Returns the first-received message from the incoming message queue,
499  * leaving it in the queue. The caller does not own a reference to the
500  * returned message. If the queue is empty, returns #NULL.
501  *
502  * @param connection the connection.
503  * @returns next message in the incoming queue.
504  */
505 DBusMessage*
506 dbus_connection_peek_message  (DBusConnection *connection)
507 {
508   return _dbus_list_get_first (&connection->incoming_messages);
509 }
510
511 /**
512  * Returns the first-received message from the incoming message queue,
513  * removing it from the queue. The caller owns a reference to the
514  * returned message. If the queue is empty, returns #NULL.
515  *
516  * @param connection the connection.
517  * @returns next message in the incoming queue.
518  */
519 DBusMessage*
520 dbus_connection_pop_message (DBusConnection *connection)
521 {
522   if (connection->n_incoming > 0)
523     {
524       connection->n_incoming -= 1;
525       return _dbus_list_pop_first (&connection->incoming_messages);
526     }
527   else
528     return NULL;
529 }
530
531 /**
532  * Sets the error handler function for the connection.
533  * 
534  * @param connection the connection.
535  * @param error_function the error handler.
536  * @param data data to pass to the error handler.
537  * @param free_data_function function to be called to free the data.
538  */
539 void
540 dbus_connection_set_error_function  (DBusConnection              *connection,
541                                      DBusConnectionErrorFunction  error_function,
542                                      void                        *data,
543                                      DBusFreeFunction             free_data_function)
544 {
545   if (connection->error_free_data_function != NULL)
546     (* connection->error_free_data_function) (connection->error_data);
547
548   connection->error_function = error_function;
549   connection->error_data = data;
550   connection->error_free_data_function = free_data_function;
551 }
552
553 /**
554  * Sets the watch functions for the connection. These functions are
555  * responsible for making the application's main loop aware of file
556  * descriptors that need to be monitored for events, using select() or
557  * poll(). When using Qt, typically the DBusAddWatchFunction would
558  * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
559  * could call g_io_add_watch(), or could be used as part of a more
560  * elaborate GSource.
561  *
562  * The DBusWatch can be queried for the file descriptor to watch using
563  * dbus_watch_get_fd(), and for the events to watch for using
564  * dbus_watch_get_flags(). The flags returned by
565  * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
566  * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
567  * all watches implicitly include a watch for hangups, errors, and
568  * other exceptional conditions.
569  *
570  * Once a file descriptor becomes readable or writable, or an exception
571  * occurs, dbus_connection_handle_watch() should be called to
572  * notify the connection of the file descriptor's condition.
573  *
574  * dbus_connection_handle_watch() cannot be called during the
575  * DBusAddWatchFunction, as the connection will not be ready to handle
576  * that watch yet.
577  * 
578  * It is not allowed to reference a DBusWatch after it has been passed
579  * to remove_function.
580  * 
581  * @param connection the connection.
582  * @param add_function function to begin monitoring a new descriptor.
583  * @param remove_function function to stop monitoring a descriptor.
584  * @param data data to pass to add_function and remove_function.
585  * @param free_data_function function to be called to free the data.
586  */
587 void
588 dbus_connection_set_watch_functions (DBusConnection              *connection,
589                                      DBusAddWatchFunction         add_function,
590                                      DBusRemoveWatchFunction      remove_function,
591                                      void                        *data,
592                                      DBusFreeFunction             free_data_function)
593 {
594   /* ref connection for slightly better reentrancy */
595   dbus_connection_ref (connection);
596   
597   _dbus_watch_list_set_functions (connection->watches,
598                                   add_function, remove_function,
599                                   data, free_data_function);
600   
601   /* drop our paranoid refcount */
602   dbus_connection_unref (connection);
603 }
604
605 /**
606  * Called to notify the connection when a previously-added watch
607  * is ready for reading or writing, or has an exception such
608  * as a hangup.
609  *
610  * @param connection the connection.
611  * @param watch the watch.
612  * @param condition the current condition of the file descriptors being watched.
613  */
614 void
615 dbus_connection_handle_watch (DBusConnection              *connection,
616                               DBusWatch                   *watch,
617                               unsigned int                 condition)
618 {
619   _dbus_transport_handle_watch (connection->transport,
620                                 watch, condition);
621 }
622
623 /** @} */