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