2003-01-08 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 #include "dbus-hash.h"
31 #include "dbus-message-internal.h"
32 #include "dbus-threads.h"
33
34 /**
35  * @defgroup DBusConnection DBusConnection
36  * @ingroup  DBus
37  * @brief Connection to another application
38  *
39  * A DBusConnection represents a connection to another
40  * application. Messages can be sent and received via this connection.
41  *
42  * The connection maintains a queue of incoming messages and a queue
43  * of outgoing messages. dbus_connection_pop_message() and friends
44  * can be used to read incoming messages from the queue.
45  * Outgoing messages are automatically discarded as they are
46  * written to the network.
47  *
48  * In brief a DBusConnection is a message queue associated with some
49  * message transport mechanism such as a socket.
50  * 
51  */
52
53 /**
54  * @defgroup DBusConnectionInternals DBusConnection implementation details
55  * @ingroup  DBusInternals
56  * @brief Implementation details of DBusConnection
57  *
58  * @{
59  */
60
61 /** Opaque typedef for DBusDataSlot */
62 typedef struct DBusDataSlot DBusDataSlot;
63 /** DBusDataSlot is used to store application data on the connection */
64 struct DBusDataSlot
65 {
66   void *data;                      /**< The application data */
67   DBusFreeFunction free_data_func; /**< Free the application data */
68 };
69
70 /**
71  * Implementation details of DBusConnection. All fields are private.
72  */
73 struct DBusConnection
74 {
75   int refcount; /**< Reference count. */
76
77   DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
78   DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
79
80   int n_outgoing;              /**< Length of outgoing queue. */
81   int n_incoming;              /**< Length of incoming queue. */
82   
83   DBusTransport *transport;    /**< Object that sends/receives messages over network. */
84   DBusWatchList *watches;      /**< Stores active watches. */
85   
86   DBusConnectionErrorFunction error_function; /**< Callback for errors. */
87   void *error_data;                           /**< Data for error callback. */
88   DBusFreeFunction error_free_data_function;  /**< Free function for error callback data. */
89   DBusHashTable *handler_table; /**< Table of registered DBusMessageHandler */
90   DBusList *filter_list;        /**< List of filters. */
91   int filters_serial;           /**< Increments when the list of filters is changed. */
92   int handlers_serial;          /**< Increments when the handler table is changed. */
93   DBusDataSlot *data_slots;        /**< Data slots */
94   int           n_slots; /**< Slots allocated so far. */
95
96   int client_serial;            /**< Client serial. Increments each time a message is sent  */
97 };
98
99 static void _dbus_connection_free_data_slots (DBusConnection *connection);
100
101 /**
102  * Adds a message to the incoming message queue, returning #FALSE
103  * if there's insufficient memory to queue the message.
104  *
105  * @param connection the connection.
106  * @param message the message to queue.
107  * @returns #TRUE on success.
108  */
109 dbus_bool_t
110 _dbus_connection_queue_received_message (DBusConnection *connection,
111                                          DBusMessage    *message)
112 {
113   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
114   
115   if (!_dbus_list_append (&connection->incoming_messages,
116                           message))
117     return FALSE;
118   
119   dbus_message_ref (message);
120   connection->n_incoming += 1;
121
122   _dbus_verbose ("Incoming message %p added to queue, %d incoming\n",
123                  message, connection->n_incoming);
124   
125   return TRUE;
126 }
127
128 /**
129  * Checks whether there are messages in the outgoing message queue.
130  *
131  * @param connection the connection.
132  * @returns #TRUE if the outgoing queue is non-empty.
133  */
134 dbus_bool_t
135 _dbus_connection_have_messages_to_send (DBusConnection *connection)
136 {
137   return connection->outgoing_messages != NULL;
138 }
139
140 /**
141  * Gets the next outgoing message. The message remains in the
142  * queue, and the caller does not own a reference to it.
143  *
144  * @param connection the connection.
145  * @returns the message to be sent.
146  */ 
147 DBusMessage*
148 _dbus_connection_get_message_to_send (DBusConnection *connection)
149 {
150   return _dbus_list_get_last (&connection->outgoing_messages);
151 }
152
153 /**
154  * Notifies the connection that a message has been sent, so the
155  * message can be removed from the outgoing queue.
156  *
157  * @param connection the connection.
158  * @param message the message that was sent.
159  */
160 void
161 _dbus_connection_message_sent (DBusConnection *connection,
162                                DBusMessage    *message)
163 {
164   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
165   _dbus_assert (message == _dbus_list_get_last (&connection->outgoing_messages));
166   
167   _dbus_list_pop_last (&connection->outgoing_messages);
168   dbus_message_unref (message);
169   
170   connection->n_outgoing -= 1;
171
172   _dbus_verbose ("Message %p removed from outgoing queue, %d left to send\n",
173                  message, connection->n_outgoing);
174   
175   if (connection->n_outgoing == 0)
176     _dbus_transport_messages_pending (connection->transport,
177                                       connection->n_outgoing);  
178 }
179
180 /**
181  * Adds a watch using the connection's DBusAddWatchFunction if
182  * available. Otherwise records the watch to be added when said
183  * function is available. Also re-adds the watch if the
184  * DBusAddWatchFunction changes. May fail due to lack of memory.
185  *
186  * @param connection the connection.
187  * @param watch the watch to add.
188  * @returns #TRUE on success.
189  */
190 dbus_bool_t
191 _dbus_connection_add_watch (DBusConnection *connection,
192                             DBusWatch      *watch)
193 {
194   if (connection->watches) /* null during finalize */
195     return _dbus_watch_list_add_watch (connection->watches,
196                                        watch);
197   else
198     return FALSE;
199 }
200
201 /**
202  * Removes a watch using the connection's DBusRemoveWatchFunction
203  * if available. It's an error to call this function on a watch
204  * that was not previously added.
205  *
206  * @param connection the connection.
207  * @param watch the watch to remove.
208  */
209 void
210 _dbus_connection_remove_watch (DBusConnection *connection,
211                                DBusWatch      *watch)
212 {
213   if (connection->watches) /* null during finalize */
214     _dbus_watch_list_remove_watch (connection->watches,
215                                    watch);
216 }
217
218 static void
219 handle_error (DBusConnection *connection,
220               DBusResultCode  result)
221 {
222   if (result != DBUS_RESULT_SUCCESS &&
223       connection->error_function != NULL)
224     {
225       dbus_connection_ref (connection);
226       (* connection->error_function) (connection, result,
227                                       connection->error_data);
228       dbus_connection_unref (connection);
229     }
230 }
231
232 static void
233 set_result_handled (DBusConnection *connection,
234                     DBusResultCode *result_address,
235                     DBusResultCode  result)
236 {
237   dbus_set_result (result_address, result);
238   handle_error (connection, result);
239 }
240
241 /**
242  * Reports a transport error to the connection. Typically
243  * results in an application error callback being invoked.
244  *
245  * @param connection the connection.
246  * @param result_code the error code.
247  */
248 void
249 _dbus_connection_transport_error (DBusConnection *connection,
250                                   DBusResultCode  result_code)
251 {
252   handle_error (connection, result_code);
253 }
254
255 /**
256  * Queues incoming messages and sends outgoing messages for this
257  * connection, optionally blocking in the process. Each call to
258  * _dbus_connection_do_iteration() will call select() or poll() one
259  * time and then read or write data if possible.
260  *
261  * The purpose of this function is to be able to flush outgoing
262  * messages or queue up incoming messages without returning
263  * control to the application and causing reentrancy weirdness.
264  *
265  * The flags parameter allows you to specify whether to
266  * read incoming messages, write outgoing messages, or both,
267  * and whether to block if no immediate action is possible.
268  *
269  * The timeout_milliseconds parameter does nothing unless the
270  * iteration is blocking.
271  *
272  * If there are no outgoing messages and DBUS_ITERATION_DO_READING
273  * wasn't specified, then it's impossible to block, even if
274  * you specify DBUS_ITERATION_BLOCK; in that case the function
275  * returns immediately.
276  * 
277  * @param connection the connection.
278  * @param flags iteration flags.
279  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
280  */
281 void
282 _dbus_connection_do_iteration (DBusConnection *connection,
283                                unsigned int    flags,
284                                int             timeout_milliseconds)
285 {
286   if (connection->n_outgoing == 0)
287     flags &= ~DBUS_ITERATION_DO_WRITING;
288   
289   _dbus_transport_do_iteration (connection->transport,
290                                 flags, timeout_milliseconds);
291 }
292
293 /**
294  * Creates a new connection for the given transport.  A transport
295  * represents a message stream that uses some concrete mechanism, such
296  * as UNIX domain sockets. May return #NULL if insufficient
297  * memory exists to create the connection.
298  *
299  * @param transport the transport.
300  * @returns the new connection, or #NULL on failure.
301  */
302 DBusConnection*
303 _dbus_connection_new_for_transport (DBusTransport *transport)
304 {
305   DBusConnection *connection;
306   DBusWatchList *watch_list;
307   DBusHashTable *handler_table;
308   
309   watch_list = NULL;
310   connection = NULL;
311   handler_table = NULL;
312   
313   watch_list = _dbus_watch_list_new ();
314   if (watch_list == NULL)
315     goto error;
316
317   handler_table =
318     _dbus_hash_table_new (DBUS_HASH_STRING,
319                           dbus_free, NULL);
320   if (handler_table == NULL)
321     goto error;
322   
323   connection = dbus_new0 (DBusConnection, 1);
324   if (connection == NULL)
325     goto error;
326   
327   connection->refcount = 1;
328   connection->transport = transport;
329   connection->watches = watch_list;
330   connection->handler_table = handler_table;
331   connection->filter_list = NULL;
332
333   connection->data_slots = NULL;
334   connection->n_slots = 0;
335   connection->client_serial = 1;
336   
337   _dbus_transport_ref (transport);
338   _dbus_transport_set_connection (transport, connection);
339   
340   return connection;
341   
342  error:
343
344   if (connection != NULL)
345     dbus_free (connection);
346
347   if (handler_table)
348     _dbus_hash_table_unref (handler_table);
349   
350   if (watch_list)
351     _dbus_watch_list_free (watch_list);
352   
353   return NULL;
354 }
355
356 static dbus_int32_t
357 _dbus_connection_get_next_client_serial (DBusConnection *connection)
358 {
359   int serial;
360
361   serial = connection->client_serial++;
362
363   if (connection->client_serial < 0)
364     connection->client_serial = 1;
365   
366   return serial;
367 }
368
369 /**
370  * Used to notify a connection when a DBusMessageHandler is
371  * destroyed, so the connection can drop any reference
372  * to the handler.
373  *
374  * @param connection the connection
375  * @param handler the handler
376  */
377 void
378 _dbus_connection_handler_destroyed (DBusConnection     *connection,
379                                     DBusMessageHandler *handler)
380 {
381   DBusHashIter iter;
382   DBusList *link;
383
384   _dbus_hash_iter_init (connection->handler_table, &iter);
385   while (_dbus_hash_iter_next (&iter))
386     {
387       DBusMessageHandler *h = _dbus_hash_iter_get_value (&iter);
388
389       if (h == handler)
390         _dbus_hash_iter_remove_entry (&iter);
391     }
392
393   link = _dbus_list_get_first_link (&connection->filter_list);
394   while (link != NULL)
395     {
396       DBusMessageHandler *h = link->data;
397       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
398
399       if (h == handler)
400         _dbus_list_remove_link (&connection->filter_list,
401                                 link);
402       
403       link = next;
404     }
405 }
406
407 /** @} */
408
409 /**
410  * @addtogroup DBusConnection
411  *
412  * @{
413  */
414
415 /**
416  * Opens a new connection to a remote address.
417  *
418  * @todo specify what the address parameter is. Right now
419  * it's just the name of a UNIX domain socket. It should be
420  * something more complex that encodes which transport to use.
421  *
422  * If the open fails, the function returns #NULL, and provides
423  * a reason for the failure in the result parameter. Pass
424  * #NULL for the result parameter if you aren't interested
425  * in the reason for failure.
426  * 
427  * @param address the address.
428  * @param result address where a result code can be returned.
429  * @returns new connection, or #NULL on failure.
430  */
431 DBusConnection*
432 dbus_connection_open (const char     *address,
433                       DBusResultCode *result)
434 {
435   DBusConnection *connection;
436   DBusTransport *transport;
437   
438   transport = _dbus_transport_open (address, result);
439   if (transport == NULL)
440     return NULL;
441   
442   connection = _dbus_connection_new_for_transport (transport);
443
444   _dbus_transport_unref (transport);
445   
446   if (connection == NULL)
447     {
448       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
449       return NULL;
450     }
451   
452   return connection;
453 }
454
455 /**
456  * Increments the reference count of a DBusConnection.
457  *
458  * @param connection the connection.
459  */
460 void
461 dbus_connection_ref (DBusConnection *connection)
462 {
463   connection->refcount += 1;
464 }
465
466 /**
467  * Decrements the reference count of a DBusConnection, and finalizes
468  * it if the count reaches zero.  If a connection is still connected
469  * when it's finalized, it will be disconnected (that is, associated
470  * file handles will be closed).
471  *
472  * @param connection the connection.
473  */
474 void
475 dbus_connection_unref (DBusConnection *connection)
476 {
477   _dbus_assert (connection != NULL);
478   _dbus_assert (connection->refcount > 0);
479   
480   connection->refcount -= 1;
481   if (connection->refcount == 0)
482     {
483       DBusHashIter iter;
484       DBusList *link;
485       
486       /* free error data as a side effect */
487       dbus_connection_set_error_function (connection,
488                                           NULL, NULL, NULL);
489
490       _dbus_watch_list_free (connection->watches);
491       connection->watches = NULL;
492
493       _dbus_connection_free_data_slots (connection);
494       
495       _dbus_hash_iter_init (connection->handler_table, &iter);
496       while (_dbus_hash_iter_next (&iter))
497         {
498           DBusMessageHandler *h = _dbus_hash_iter_get_value (&iter);
499           
500           _dbus_message_handler_remove_connection (h, connection);
501         }
502
503       link = _dbus_list_get_first_link (&connection->filter_list);
504       while (link != NULL)
505         {
506           DBusMessageHandler *h = link->data;
507           DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
508           
509           _dbus_message_handler_remove_connection (h, connection);
510           
511           link = next;
512         }
513       
514       _dbus_hash_table_unref (connection->handler_table);
515       connection->handler_table = NULL;
516
517       _dbus_list_clear (&connection->filter_list);
518       
519       _dbus_list_foreach (&connection->outgoing_messages,
520                           (DBusForeachFunction) dbus_message_unref,
521                           NULL);
522       _dbus_list_clear (&connection->outgoing_messages);
523
524       _dbus_list_foreach (&connection->incoming_messages,
525                           (DBusForeachFunction) dbus_message_unref,
526                           NULL);
527       _dbus_list_clear (&connection->incoming_messages);
528       
529       _dbus_transport_unref (connection->transport);
530       
531       dbus_free (connection);
532     }
533 }
534
535 /**
536  * Closes the connection, so no further data can be sent or received.
537  * Any further attempts to send data will result in errors.  This
538  * function does not affect the connection's reference count.  It's
539  * safe to disconnect a connection more than once; all calls after the
540  * first do nothing. It's impossible to "reconnect" a connection, a
541  * new connection must be created.
542  *
543  * @param connection the connection.
544  */
545 void
546 dbus_connection_disconnect (DBusConnection *connection)
547 {
548   _dbus_transport_disconnect (connection->transport);
549 }
550
551 /**
552  * Gets whether the connection is currently connected.  All
553  * connections are connected when they are opened.  A connection may
554  * become disconnected when the remote application closes its end, or
555  * exits; a connection may also be disconnected with
556  * dbus_connection_disconnect().
557  *
558  * @param connection the connection.
559  * @returns #TRUE if the connection is still alive.
560  */
561 dbus_bool_t
562 dbus_connection_get_is_connected (DBusConnection *connection)
563 {
564   return _dbus_transport_get_is_connected (connection->transport);
565 }
566
567 /**
568  * Adds a message to the outgoing message queue. Does not block to
569  * write the message to the network; that happens asynchronously. to
570  * force the message to be written, call dbus_connection_flush().
571  *
572  * If the function fails, it returns #FALSE and returns the
573  * reason for failure via the result parameter.
574  * The result parameter can be #NULL if you aren't interested
575  * in the reason for the failure.
576  * 
577  * @param connection the connection.
578  * @param message the message to write.
579  * @param result address where result code can be placed.
580  * @returns #TRUE on success.
581  */
582 dbus_bool_t
583 dbus_connection_send_message (DBusConnection *connection,
584                               DBusMessage    *message,
585                               DBusResultCode *result)
586 {  
587   if (!_dbus_list_prepend (&connection->outgoing_messages,
588                            message))
589     {
590       set_result_handled (connection, result, DBUS_RESULT_NO_MEMORY);
591       return FALSE;
592     }
593
594   dbus_message_ref (message);
595   connection->n_outgoing += 1;
596
597   _dbus_verbose ("Message %p added to outgoing queue, %d pending to send\n",
598                  message, connection->n_outgoing);
599
600   _dbus_message_set_client_serial (message, _dbus_connection_get_next_client_serial (connection));
601   _dbus_message_lock (message);
602   
603   if (connection->n_outgoing == 1)
604     _dbus_transport_messages_pending (connection->transport,
605                                       connection->n_outgoing);
606
607   return TRUE;
608 }
609
610 /**
611  * Queues a message to send, as with dbus_connection_send_message(),
612  * but also sets up a DBusMessageHandler to receive a reply to the
613  * message. If no reply is received in the given timeout_milliseconds,
614  * expires the pending reply and sends the DBusMessageHandler a
615  * synthetic error reply (generated in-process, not by the remote
616  * application) indicating that a timeout occurred.
617  *
618  * Reply handlers see their replies after message filters see them,
619  * but before message handlers added with
620  * dbus_connection_register_handler() see them, regardless of the
621  * reply message's name. Reply handlers are only handed a single
622  * message as a reply, after a reply has been seen the handler is
623  * removed. If a filter filters out the reply before the handler sees
624  * it, the handler is not removed but the timeout will immediately
625  * fire again. If a filter was dumb and kept removing the timeout
626  * reply then we'd get in an infinite loop.
627  * 
628  * If #NULL is passed for the reply_handler, the timeout reply will
629  * still be generated and placed into the message queue, but no
630  * specific message handler will receive the reply.
631  *
632  * If -1 is passed for the timeout, a sane default timeout is used. -1
633  * is typically the best value for the timeout for this reason, unless
634  * you want a very short or very long timeout.  There is no way to
635  * avoid a timeout entirely, other than passing INT_MAX for the
636  * timeout to postpone it indefinitely.
637  * 
638  * @param connection the connection
639  * @param message the message to send
640  * @param reply_handler message handler expecting the reply, or #NULL
641  * @param timeout_milliseconds timeout in milliseconds or -1 for default
642  * @param result return location for result code
643  * @returns #TRUE if the message is successfully queued, #FALSE if no memory.
644  *
645  * @todo this function isn't implemented because we need message serials
646  * and other slightly more rich DBusMessage implementation in order to
647  * implement it. The basic idea will be to keep a hash of serials we're
648  * expecting a reply to, and also to add a way to tell GLib or Qt to
649  * install a timeout. Then install a timeout which is the shortest
650  * timeout of any pending reply.
651  *
652  * @todo implement non-reentrant "block for reply" variant.  i.e. send
653  * a message, block until we get a reply, then pull reply out of
654  * message queue and return it, *without dispatching any handlers for
655  * any other messages* - used for non-reentrant "method calls" We can
656  * block properly for this using _dbus_connection_do_iteration().
657  * 
658  */
659 dbus_bool_t
660 dbus_connection_send_message_with_reply (DBusConnection     *connection,
661                                          DBusMessage        *message,
662                                          DBusMessageHandler *reply_handler,
663                                          int                 timeout_milliseconds,
664                                          DBusResultCode     *result)
665 {
666   /* FIXME */
667   return dbus_connection_send_message (connection, message, result);
668 }
669
670 /**
671  * Blocks until the outgoing message queue is empty.
672  *
673  * @param connection the connection.
674  */
675 void
676 dbus_connection_flush (DBusConnection *connection)
677 {
678   while (connection->n_outgoing > 0)
679     _dbus_connection_do_iteration (connection,
680                                    DBUS_ITERATION_DO_WRITING |
681                                    DBUS_ITERATION_BLOCK,
682                                    -1);
683 }
684
685 /**
686  * Gets the number of messages in the incoming message queue.
687  *
688  * @param connection the connection.
689  * @returns the number of messages in the queue.
690  */
691 int
692 dbus_connection_get_n_messages (DBusConnection *connection)
693 {
694   return connection->n_incoming;
695 }
696
697 /**
698  * Returns the first-received message from the incoming message queue,
699  * leaving it in the queue. The caller does not own a reference to the
700  * returned message. If the queue is empty, returns #NULL.
701  *
702  * @param connection the connection.
703  * @returns next message in the incoming queue.
704  */
705 DBusMessage*
706 dbus_connection_peek_message  (DBusConnection *connection)
707 {
708   return _dbus_list_get_first (&connection->incoming_messages);
709 }
710
711 /**
712  * Returns the first-received message from the incoming message queue,
713  * removing it from the queue. The caller owns a reference to the
714  * returned message. If the queue is empty, returns #NULL.
715  *
716  * @param connection the connection.
717  * @returns next message in the incoming queue.
718  */
719 DBusMessage*
720 dbus_connection_pop_message (DBusConnection *connection)
721 {
722   if (connection->n_incoming > 0)
723     {
724       DBusMessage *message;
725
726       message = _dbus_list_pop_first (&connection->incoming_messages);
727       connection->n_incoming -= 1;
728
729       _dbus_verbose ("Incoming message %p removed from queue, %d incoming\n",
730                      message, connection->n_incoming);
731
732       return message;
733     }
734   else
735     return NULL;
736 }
737
738 /**
739  * Pops the first-received message from the current incoming message
740  * queue, runs any handlers for it, then unrefs the message.
741  *
742  * @param connection the connection
743  * @returns #TRUE if the queue is not empty after dispatch
744  *
745  * @todo this function is not properly robust against reentrancy,
746  * that is, if handlers are added/removed while dispatching
747  * a message, things will get messed up.
748  */
749 dbus_bool_t
750 dbus_connection_dispatch_message (DBusConnection *connection)
751 {
752   DBusMessage *message;
753   int filter_serial;
754   int handler_serial;
755   DBusList *link;
756   DBusHandlerResult result;
757   const char *name;
758   
759   dbus_connection_ref (connection);
760   
761   message = dbus_connection_pop_message (connection);
762   if (message == NULL)
763     {
764       dbus_connection_unref (connection);
765       return FALSE;
766     }
767
768   filter_serial = connection->filters_serial;
769   handler_serial = connection->handlers_serial;
770
771   result = DBUS_HANDLER_RESULT_ALLOW_MORE_HANDLERS;
772   
773   link = _dbus_list_get_first_link (&connection->filter_list);
774   while (link != NULL)
775     {
776       DBusMessageHandler *handler = link->data;
777       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
778       
779       result = _dbus_message_handler_handle_message (handler, connection,
780                                                      message);
781
782       if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
783         goto out;
784
785       if (filter_serial != connection->filters_serial)
786         {
787           _dbus_warn ("Message filters added or removed while dispatching filters - not currently supported!\n");
788           goto out;
789         }
790       
791       link = next;
792     }
793
794   name = dbus_message_get_name (message);
795   if (name != NULL)
796     {
797       DBusMessageHandler *handler;
798       
799       handler = _dbus_hash_table_lookup_string (connection->handler_table,
800                                                 name);
801       if (handler != NULL)
802         {
803
804           result = _dbus_message_handler_handle_message (handler, connection,
805                                                          message);
806       
807           if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
808             goto out;
809           
810           if (handler_serial != connection->handlers_serial)
811             {
812               _dbus_warn ("Message handlers added or removed while dispatching handlers - not currently supported!\n");
813               goto out;
814             }
815         }
816     }
817
818  out:
819   dbus_connection_unref (connection);
820   dbus_message_unref (message);
821   
822   return connection->n_incoming > 0;
823 }
824
825 /**
826  * Sets the error handler function for the connection.
827  * 
828  * @param connection the connection.
829  * @param error_function the error handler.
830  * @param data data to pass to the error handler.
831  * @param free_data_function function to be called to free the data.
832  */
833 void
834 dbus_connection_set_error_function  (DBusConnection              *connection,
835                                      DBusConnectionErrorFunction  error_function,
836                                      void                        *data,
837                                      DBusFreeFunction             free_data_function)
838 {
839   if (connection->error_free_data_function != NULL)
840     (* connection->error_free_data_function) (connection->error_data);
841
842   connection->error_function = error_function;
843   connection->error_data = data;
844   connection->error_free_data_function = free_data_function;
845 }
846
847 /**
848  * Sets the watch functions for the connection. These functions are
849  * responsible for making the application's main loop aware of file
850  * descriptors that need to be monitored for events, using select() or
851  * poll(). When using Qt, typically the DBusAddWatchFunction would
852  * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
853  * could call g_io_add_watch(), or could be used as part of a more
854  * elaborate GSource.
855  *
856  * The DBusWatch can be queried for the file descriptor to watch using
857  * dbus_watch_get_fd(), and for the events to watch for using
858  * dbus_watch_get_flags(). The flags returned by
859  * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
860  * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
861  * all watches implicitly include a watch for hangups, errors, and
862  * other exceptional conditions.
863  *
864  * Once a file descriptor becomes readable or writable, or an exception
865  * occurs, dbus_connection_handle_watch() should be called to
866  * notify the connection of the file descriptor's condition.
867  *
868  * dbus_connection_handle_watch() cannot be called during the
869  * DBusAddWatchFunction, as the connection will not be ready to handle
870  * that watch yet.
871  * 
872  * It is not allowed to reference a DBusWatch after it has been passed
873  * to remove_function.
874  * 
875  * @param connection the connection.
876  * @param add_function function to begin monitoring a new descriptor.
877  * @param remove_function function to stop monitoring a descriptor.
878  * @param data data to pass to add_function and remove_function.
879  * @param free_data_function function to be called to free the data.
880  */
881 void
882 dbus_connection_set_watch_functions (DBusConnection              *connection,
883                                      DBusAddWatchFunction         add_function,
884                                      DBusRemoveWatchFunction      remove_function,
885                                      void                        *data,
886                                      DBusFreeFunction             free_data_function)
887 {
888   /* ref connection for slightly better reentrancy */
889   dbus_connection_ref (connection);
890   
891   _dbus_watch_list_set_functions (connection->watches,
892                                   add_function, remove_function,
893                                   data, free_data_function);
894   
895   /* drop our paranoid refcount */
896   dbus_connection_unref (connection);
897 }
898
899 /**
900  * Called to notify the connection when a previously-added watch
901  * is ready for reading or writing, or has an exception such
902  * as a hangup.
903  *
904  * @param connection the connection.
905  * @param watch the watch.
906  * @param condition the current condition of the file descriptors being watched.
907  */
908 void
909 dbus_connection_handle_watch (DBusConnection              *connection,
910                               DBusWatch                   *watch,
911                               unsigned int                 condition)
912 {
913   _dbus_transport_handle_watch (connection->transport,
914                                 watch, condition);
915 }
916
917 /**
918  * Adds a message filter. Filters are handlers that are run on
919  * all incoming messages, prior to the normal handlers
920  * registered with dbus_connection_register_handler().
921  * Filters are run in the order that they were added.
922  * The same handler can be added as a filter more than once, in
923  * which case it will be run more than once.
924  *
925  * @param connection the connection
926  * @param handler the handler
927  * @returns #TRUE on success, #FALSE if not enough memory.
928  */
929 dbus_bool_t
930 dbus_connection_add_filter (DBusConnection      *connection,
931                             DBusMessageHandler  *handler)
932 {
933   if (!_dbus_message_handler_add_connection (handler, connection))
934     return FALSE;
935
936   if (!_dbus_list_append (&connection->filter_list,
937                           handler))
938     {
939       _dbus_message_handler_remove_connection (handler, connection);
940       return FALSE;
941     }
942
943   connection->filters_serial += 1;
944   
945   return TRUE;
946 }
947
948 /**
949  * Removes a previously-added message filter. It is a programming
950  * error to call this function for a handler that has not
951  * been added as a filter. If the given handler was added
952  * more than once, only one instance of it will be removed
953  * (the most recently-added instance).
954  *
955  * @param connection the connection
956  * @param handler the handler to remove
957  *
958  */
959 void
960 dbus_connection_remove_filter (DBusConnection      *connection,
961                                DBusMessageHandler  *handler)
962 {
963   if (!_dbus_list_remove_last (&connection->filter_list, handler))
964     {
965       _dbus_warn ("Tried to remove a DBusConnection filter that had not been added\n");
966       return;
967     }
968
969   _dbus_message_handler_remove_connection (handler, connection);
970
971   connection->filters_serial += 1;
972 }
973
974 /**
975  * Registers a handler for a list of message names. A single handler
976  * can be registered for any number of message names, but each message
977  * name can only have one handler at a time. It's not allowed to call
978  * this function with the name of a message that already has a
979  * handler. If the function returns #FALSE, the handlers were not
980  * registered due to lack of memory.
981  * 
982  * @param connection the connection
983  * @param handler the handler
984  * @param messages_to_handle the messages to handle
985  * @param n_messages the number of message names in messages_to_handle
986  * @returns #TRUE on success, #FALSE if no memory or another handler already exists
987  * 
988  **/
989 dbus_bool_t
990 dbus_connection_register_handler (DBusConnection     *connection,
991                                   DBusMessageHandler *handler,
992                                   const char        **messages_to_handle,
993                                   int                 n_messages)
994 {
995   int i;
996
997   i = 0;
998   while (i < n_messages)
999     {
1000       DBusHashIter iter;
1001       char *key;
1002
1003       key = _dbus_strdup (messages_to_handle[i]);
1004       if (key == NULL)
1005         goto failed;
1006       
1007       if (!_dbus_hash_iter_lookup (connection->handler_table,
1008                                    key, TRUE,
1009                                    &iter))
1010         {
1011           dbus_free (key);
1012           goto failed;
1013         }
1014
1015       if (_dbus_hash_iter_get_value (&iter) != NULL)
1016         {
1017           _dbus_warn ("Bug in application: attempted to register a second handler for %s\n",
1018                       messages_to_handle[i]);
1019           dbus_free (key); /* won't have replaced the old key with the new one */
1020           goto failed;
1021         }
1022
1023       if (!_dbus_message_handler_add_connection (handler, connection))
1024         {
1025           _dbus_hash_iter_remove_entry (&iter);
1026           /* key has freed on nuking the entry */
1027           goto failed;
1028         }
1029       
1030       _dbus_hash_iter_set_value (&iter, handler);
1031
1032       connection->handlers_serial += 1;
1033       
1034       ++i;
1035     }
1036   
1037   return TRUE;
1038   
1039  failed:
1040   /* unregister everything registered so far,
1041    * so we don't fail partially
1042    */
1043   dbus_connection_unregister_handler (connection,
1044                                       handler,
1045                                       messages_to_handle,
1046                                       i);
1047
1048   return FALSE;
1049 }
1050
1051 /**
1052  * Unregisters a handler for a list of message names. The handlers
1053  * must have been previously registered.
1054  *
1055  * @param connection the connection
1056  * @param handler the handler
1057  * @param messages_to_handle the messages to handle
1058  * @param n_messages the number of message names in messages_to_handle
1059  * 
1060  **/
1061 void
1062 dbus_connection_unregister_handler (DBusConnection     *connection,
1063                                     DBusMessageHandler *handler,
1064                                     const char        **messages_to_handle,
1065                                     int                 n_messages)
1066 {
1067   int i;
1068
1069   i = 0;
1070   while (i < n_messages)
1071     {
1072       DBusHashIter iter;
1073
1074       if (!_dbus_hash_iter_lookup (connection->handler_table,
1075                                    (char*) messages_to_handle[i], FALSE,
1076                                    &iter))
1077         {
1078           _dbus_warn ("Bug in application: attempted to unregister handler for %s which was not registered\n",
1079                       messages_to_handle[i]);
1080         }
1081       else if (_dbus_hash_iter_get_value (&iter) != handler)
1082         {
1083           _dbus_warn ("Bug in application: attempted to unregister handler for %s which was registered by a different handler\n",
1084                       messages_to_handle[i]);
1085         }
1086       else
1087         {
1088           _dbus_hash_iter_remove_entry (&iter);
1089           _dbus_message_handler_remove_connection (handler, connection);
1090         }
1091
1092       ++i;
1093     }
1094
1095   connection->handlers_serial += 1;
1096 }
1097
1098 static int *allocated_slots = NULL;
1099 static int  n_allocated_slots = 0;
1100 static int  n_used_slots = 0;
1101 static DBusStaticMutex allocated_slots_lock = DBUS_STATIC_MUTEX_INIT;
1102
1103 /**
1104  * Allocates an integer ID to be used for storing application-specific
1105  * data on any DBusConnection. The allocated ID may then be used
1106  * with dbus_connection_set_data() and dbus_connection_get_data().
1107  * If allocation fails, -1 is returned.
1108  *
1109  * @returns -1 on failure, otherwise the data slot ID
1110  */
1111 int
1112 dbus_connection_allocate_data_slot (void)
1113 {
1114   int slot;
1115   
1116   if (!dbus_static_mutex_lock (&allocated_slots_lock))
1117     return -1;
1118
1119   if (n_used_slots < n_allocated_slots)
1120     {
1121       slot = 0;
1122       while (slot < n_allocated_slots)
1123         {
1124           if (allocated_slots[slot] < 0)
1125             {
1126               allocated_slots[slot] = slot;
1127               n_used_slots += 1;
1128               break;
1129             }
1130           ++slot;
1131         }
1132
1133       _dbus_assert (slot < n_allocated_slots);
1134     }
1135   else
1136     {
1137       int *tmp;
1138       
1139       slot = -1;
1140       tmp = dbus_realloc (allocated_slots,
1141                           sizeof (int) * (n_allocated_slots + 1));
1142       if (tmp == NULL)
1143         goto out;
1144
1145       allocated_slots = tmp;
1146       slot = n_allocated_slots;
1147       n_allocated_slots += 1;
1148       n_used_slots += 1;
1149       allocated_slots[slot] = slot;
1150     }
1151
1152   _dbus_assert (slot >= 0);
1153   _dbus_assert (slot < n_allocated_slots);
1154   
1155  out:
1156   dbus_static_mutex_unlock (&allocated_slots_lock);
1157   return slot;
1158 }
1159
1160 /**
1161  * Deallocates a global ID for connection data slots.
1162  * dbus_connection_get_data() and dbus_connection_set_data()
1163  * may no longer be used with this slot.
1164  * Existing data stored on existing DBusConnection objects
1165  * will be freed when the connection is finalized,
1166  * but may not be retrieved (and may only be replaced
1167  * if someone else reallocates the slot).
1168  *
1169  * @param slot the slot to deallocate
1170  */
1171 void
1172 dbus_connection_free_data_slot (int slot)
1173 {
1174   dbus_static_mutex_lock (&allocated_slots_lock);
1175
1176   _dbus_assert (slot < n_allocated_slots);
1177   _dbus_assert (allocated_slots[slot] == slot);
1178   
1179   allocated_slots[slot] = -1;
1180   n_used_slots -= 1;
1181
1182   if (n_used_slots == 0)
1183     {
1184       dbus_free (allocated_slots);
1185       allocated_slots = NULL;
1186       n_allocated_slots = 0;
1187     }
1188   
1189   dbus_static_mutex_unlock (&allocated_slots_lock);
1190 }
1191
1192 /**
1193  * Stores a pointer on a DBusConnection, along
1194  * with an optional function to be used for freeing
1195  * the data when the data is set again, or when
1196  * the connection is finalized. The slot number
1197  * must have been allocated with dbus_connection_allocate_data_slot().
1198  *
1199  * @param connection the connection
1200  * @param slot the slot number
1201  * @param data the data to store
1202  * @param free_data_func finalizer function for the data
1203  * @returns #TRUE if there was enough memory to store the data
1204  */
1205 dbus_bool_t
1206 dbus_connection_set_data (DBusConnection   *connection,
1207                           int               slot,
1208                           void             *data,
1209                           DBusFreeFunction  free_data_func)
1210 {
1211   _dbus_assert (slot < n_allocated_slots);
1212   _dbus_assert (allocated_slots[slot] == slot);
1213   
1214   if (slot >= connection->n_slots)
1215     {
1216       DBusDataSlot *tmp;
1217       int i;
1218       
1219       tmp = dbus_realloc (connection->data_slots,
1220                           sizeof (DBusDataSlot) * (slot + 1));
1221       if (tmp == NULL)
1222         return FALSE;
1223       
1224       connection->data_slots = tmp;
1225       i = connection->n_slots;
1226       connection->n_slots = slot + 1;
1227       while (i < connection->n_slots)
1228         {
1229           connection->data_slots[i].data = NULL;
1230           connection->data_slots[i].free_data_func = NULL;
1231           ++i;
1232         }
1233     }
1234
1235   _dbus_assert (slot < connection->n_slots);
1236   
1237   if (connection->data_slots[slot].free_data_func)
1238     (* connection->data_slots[slot].free_data_func) (connection->data_slots[slot].data);
1239
1240   connection->data_slots[slot].data = data;
1241   connection->data_slots[slot].free_data_func = free_data_func;
1242
1243   return TRUE;
1244 }
1245
1246 /**
1247  * Retrieves data previously set with dbus_connection_set_data().
1248  * The slot must still be allocated (must not have been freed).
1249  *
1250  * @param connection the connection
1251  * @param slot the slot to get data from
1252  * @returns the data, or #NULL if not found
1253  */
1254 void*
1255 dbus_connection_get_data (DBusConnection   *connection,
1256                           int               slot)
1257 {
1258   _dbus_assert (slot < n_allocated_slots);
1259   _dbus_assert (allocated_slots[slot] == slot);
1260
1261   if (slot >= connection->n_slots)
1262     return NULL;
1263
1264   return connection->data_slots[slot].data;
1265 }
1266
1267 static void
1268 _dbus_connection_free_data_slots (DBusConnection *connection)
1269 {
1270   int i;
1271
1272   i = 0;
1273   while (i < connection->n_slots)
1274     {
1275       if (connection->data_slots[i].free_data_func)
1276         (* connection->data_slots[i].free_data_func) (connection->data_slots[i].data);
1277       connection->data_slots[i].data = NULL;
1278       connection->data_slots[i].free_data_func = NULL;
1279       ++i;
1280     }
1281
1282   dbus_free (connection->data_slots);
1283   connection->data_slots = NULL;
1284   connection->n_slots = 0;
1285 }
1286
1287 /** @} */