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