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