2003-03-14 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-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-message-handler.h"
34 #include "dbus-threads.h"
35 #include "dbus-protocol.h"
36 #include "dbus-dataslot.h"
37
38 /**
39  * @defgroup DBusConnection DBusConnection
40  * @ingroup  DBus
41  * @brief Connection to another application
42  *
43  * A DBusConnection represents a connection to another
44  * application. Messages can be sent and received via this connection.
45  *
46  * The connection maintains a queue of incoming messages and a queue
47  * of outgoing messages. dbus_connection_pop_message() and friends
48  * can be used to read incoming messages from the queue.
49  * Outgoing messages are automatically discarded as they are
50  * written to the network.
51  *
52  * In brief a DBusConnection is a message queue associated with some
53  * message transport mechanism such as a socket.
54  * 
55  */
56
57 /**
58  * @defgroup DBusConnectionInternals DBusConnection implementation details
59  * @ingroup  DBusInternals
60  * @brief Implementation details of DBusConnection
61  *
62  * @{
63  */
64
65 /** default timeout value when waiting for a message reply */
66 #define DEFAULT_TIMEOUT_VALUE (15 * 1000)
67
68 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
69
70 /**
71  * Implementation details of DBusConnection. All fields are private.
72  */
73 struct DBusConnection
74 {
75   int refcount; /**< Reference count. */
76
77   DBusMutex *mutex; /**< Lock on the entire DBusConnection */
78
79   dbus_bool_t dispatch_acquired; /**< Protects dispatch_message */
80   DBusCondVar *dispatch_cond;    /**< Protects dispatch_message */
81
82   dbus_bool_t io_path_acquired;  /**< Protects transport io path */
83   DBusCondVar *io_path_cond;     /**< Protects transport io path */
84   
85   DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
86   DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
87
88   DBusMessage *message_borrowed; /**< True if the first incoming message has been borrowed */
89   DBusCondVar *message_returned_cond; /**< Used with dbus_connection_borrow_message() */
90   
91   int n_outgoing;              /**< Length of outgoing queue. */
92   int n_incoming;              /**< Length of incoming queue. */
93   
94   DBusTransport *transport;    /**< Object that sends/receives messages over network. */
95   DBusWatchList *watches;      /**< Stores active watches. */
96   DBusTimeoutList *timeouts;   /**< Stores active timeouts. */
97   
98   DBusHashTable *handler_table; /**< Table of registered DBusMessageHandler */
99   DBusList *filter_list;        /**< List of filters. */
100
101   DBusDataSlotList slot_list;   /**< Data stored by allocated integer ID */
102
103   DBusHashTable *pending_replies;  /**< Hash of message serials and their message handlers. */  
104   DBusCounter *connection_counter; /**< Counter that we decrement when finalized */
105   
106   int client_serial;            /**< Client serial. Increments each time a message is sent  */
107   DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
108
109   DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop  */
110   void *wakeup_main_data; /**< Application data for wakeup_main_function */
111   DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
112 };
113
114 typedef struct
115 {
116   DBusConnection *connection;
117   DBusMessageHandler *handler;
118   DBusTimeout *timeout;
119   int serial;
120
121   DBusList *timeout_link; /* Preallocated timeout response */
122   
123   dbus_bool_t timeout_added;
124   dbus_bool_t connection_added;
125 } ReplyHandlerData;
126
127 static void reply_handler_data_free (ReplyHandlerData *data);
128
129 static void _dbus_connection_remove_timeout_locked (DBusConnection *connection,
130                                                     DBusTimeout    *timeout);
131
132 /**
133  * Acquires the connection lock.
134  *
135  * @param connection the connection.
136  */
137 void
138 _dbus_connection_lock (DBusConnection *connection)
139 {
140   dbus_mutex_lock (connection->mutex);
141 }
142
143 /**
144  * Releases the connection lock.
145  *
146  * @param connection the connection.
147  */
148 void
149 _dbus_connection_unlock (DBusConnection *connection)
150 {
151   dbus_mutex_unlock (connection->mutex);
152 }
153
154 /**
155  * Wakes up the main loop if it is sleeping
156  * Needed if we're e.g. queueing outgoing messages
157  * on a thread while the mainloop sleeps.
158  *
159  * @param connection the connection.
160  */
161 static void
162 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
163 {
164   if (connection->wakeup_main_function)
165     (*connection->wakeup_main_function) (connection->wakeup_main_data);
166 }
167
168 /**
169  * Adds a message to the incoming message queue, returning #FALSE
170  * if there's insufficient memory to queue the message.
171  *
172  * @param connection the connection.
173  * @param message the message to queue.
174  * @returns #TRUE on success.
175  */
176 dbus_bool_t
177 _dbus_connection_queue_received_message (DBusConnection *connection,
178                                          DBusMessage    *message)
179 {
180   ReplyHandlerData *reply_handler_data;
181   dbus_int32_t reply_serial;
182   
183   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
184   
185   if (!_dbus_list_append (&connection->incoming_messages,
186                           message))
187     return FALSE;
188
189   /* If this is a reply we're waiting on, remove timeout for it */
190   reply_serial = dbus_message_get_reply_serial (message);
191   if (reply_serial != -1)
192     {
193       reply_handler_data = _dbus_hash_table_lookup_int (connection->pending_replies,
194                                                         reply_serial);
195       if (reply_handler_data != NULL)
196         {
197           if (reply_handler_data->timeout_added)
198             _dbus_connection_remove_timeout_locked (connection,
199                                                     reply_handler_data->timeout);
200           reply_handler_data->timeout_added = FALSE;
201         }
202     }
203   
204   dbus_message_ref (message);
205   connection->n_incoming += 1;
206
207   _dbus_connection_wakeup_mainloop (connection);
208
209   _dbus_assert (dbus_message_get_name (message) != NULL);
210   _dbus_verbose ("Incoming message %p (%s) added to queue, %d incoming\n",
211                  message, dbus_message_get_name (message),
212                  connection->n_incoming);
213   
214   return TRUE;
215 }
216
217 /**
218  * Adds a link + message to the incoming message queue.
219  * Can't fail. Takes ownership of both link and message.
220  *
221  * @param connection the connection.
222  * @param link the list node and message to queue.
223  *
224  * @todo This needs to wake up the mainloop if it is in
225  * a poll/select and this is a multithreaded app.
226  */
227 static void
228 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
229                                                  DBusList *link)
230 {
231   _dbus_list_append_link (&connection->incoming_messages, link);
232
233   connection->n_incoming += 1;
234
235   _dbus_connection_wakeup_mainloop (connection);
236   
237   _dbus_verbose ("Incoming synthesized message %p added to queue, %d incoming\n",
238                  link->data, connection->n_incoming);
239 }
240
241
242 /**
243  * Checks whether there are messages in the outgoing message queue.
244  *
245  * @param connection the connection.
246  * @returns #TRUE if the outgoing queue is non-empty.
247  */
248 dbus_bool_t
249 _dbus_connection_have_messages_to_send (DBusConnection *connection)
250 {
251   return connection->outgoing_messages != NULL;
252 }
253
254 /**
255  * Gets the next outgoing message. The message remains in the
256  * queue, and the caller does not own a reference to it.
257  *
258  * @param connection the connection.
259  * @returns the message to be sent.
260  */ 
261 DBusMessage*
262 _dbus_connection_get_message_to_send (DBusConnection *connection)
263 {
264   return _dbus_list_get_last (&connection->outgoing_messages);
265 }
266
267 /**
268  * Notifies the connection that a message has been sent, so the
269  * message can be removed from the outgoing queue.
270  *
271  * @param connection the connection.
272  * @param message the message that was sent.
273  */
274 void
275 _dbus_connection_message_sent (DBusConnection *connection,
276                                DBusMessage    *message)
277 {
278   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
279   _dbus_assert (message == _dbus_list_get_last (&connection->outgoing_messages));
280   
281   _dbus_list_pop_last (&connection->outgoing_messages);
282   dbus_message_unref (message);
283   
284   connection->n_outgoing -= 1;
285
286   _dbus_verbose ("Message %p removed from outgoing queue, %d left to send\n",
287                  message, connection->n_outgoing);
288   
289   if (connection->n_outgoing == 0)
290     _dbus_transport_messages_pending (connection->transport,
291                                       connection->n_outgoing);  
292 }
293
294 /**
295  * Adds a watch using the connection's DBusAddWatchFunction if
296  * available. Otherwise records the watch to be added when said
297  * function is available. Also re-adds the watch if the
298  * DBusAddWatchFunction changes. May fail due to lack of memory.
299  *
300  * @param connection the connection.
301  * @param watch the watch to add.
302  * @returns #TRUE on success.
303  */
304 dbus_bool_t
305 _dbus_connection_add_watch (DBusConnection *connection,
306                             DBusWatch      *watch)
307 {
308   if (connection->watches) /* null during finalize */
309     return _dbus_watch_list_add_watch (connection->watches,
310                                        watch);
311   else
312     return FALSE;
313 }
314
315 /**
316  * Removes a watch using the connection's DBusRemoveWatchFunction
317  * if available. It's an error to call this function on a watch
318  * that was not previously added.
319  *
320  * @param connection the connection.
321  * @param watch the watch to remove.
322  */
323 void
324 _dbus_connection_remove_watch (DBusConnection *connection,
325                                DBusWatch      *watch)
326 {
327   if (connection->watches) /* null during finalize */
328     _dbus_watch_list_remove_watch (connection->watches,
329                                    watch);
330 }
331
332 /**
333  * Adds a timeout using the connection's DBusAddTimeoutFunction if
334  * available. Otherwise records the timeout to be added when said
335  * function is available. Also re-adds the timeout if the
336  * DBusAddTimeoutFunction changes. May fail due to lack of memory.
337  * The timeout will fire only one time.
338  *
339  * @param connection the connection.
340  * @param timeout the timeout to add.
341  * @returns #TRUE on success.
342  */
343 dbus_bool_t
344 _dbus_connection_add_timeout (DBusConnection *connection,
345                               DBusTimeout    *timeout)
346 {
347  if (connection->timeouts) /* null during finalize */
348     return _dbus_timeout_list_add_timeout (connection->timeouts,
349                                            timeout);
350   else
351     return FALSE;  
352 }
353
354 /**
355  * Removes a timeout using the connection's DBusRemoveTimeoutFunction
356  * if available. It's an error to call this function on a timeout
357  * that was not previously added.
358  *
359  * @param connection the connection.
360  * @param timeout the timeout to remove.
361  */
362 void
363 _dbus_connection_remove_timeout (DBusConnection *connection,
364                                  DBusTimeout    *timeout)
365 {
366   if (connection->timeouts) /* null during finalize */
367     _dbus_timeout_list_remove_timeout (connection->timeouts,
368                                        timeout);
369 }
370
371 static void
372 _dbus_connection_remove_timeout_locked (DBusConnection *connection,
373                                         DBusTimeout    *timeout)
374 {
375   dbus_mutex_lock (connection->mutex);
376   _dbus_connection_remove_timeout (connection, timeout);
377   dbus_mutex_unlock (connection->mutex);
378 }
379
380
381 /**
382  * Tells the connection that the transport has been disconnected.
383  * Results in posting a disconnect message on the incoming message
384  * queue.  Only has an effect the first time it's called.
385  *
386  * @param connection the connection
387  */
388 void
389 _dbus_connection_notify_disconnected (DBusConnection *connection)
390 {
391   if (connection->disconnect_message_link)
392     {
393       /* We haven't sent the disconnect message already */
394       _dbus_connection_queue_synthesized_message_link (connection,
395                                                        connection->disconnect_message_link);
396       connection->disconnect_message_link = NULL;
397     }
398 }
399
400
401 /**
402  * Acquire the transporter I/O path. This must be done before
403  * doing any I/O in the transporter. May sleep and drop the
404  * connection mutex while waiting for the I/O path.
405  *
406  * @param connection the connection.
407  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
408  * @returns TRUE if the I/O path was acquired.
409  */
410 static dbus_bool_t
411 _dbus_connection_acquire_io_path (DBusConnection *connection,
412                                   int timeout_milliseconds)
413 {
414   dbus_bool_t res = TRUE;
415
416   if (connection->io_path_acquired)
417     {
418       if (timeout_milliseconds != -1) 
419         res = dbus_condvar_wait_timeout (connection->io_path_cond,
420                                          connection->mutex,
421                                          timeout_milliseconds);
422       else
423         dbus_condvar_wait (connection->io_path_cond, connection->mutex);
424     }
425   
426   if (res)
427     {
428       _dbus_assert (!connection->io_path_acquired);
429
430       connection->io_path_acquired = TRUE;
431     }
432   
433   return res;
434 }
435
436 /**
437  * Release the I/O path when you're done with it. Only call
438  * after you've acquired the I/O. Wakes up at most one thread
439  * currently waiting to acquire the I/O path.
440  *
441  * @param connection the connection.
442  */
443 static void
444 _dbus_connection_release_io_path (DBusConnection *connection)
445 {
446   _dbus_assert (connection->io_path_acquired);
447
448   connection->io_path_acquired = FALSE;
449   dbus_condvar_wake_one (connection->io_path_cond);
450 }
451
452
453 /**
454  * Queues incoming messages and sends outgoing messages for this
455  * connection, optionally blocking in the process. Each call to
456  * _dbus_connection_do_iteration() will call select() or poll() one
457  * time and then read or write data if possible.
458  *
459  * The purpose of this function is to be able to flush outgoing
460  * messages or queue up incoming messages without returning
461  * control to the application and causing reentrancy weirdness.
462  *
463  * The flags parameter allows you to specify whether to
464  * read incoming messages, write outgoing messages, or both,
465  * and whether to block if no immediate action is possible.
466  *
467  * The timeout_milliseconds parameter does nothing unless the
468  * iteration is blocking.
469  *
470  * If there are no outgoing messages and DBUS_ITERATION_DO_READING
471  * wasn't specified, then it's impossible to block, even if
472  * you specify DBUS_ITERATION_BLOCK; in that case the function
473  * returns immediately.
474  * 
475  * @param connection the connection.
476  * @param flags iteration flags.
477  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
478  */
479 void
480 _dbus_connection_do_iteration (DBusConnection *connection,
481                                unsigned int    flags,
482                                int             timeout_milliseconds)
483 {
484   if (connection->n_outgoing == 0)
485     flags &= ~DBUS_ITERATION_DO_WRITING;
486
487   if (_dbus_connection_acquire_io_path (connection,
488                                         (flags & DBUS_ITERATION_BLOCK)?timeout_milliseconds:0))
489     {
490       _dbus_transport_do_iteration (connection->transport,
491                                     flags, timeout_milliseconds);
492       _dbus_connection_release_io_path (connection);
493     }
494 }
495
496 /**
497  * Creates a new connection for the given transport.  A transport
498  * represents a message stream that uses some concrete mechanism, such
499  * as UNIX domain sockets. May return #NULL if insufficient
500  * memory exists to create the connection.
501  *
502  * @param transport the transport.
503  * @returns the new connection, or #NULL on failure.
504  */
505 DBusConnection*
506 _dbus_connection_new_for_transport (DBusTransport *transport)
507 {
508   DBusConnection *connection;
509   DBusWatchList *watch_list;
510   DBusTimeoutList *timeout_list;
511   DBusHashTable *handler_table, *pending_replies;
512   DBusMutex *mutex;
513   DBusCondVar *message_returned_cond;
514   DBusCondVar *dispatch_cond;
515   DBusCondVar *io_path_cond;
516   DBusList *disconnect_link;
517   DBusMessage *disconnect_message;
518
519   watch_list = NULL;
520   connection = NULL;
521   handler_table = NULL;
522   pending_replies = NULL;
523   timeout_list = NULL;
524   mutex = NULL;
525   message_returned_cond = NULL;
526   dispatch_cond = NULL;
527   io_path_cond = NULL;
528   disconnect_link = NULL;
529   disconnect_message = NULL;
530   
531   watch_list = _dbus_watch_list_new ();
532   if (watch_list == NULL)
533     goto error;
534
535   timeout_list = _dbus_timeout_list_new ();
536   if (timeout_list == NULL)
537     goto error;
538   
539   handler_table =
540     _dbus_hash_table_new (DBUS_HASH_STRING,
541                           dbus_free, NULL);
542   if (handler_table == NULL)
543     goto error;
544
545   pending_replies =
546     _dbus_hash_table_new (DBUS_HASH_INT,
547                           NULL, (DBusFreeFunction)reply_handler_data_free);
548   if (pending_replies == NULL)
549     goto error;
550   
551   connection = dbus_new0 (DBusConnection, 1);
552   if (connection == NULL)
553     goto error;
554
555   mutex = dbus_mutex_new ();
556   if (mutex == NULL)
557     goto error;
558   
559   message_returned_cond = dbus_condvar_new ();
560   if (message_returned_cond == NULL)
561     goto error;
562   
563   dispatch_cond = dbus_condvar_new ();
564   if (dispatch_cond == NULL)
565     goto error;
566   
567   io_path_cond = dbus_condvar_new ();
568   if (io_path_cond == NULL)
569     goto error;
570
571   disconnect_message = dbus_message_new (NULL, DBUS_MESSAGE_LOCAL_DISCONNECT);
572   if (disconnect_message == NULL)
573     goto error;
574
575   disconnect_link = _dbus_list_alloc_link (disconnect_message);
576   if (disconnect_link == NULL)
577     goto error;
578
579   if (_dbus_modify_sigpipe)
580     _dbus_disable_sigpipe ();
581   
582   connection->refcount = 1;
583   connection->mutex = mutex;
584   connection->dispatch_cond = dispatch_cond;
585   connection->io_path_cond = io_path_cond;
586   connection->message_returned_cond = message_returned_cond;
587   connection->transport = transport;
588   connection->watches = watch_list;
589   connection->timeouts = timeout_list;
590   connection->handler_table = handler_table;
591   connection->pending_replies = pending_replies;
592   connection->filter_list = NULL;
593
594   _dbus_data_slot_list_init (&connection->slot_list);
595
596   connection->client_serial = 1;
597
598   connection->disconnect_message_link = disconnect_link;
599   
600   _dbus_transport_ref (transport);
601   _dbus_transport_set_connection (transport, connection);
602   
603   return connection;
604   
605  error:
606   if (disconnect_message != NULL)
607     dbus_message_unref (disconnect_message);
608   
609   if (disconnect_link != NULL)
610     _dbus_list_free_link (disconnect_link);
611   
612   if (io_path_cond != NULL)
613     dbus_condvar_free (io_path_cond);
614   
615   if (dispatch_cond != NULL)
616     dbus_condvar_free (dispatch_cond);
617   
618   if (message_returned_cond != NULL)
619     dbus_condvar_free (message_returned_cond);
620   
621   if (mutex != NULL)
622     dbus_mutex_free (mutex);
623
624   if (connection != NULL)
625     dbus_free (connection);
626
627   if (handler_table)
628     _dbus_hash_table_unref (handler_table);
629
630   if (pending_replies)
631     _dbus_hash_table_unref (pending_replies);
632   
633   if (watch_list)
634     _dbus_watch_list_free (watch_list);
635
636   if (timeout_list)
637     _dbus_timeout_list_free (timeout_list);
638   
639   return NULL;
640 }
641
642 static dbus_int32_t
643 _dbus_connection_get_next_client_serial (DBusConnection *connection)
644 {
645   int serial;
646
647   serial = connection->client_serial++;
648
649   if (connection->client_serial < 0)
650     connection->client_serial = 1;
651   
652   return serial;
653 }
654
655 /**
656  * Used to notify a connection when a DBusMessageHandler is
657  * destroyed, so the connection can drop any reference
658  * to the handler. This is a private function, but still
659  * takes the connection lock. Don't call it with the lock held.
660  *
661  * @todo needs to check in pending_replies too.
662  * 
663  * @param connection the connection
664  * @param handler the handler
665  */
666 void
667 _dbus_connection_handler_destroyed_locked (DBusConnection     *connection,
668                                            DBusMessageHandler *handler)
669 {
670   DBusHashIter iter;
671   DBusList *link;
672
673   dbus_mutex_lock (connection->mutex);
674   
675   _dbus_hash_iter_init (connection->handler_table, &iter);
676   while (_dbus_hash_iter_next (&iter))
677     {
678       DBusMessageHandler *h = _dbus_hash_iter_get_value (&iter);
679
680       if (h == handler)
681         _dbus_hash_iter_remove_entry (&iter);
682     }
683
684   link = _dbus_list_get_first_link (&connection->filter_list);
685   while (link != NULL)
686     {
687       DBusMessageHandler *h = link->data;
688       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
689
690       if (h == handler)
691         _dbus_list_remove_link (&connection->filter_list,
692                                 link);
693       
694       link = next;
695     }
696   dbus_mutex_unlock (connection->mutex);
697 }
698
699 /**
700  * Adds the counter used to count the number of open connections.
701  * Increments the counter by one, and saves it to be decremented
702  * again when this connection is finalized.
703  *
704  * @param connection a #DBusConnection
705  * @param counter counter that tracks number of connections
706  */
707 void
708 _dbus_connection_set_connection_counter (DBusConnection *connection,
709                                          DBusCounter    *counter)
710 {
711   _dbus_assert (connection->connection_counter == NULL);
712   
713   connection->connection_counter = counter;
714   _dbus_counter_ref (connection->connection_counter);
715   _dbus_counter_adjust (connection->connection_counter, 1);
716 }
717
718 /** @} */
719
720 /**
721  * @addtogroup DBusConnection
722  *
723  * @{
724  */
725
726 /**
727  * Opens a new connection to a remote address.
728  *
729  * @todo specify what the address parameter is. Right now
730  * it's just the name of a UNIX domain socket. It should be
731  * something more complex that encodes which transport to use.
732  *
733  * If the open fails, the function returns #NULL, and provides
734  * a reason for the failure in the result parameter. Pass
735  * #NULL for the result parameter if you aren't interested
736  * in the reason for failure.
737  * 
738  * @param address the address.
739  * @param result address where a result code can be returned.
740  * @returns new connection, or #NULL on failure.
741  */
742 DBusConnection*
743 dbus_connection_open (const char     *address,
744                       DBusResultCode *result)
745 {
746   DBusConnection *connection;
747   DBusTransport *transport;
748   
749   transport = _dbus_transport_open (address, result);
750   if (transport == NULL)
751     return NULL;
752   
753   connection = _dbus_connection_new_for_transport (transport);
754
755   _dbus_transport_unref (transport);
756   
757   if (connection == NULL)
758     {
759       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
760       return NULL;
761     }
762   
763   return connection;
764 }
765
766 /**
767  * Increments the reference count of a DBusConnection.
768  *
769  * @param connection the connection.
770  */
771 void
772 dbus_connection_ref (DBusConnection *connection)
773 {
774   dbus_mutex_lock (connection->mutex);
775   _dbus_assert (connection->refcount > 0);
776
777   connection->refcount += 1;
778   dbus_mutex_unlock (connection->mutex);
779 }
780
781 /**
782  * Increments the reference count of a DBusConnection.
783  * Requires that the caller already holds the connection lock.
784  *
785  * @param connection the connection.
786  */
787 void
788 _dbus_connection_ref_unlocked (DBusConnection *connection)
789 {
790   _dbus_assert (connection->refcount > 0);
791   connection->refcount += 1;
792 }
793
794
795 /* This is run without the mutex held, but after the last reference
796  * to the connection has been dropped we should have no thread-related
797  * problems
798  */
799 static void
800 _dbus_connection_last_unref (DBusConnection *connection)
801 {
802   DBusHashIter iter;
803   DBusList *link;
804
805   /* You have to disconnect the connection before unref:ing it. Otherwise
806    * you won't get the disconnected message.
807    */
808   _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
809   
810   if (connection->connection_counter != NULL)
811     {
812       /* subtract ourselves from the counter */
813       _dbus_counter_adjust (connection->connection_counter, - 1);
814       _dbus_counter_unref (connection->connection_counter);
815       connection->connection_counter = NULL;
816     }
817   
818   _dbus_watch_list_free (connection->watches);
819   connection->watches = NULL;
820   
821   _dbus_timeout_list_free (connection->timeouts);
822   connection->timeouts = NULL;
823
824   /* calls out to application code... */
825   _dbus_data_slot_list_free (&connection->slot_list);
826   
827   _dbus_hash_iter_init (connection->handler_table, &iter);
828   while (_dbus_hash_iter_next (&iter))
829     {
830       DBusMessageHandler *h = _dbus_hash_iter_get_value (&iter);
831       
832       _dbus_message_handler_remove_connection (h, connection);
833     }
834   
835   link = _dbus_list_get_first_link (&connection->filter_list);
836   while (link != NULL)
837     {
838       DBusMessageHandler *h = link->data;
839       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
840       
841       _dbus_message_handler_remove_connection (h, connection);
842       
843       link = next;
844     }
845
846   _dbus_hash_table_unref (connection->handler_table);
847   connection->handler_table = NULL;
848
849   _dbus_hash_table_unref (connection->pending_replies);
850   connection->pending_replies = NULL;
851   
852   _dbus_list_clear (&connection->filter_list);
853   
854   _dbus_list_foreach (&connection->outgoing_messages,
855                       (DBusForeachFunction) dbus_message_unref,
856                       NULL);
857   _dbus_list_clear (&connection->outgoing_messages);
858   
859   _dbus_list_foreach (&connection->incoming_messages,
860                       (DBusForeachFunction) dbus_message_unref,
861                       NULL);
862   _dbus_list_clear (&connection->incoming_messages);
863   
864   _dbus_transport_unref (connection->transport);
865
866   if (connection->disconnect_message_link)
867     {
868       DBusMessage *message = connection->disconnect_message_link->data;
869       dbus_message_unref (message);
870       _dbus_list_free_link (connection->disconnect_message_link);
871     }
872   
873   dbus_condvar_free (connection->dispatch_cond);
874   dbus_condvar_free (connection->io_path_cond);
875   dbus_condvar_free (connection->message_returned_cond);
876   
877   dbus_mutex_free (connection->mutex);
878   
879   dbus_free (connection);
880 }
881
882 /**
883  * Decrements the reference count of a DBusConnection, and finalizes
884  * it if the count reaches zero.  It is a bug to drop the last reference
885  * to a connection that has not been disconnected.
886  *
887  * @param connection the connection.
888  */
889 void
890 dbus_connection_unref (DBusConnection *connection)
891 {
892   dbus_bool_t last_unref;
893   
894   dbus_mutex_lock (connection->mutex);
895   
896   _dbus_assert (connection != NULL);
897   _dbus_assert (connection->refcount > 0);
898
899   connection->refcount -= 1;
900   last_unref = (connection->refcount == 0);
901
902   dbus_mutex_unlock (connection->mutex);
903
904   if (last_unref)
905     _dbus_connection_last_unref (connection);
906 }
907
908 /**
909  * Closes the connection, so no further data can be sent or received.
910  * Any further attempts to send data will result in errors.  This
911  * function does not affect the connection's reference count.  It's
912  * safe to disconnect a connection more than once; all calls after the
913  * first do nothing. It's impossible to "reconnect" a connection, a
914  * new connection must be created.
915  *
916  * @param connection the connection.
917  */
918 void
919 dbus_connection_disconnect (DBusConnection *connection)
920 {
921   dbus_mutex_lock (connection->mutex);
922   _dbus_transport_disconnect (connection->transport);
923   dbus_mutex_unlock (connection->mutex);
924 }
925
926 /**
927  * Gets whether the connection is currently connected.  All
928  * connections are connected when they are opened.  A connection may
929  * become disconnected when the remote application closes its end, or
930  * exits; a connection may also be disconnected with
931  * dbus_connection_disconnect().
932  *
933  * @param connection the connection.
934  * @returns #TRUE if the connection is still alive.
935  */
936 dbus_bool_t
937 dbus_connection_get_is_connected (DBusConnection *connection)
938 {
939   dbus_bool_t res;
940   
941   dbus_mutex_lock (connection->mutex);
942   res = _dbus_transport_get_is_connected (connection->transport);
943   dbus_mutex_unlock (connection->mutex);
944   
945   return res;
946 }
947
948 /**
949  * Gets whether the connection was authenticated. (Note that
950  * if the connection was authenticated then disconnected,
951  * this function still returns #TRUE)
952  *
953  * @param connection the connection
954  * @returns #TRUE if the connection was ever authenticated
955  */
956 dbus_bool_t
957 dbus_connection_get_is_authenticated (DBusConnection *connection)
958 {
959   dbus_bool_t res;
960   
961   dbus_mutex_lock (connection->mutex);
962   res = _dbus_transport_get_is_authenticated (connection->transport);
963   dbus_mutex_unlock (connection->mutex);
964   
965   return res;
966 }
967
968 /**
969  * Preallocates resources needed to send a message, allowing the message 
970  * to be sent without the possibility of memory allocation failure.
971  * Allows apps to create a future guarantee that they can send
972  * a message regardless of memory shortages.
973  *
974  * @param connection the connection we're preallocating for.
975  * @returns the preallocated resources, or #NULL
976  */
977 DBusPreallocatedSend*
978 dbus_connection_preallocate_send (DBusConnection *connection)
979 {
980   /* we store "connection" in the link just to enforce via
981    * assertion that preallocated links are only used
982    * with the connection they were created for.
983    */
984   return (DBusPreallocatedSend*) _dbus_list_alloc_link (connection);
985 }
986
987 /**
988  * Frees preallocated message-sending resources from
989  * dbus_connection_preallocate_send(). Should only
990  * be called if the preallocated resources are not used
991  * to send a message.
992  *
993  * @param connection the connection
994  * @param preallocated the resources
995  */
996 void
997 dbus_connection_free_preallocated_send (DBusConnection       *connection,
998                                         DBusPreallocatedSend *preallocated)
999 {
1000   DBusList *link = (DBusList*) preallocated;
1001   _dbus_assert (link->data == connection);
1002   _dbus_list_free_link (link);
1003 }
1004
1005 /**
1006  * Sends a message using preallocated resources. This function cannot fail.
1007  * It works identically to dbus_connection_send() in other respects.
1008  * Preallocated resources comes from dbus_connection_preallocate_send().
1009  * This function "consumes" the preallocated resources, they need not
1010  * be freed separately.
1011  *
1012  * @param connection the connection
1013  * @param preallocated the preallocated resources
1014  * @param message the message to send
1015  * @param client_serial return location for client serial assigned to the message
1016  */
1017 void
1018 dbus_connection_send_preallocated (DBusConnection       *connection,
1019                                    DBusPreallocatedSend *preallocated,
1020                                    DBusMessage          *message,
1021                                    dbus_int32_t         *client_serial)
1022 {
1023   DBusList *link = (DBusList*) preallocated;
1024   dbus_int32_t serial;
1025   
1026   _dbus_assert (link->data == connection);
1027   _dbus_assert (dbus_message_get_name (message) != NULL);
1028   
1029   dbus_mutex_lock (connection->mutex);
1030
1031   link->data = message;
1032   _dbus_list_prepend_link (&connection->outgoing_messages,
1033                            link);
1034
1035   dbus_message_ref (message);
1036   connection->n_outgoing += 1;
1037
1038   _dbus_verbose ("Message %p (%s) added to outgoing queue, %d pending to send\n",
1039                  message,
1040                  dbus_message_get_name (message),
1041                  connection->n_outgoing);
1042
1043   if (dbus_message_get_serial (message) == -1)
1044     {
1045       serial = _dbus_connection_get_next_client_serial (connection);
1046       _dbus_message_set_serial (message, serial);
1047     }
1048   
1049   if (client_serial)
1050     *client_serial = dbus_message_get_serial (message);
1051   
1052   _dbus_message_lock (message);
1053
1054   if (connection->n_outgoing == 1)
1055     _dbus_transport_messages_pending (connection->transport,
1056                                       connection->n_outgoing);
1057   
1058   _dbus_connection_wakeup_mainloop (connection);
1059
1060   dbus_mutex_unlock (connection->mutex);
1061 }
1062
1063 /**
1064  * Adds a message to the outgoing message queue. Does not block to
1065  * write the message to the network; that happens asynchronously. To
1066  * force the message to be written, call dbus_connection_flush().
1067  * Because this only queues the message, the only reason it can
1068  * fail is lack of memory. Even if the connection is disconnected,
1069  * no error will be returned.
1070  *
1071  * If the function fails, it returns #FALSE and returns the
1072  * reason for failure via the result parameter.
1073  * The result parameter can be #NULL if you aren't interested
1074  * in the reason for the failure.
1075  * 
1076  * @param connection the connection.
1077  * @param message the message to write.
1078  * @param client_serial return location for client serial.
1079  * @returns #TRUE on success.
1080  */
1081 dbus_bool_t
1082 dbus_connection_send (DBusConnection *connection,
1083                       DBusMessage    *message,
1084                       dbus_int32_t   *client_serial)
1085 {
1086   DBusPreallocatedSend *preallocated;
1087
1088   preallocated = dbus_connection_preallocate_send (connection);
1089   if (preallocated == NULL)
1090     {
1091       return FALSE;
1092     }
1093   else
1094     {
1095       dbus_connection_send_preallocated (connection, preallocated, message, client_serial);
1096       return TRUE;
1097     }
1098 }
1099
1100 static void
1101 reply_handler_timeout (void *data)
1102 {
1103   DBusConnection *connection;
1104   ReplyHandlerData *reply_handler_data = data;
1105
1106   connection = reply_handler_data->connection;
1107   
1108   dbus_mutex_lock (connection->mutex);
1109   if (reply_handler_data->timeout_link)
1110     {
1111       _dbus_connection_queue_synthesized_message_link (connection,
1112                                                        reply_handler_data->timeout_link);
1113       reply_handler_data->timeout_link = NULL;
1114     }
1115
1116   _dbus_connection_remove_timeout (connection,
1117                                    reply_handler_data->timeout);
1118   reply_handler_data->timeout_added = FALSE;
1119   
1120   dbus_mutex_unlock (connection->mutex);
1121 }
1122
1123 static void
1124 reply_handler_data_free (ReplyHandlerData *data)
1125 {
1126   if (!data)
1127     return;
1128
1129   if (data->timeout_added)
1130     _dbus_connection_remove_timeout_locked (data->connection,
1131                                             data->timeout);
1132
1133   if (data->connection_added)
1134     _dbus_message_handler_remove_connection (data->handler,
1135                                              data->connection);
1136
1137   if (data->timeout_link)
1138     {
1139       dbus_message_unref ((DBusMessage *)data->timeout_link->data);
1140       _dbus_list_free_link (data->timeout_link);
1141     }
1142   
1143   dbus_message_handler_unref (data->handler);
1144   
1145   dbus_free (data);
1146 }
1147
1148 /**
1149  * Queues a message to send, as with dbus_connection_send_message(),
1150  * but also sets up a DBusMessageHandler to receive a reply to the
1151  * message. If no reply is received in the given timeout_milliseconds,
1152  * expires the pending reply and sends the DBusMessageHandler a
1153  * synthetic error reply (generated in-process, not by the remote
1154  * application) indicating that a timeout occurred.
1155  *
1156  * Reply handlers see their replies after message filters see them,
1157  * but before message handlers added with
1158  * dbus_connection_register_handler() see them, regardless of the
1159  * reply message's name. Reply handlers are only handed a single
1160  * message as a reply, after one reply has been seen the handler is
1161  * removed. If a filter filters out the reply before the handler sees
1162  * it, the reply is immediately timed out and a timeout error reply is
1163  * generated. If a filter removes the timeout error reply then the
1164  * reply handler will never be called. Filters should not do this.
1165  * 
1166  * If #NULL is passed for the reply_handler, the timeout reply will
1167  * still be generated and placed into the message queue, but no
1168  * specific message handler will receive the reply.
1169  *
1170  * If -1 is passed for the timeout, a sane default timeout is used. -1
1171  * is typically the best value for the timeout for this reason, unless
1172  * you want a very short or very long timeout.  There is no way to
1173  * avoid a timeout entirely, other than passing INT_MAX for the
1174  * timeout to postpone it indefinitely.
1175  * 
1176  * @param connection the connection
1177  * @param message the message to send
1178  * @param reply_handler message handler expecting the reply, or #NULL
1179  * @param timeout_milliseconds timeout in milliseconds or -1 for default
1180  * @returns #TRUE if the message is successfully queued, #FALSE if no memory.
1181  *
1182  */
1183 dbus_bool_t
1184 dbus_connection_send_with_reply (DBusConnection     *connection,
1185                                  DBusMessage        *message,
1186                                  DBusMessageHandler *reply_handler,
1187                                  int                 timeout_milliseconds)
1188 {
1189   DBusTimeout *timeout;
1190   ReplyHandlerData *data;
1191   DBusMessage *reply;
1192   DBusList *reply_link;
1193   dbus_int32_t serial = -1;
1194   
1195   if (timeout_milliseconds == -1)
1196     timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1197
1198   data = dbus_new0 (ReplyHandlerData, 1);
1199
1200   if (!data)
1201     return FALSE;
1202   
1203   timeout = _dbus_timeout_new (timeout_milliseconds, reply_handler_timeout,
1204                                data, NULL);
1205
1206   if (!timeout)
1207     {
1208       reply_handler_data_free (data);
1209       return FALSE;
1210     }
1211
1212   dbus_mutex_lock (connection->mutex);
1213   
1214   /* Add timeout */
1215   if (!_dbus_connection_add_timeout (connection, timeout))
1216     {
1217       reply_handler_data_free (data);
1218       _dbus_timeout_unref (timeout);
1219       dbus_mutex_unlock (connection->mutex);
1220       return FALSE;
1221     }
1222
1223   /* The connection now owns the reference to the timeout. */
1224   _dbus_timeout_unref (timeout);
1225   
1226   data->timeout_added = TRUE;
1227   data->timeout = timeout;
1228   data->connection = connection;
1229   
1230   if (!_dbus_message_handler_add_connection (reply_handler, connection))
1231     {
1232       dbus_mutex_unlock (connection->mutex);
1233       reply_handler_data_free (data);
1234       return FALSE;
1235     }
1236   data->connection_added = TRUE;
1237   
1238   /* Assign a serial to the message */
1239   if (dbus_message_get_serial (message) == -1)
1240     {
1241       serial = _dbus_connection_get_next_client_serial (connection);
1242       _dbus_message_set_serial (message, serial);
1243     }
1244
1245   data->handler = reply_handler;
1246   data->serial = serial;
1247
1248   dbus_message_handler_ref (reply_handler);
1249
1250   reply = dbus_message_new_error_reply (message, DBUS_ERROR_NO_REPLY,
1251                                         "No reply within specified time");
1252   if (!reply)
1253     {
1254       dbus_mutex_unlock (connection->mutex);
1255       reply_handler_data_free (data);
1256       return FALSE;
1257     }
1258
1259   reply_link = _dbus_list_alloc_link (reply);
1260   if (!reply)
1261     {
1262       dbus_mutex_unlock (connection->mutex);
1263       dbus_message_unref (reply);
1264       reply_handler_data_free (data);
1265       return FALSE;
1266     }
1267
1268   data->timeout_link = reply_link;
1269   
1270   /* Insert the serial in the pending replies hash. */
1271   if (!_dbus_hash_table_insert_int (connection->pending_replies, serial, data))
1272     {
1273       dbus_mutex_unlock (connection->mutex);
1274       reply_handler_data_free (data);      
1275       return FALSE;
1276     }
1277
1278   dbus_mutex_unlock (connection->mutex);
1279   
1280   if (!dbus_connection_send (connection, message, NULL))
1281     {
1282       /* This will free the handler data too */
1283       _dbus_hash_table_remove_int (connection->pending_replies, serial);
1284       return FALSE;
1285     }
1286
1287   return TRUE;
1288 }
1289
1290 /**
1291  * Sends a message and blocks a certain time period while waiting for a reply.
1292  * This function does not dispatch any message handlers until the main loop
1293  * has been reached. This function is used to do non-reentrant "method calls."
1294  * If a reply is received, it is returned, and removed from the incoming
1295  * message queue. If it is not received, #NULL is returned and the
1296  * error is set to #DBUS_ERROR_NO_REPLY. If something else goes
1297  * wrong, result is set to whatever is appropriate, such as
1298  * #DBUS_ERROR_NO_MEMORY or #DBUS_ERROR_DISCONNECTED.
1299  *
1300  * @todo could use performance improvements (it keeps scanning
1301  * the whole message queue for example) and has thread issues,
1302  * see comments in source
1303  *
1304  * @param connection the connection
1305  * @param message the message to send
1306  * @param timeout_milliseconds timeout in milliseconds or -1 for default
1307  * @param error return location for error message
1308  * @returns the message that is the reply or #NULL with an error code if the
1309  * function fails.
1310  */
1311 DBusMessage *
1312 dbus_connection_send_with_reply_and_block (DBusConnection     *connection,
1313                                            DBusMessage        *message,
1314                                            int                 timeout_milliseconds,
1315                                            DBusError          *error)
1316 {
1317   dbus_int32_t client_serial;
1318   DBusList *link;
1319   long start_tv_sec, start_tv_usec;
1320   long end_tv_sec, end_tv_usec;
1321   long tv_sec, tv_usec;
1322
1323   if (timeout_milliseconds == -1)
1324     timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1325
1326   /* it would probably seem logical to pass in _DBUS_INT_MAX
1327    * for infinite timeout, but then math below would get
1328    * all overflow-prone, so smack that down.
1329    */
1330   if (timeout_milliseconds > _DBUS_ONE_HOUR_IN_MILLISECONDS * 6)
1331     timeout_milliseconds = _DBUS_ONE_HOUR_IN_MILLISECONDS * 6;
1332   
1333   if (!dbus_connection_send (connection, message, &client_serial))
1334     {
1335       _DBUS_SET_OOM (error);
1336       return NULL;
1337     }
1338
1339   message = NULL;
1340   
1341   /* Flush message queue */
1342   dbus_connection_flush (connection);
1343
1344   dbus_mutex_lock (connection->mutex);
1345
1346   _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
1347   end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
1348   end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
1349   end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
1350   end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
1351
1352   _dbus_verbose ("will block %d milliseconds from %ld sec %ld usec to %ld sec %ld usec\n",
1353                  timeout_milliseconds,
1354                  start_tv_sec, start_tv_usec,
1355                  end_tv_sec, end_tv_usec);
1356   
1357   /* Now we wait... */
1358   /* THREAD TODO: This is busted. What if a dispatch_message or pop_message
1359    * gets the message before we do?
1360    */
1361  block_again:  
1362   
1363   _dbus_connection_do_iteration (connection,
1364                                  DBUS_ITERATION_DO_READING |
1365                                  DBUS_ITERATION_BLOCK,
1366                                  timeout_milliseconds);
1367
1368   /* Check if we've gotten a reply */
1369   link = _dbus_list_get_first_link (&connection->incoming_messages);
1370
1371   while (link != NULL)
1372     {
1373       DBusMessage *reply = link->data;
1374
1375       if (dbus_message_get_reply_serial (reply) == client_serial)
1376         {
1377           _dbus_list_remove_link (&connection->incoming_messages, link);
1378           dbus_message_ref (reply);
1379           
1380           dbus_mutex_unlock (connection->mutex);
1381           return reply;
1382         }
1383       link = _dbus_list_get_next_link (&connection->incoming_messages, link);
1384     }
1385
1386   _dbus_get_current_time (&tv_sec, &tv_usec);
1387   
1388   if (tv_sec < start_tv_sec)
1389     ; /* clock set backward, bail out */
1390   else if (connection->disconnect_message_link == NULL)
1391     ; /* we're disconnected, bail out */
1392   else if (tv_sec < end_tv_sec ||
1393            (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
1394     {
1395       timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
1396         (end_tv_usec - tv_usec) / 1000;
1397       _dbus_verbose ("%d milliseconds remain\n", timeout_milliseconds);
1398       _dbus_assert (timeout_milliseconds > 0);
1399       
1400       goto block_again; /* not expired yet */
1401     }
1402   
1403   if (dbus_connection_get_is_connected (connection))
1404     dbus_set_error (error, DBUS_ERROR_NO_REPLY, "Message did not receive a reply");
1405   else
1406     dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Disconnected prior to receiving a reply");
1407
1408   dbus_mutex_unlock (connection->mutex);
1409
1410   return NULL;
1411 }
1412
1413 /**
1414  * Blocks until the outgoing message queue is empty.
1415  *
1416  * @param connection the connection.
1417  */
1418 void
1419 dbus_connection_flush (DBusConnection *connection)
1420 {
1421   /* We have to specify DBUS_ITERATION_DO_READING here
1422    * because otherwise we could have two apps deadlock
1423    * if they are both doing a flush(), and the kernel
1424    * buffers fill up.
1425    */
1426   
1427   dbus_mutex_lock (connection->mutex);
1428   while (connection->n_outgoing > 0)
1429     _dbus_connection_do_iteration (connection,
1430                                    DBUS_ITERATION_DO_READING |
1431                                    DBUS_ITERATION_DO_WRITING |
1432                                    DBUS_ITERATION_BLOCK,
1433                                    -1);
1434   dbus_mutex_unlock (connection->mutex);
1435 }
1436
1437 /**
1438  * Gets the number of messages in the incoming message queue.
1439  *
1440  * @param connection the connection.
1441  * @returns the number of messages in the queue.
1442  */
1443 int
1444 dbus_connection_get_n_messages (DBusConnection *connection)
1445 {
1446   int res;
1447
1448   dbus_mutex_lock (connection->mutex);
1449   res = connection->n_incoming;
1450   dbus_mutex_unlock (connection->mutex);
1451   return res;
1452 }
1453
1454
1455 /* Call with mutex held. Will drop it while waiting and re-acquire
1456  * before returning
1457  */
1458 static void
1459 _dbus_connection_wait_for_borrowed (DBusConnection *connection)
1460 {
1461   _dbus_assert (connection->message_borrowed != NULL);
1462
1463   while (connection->message_borrowed != NULL)
1464     dbus_condvar_wait (connection->message_returned_cond, connection->mutex);
1465 }
1466
1467 /**
1468  * Returns the first-received message from the incoming message queue,
1469  * leaving it in the queue. If the queue is empty, returns #NULL.
1470  * 
1471  * The caller does not own a reference to the returned message, and must
1472  * either return it using dbus_connection_return_message or keep it after
1473  * calling dbus_connection_steal_borrowed_message. No one can get at the
1474  * message while its borrowed, so return it as quickly as possible and
1475  * don't keep a reference to it after returning it. If you need to keep
1476  * the message, make a copy of it.
1477  *
1478  * @param connection the connection.
1479  * @returns next message in the incoming queue.
1480  */
1481 DBusMessage*
1482 dbus_connection_borrow_message  (DBusConnection *connection)
1483 {
1484   DBusMessage *message;
1485
1486   dbus_mutex_lock (connection->mutex);
1487
1488   if (connection->message_borrowed != NULL)
1489     _dbus_connection_wait_for_borrowed (connection);
1490   
1491   message = _dbus_list_get_first (&connection->incoming_messages);
1492
1493   if (message) 
1494     connection->message_borrowed = message;
1495   
1496   dbus_mutex_unlock (connection->mutex);
1497   return message;
1498 }
1499
1500 /**
1501  * @todo docs
1502  */
1503 void
1504 dbus_connection_return_message (DBusConnection *connection,
1505                                 DBusMessage    *message)
1506 {
1507   dbus_mutex_lock (connection->mutex);
1508   
1509   _dbus_assert (message == connection->message_borrowed);
1510   
1511   connection->message_borrowed = NULL;
1512   dbus_condvar_wake_all (connection->message_returned_cond);
1513   
1514   dbus_mutex_unlock (connection->mutex);
1515 }
1516
1517 /**
1518  * @todo docs
1519  */
1520 void
1521 dbus_connection_steal_borrowed_message (DBusConnection *connection,
1522                                         DBusMessage    *message)
1523 {
1524   DBusMessage *pop_message;
1525   
1526   dbus_mutex_lock (connection->mutex);
1527  
1528   _dbus_assert (message == connection->message_borrowed);
1529
1530   pop_message = _dbus_list_pop_first (&connection->incoming_messages);
1531   _dbus_assert (message == pop_message);
1532   
1533   connection->n_incoming -= 1;
1534  
1535   _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
1536                  message, connection->n_incoming);
1537  
1538   connection->message_borrowed = NULL;
1539   dbus_condvar_wake_all (connection->message_returned_cond);
1540   
1541   dbus_mutex_unlock (connection->mutex);
1542 }
1543
1544
1545 /* See dbus_connection_pop_message, but requires the caller to own
1546  * the lock before calling. May drop the lock while running.
1547  */
1548 static DBusMessage*
1549 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
1550 {
1551   if (connection->message_borrowed != NULL)
1552     _dbus_connection_wait_for_borrowed (connection);
1553   
1554   if (connection->n_incoming > 0)
1555     {
1556       DBusMessage *message;
1557
1558       message = _dbus_list_pop_first (&connection->incoming_messages);
1559       connection->n_incoming -= 1;
1560
1561       _dbus_verbose ("Incoming message %p removed from queue, %d incoming\n",
1562                      message, connection->n_incoming);
1563
1564       return message;
1565     }
1566   else
1567     return NULL;
1568 }
1569
1570
1571 /**
1572  * Returns the first-received message from the incoming message queue,
1573  * removing it from the queue. The caller owns a reference to the
1574  * returned message. If the queue is empty, returns #NULL.
1575  *
1576  * @param connection the connection.
1577  * @returns next message in the incoming queue.
1578  */
1579 DBusMessage*
1580 dbus_connection_pop_message (DBusConnection *connection)
1581 {
1582   DBusMessage *message;
1583   dbus_mutex_lock (connection->mutex);
1584
1585   message = _dbus_connection_pop_message_unlocked (connection);
1586   
1587   dbus_mutex_unlock (connection->mutex);
1588   
1589   return message;
1590 }
1591
1592 /**
1593  * Acquire the dispatcher. This must be done before dispatching
1594  * messages in order to guarantee the right order of
1595  * message delivery. May sleep and drop the connection mutex
1596  * while waiting for the dispatcher.
1597  *
1598  * @param connection the connection.
1599  */
1600 static void
1601 _dbus_connection_acquire_dispatch (DBusConnection *connection)
1602 {
1603   if (connection->dispatch_acquired)
1604     dbus_condvar_wait (connection->dispatch_cond, connection->mutex);
1605   _dbus_assert (!connection->dispatch_acquired);
1606
1607   connection->dispatch_acquired = TRUE;
1608 }
1609
1610 /**
1611  * Release the dispatcher when you're done with it. Only call
1612  * after you've acquired the dispatcher. Wakes up at most one
1613  * thread currently waiting to acquire the dispatcher.
1614  *
1615  * @param connection the connection.
1616  */
1617 static void
1618 _dbus_connection_release_dispatch (DBusConnection *connection)
1619 {
1620   _dbus_assert (connection->dispatch_acquired);
1621
1622   connection->dispatch_acquired = FALSE;
1623   dbus_condvar_wake_one (connection->dispatch_cond);
1624 }
1625
1626 static void
1627 _dbus_connection_failed_pop (DBusConnection *connection,
1628                              DBusList *message_link)
1629 {
1630   _dbus_list_prepend_link (&connection->incoming_messages,
1631                            message_link);
1632   connection->n_incoming += 1;
1633 }
1634
1635 /**
1636  * Pops the first-received message from the current incoming message
1637  * queue, runs any handlers for it, then unrefs the message.
1638  *
1639  * @param connection the connection
1640  * @returns #TRUE if the queue is not empty after dispatch
1641  */
1642 dbus_bool_t
1643 dbus_connection_dispatch_message (DBusConnection *connection)
1644 {
1645   DBusMessageHandler *handler;
1646   DBusMessage *message;
1647   DBusList *link, *filter_list_copy, *message_link;
1648   DBusHandlerResult result;
1649   ReplyHandlerData *reply_handler_data;
1650   const char *name;
1651   dbus_int32_t reply_serial;
1652
1653   /* Preallocate link so we can put the message back on failure */
1654   message_link = _dbus_list_alloc_link (NULL);
1655   if (message_link == NULL)
1656     return FALSE;
1657   
1658   dbus_mutex_lock (connection->mutex);
1659
1660   /* We need to ref the connection since the callback could potentially
1661    * drop the last ref to it */
1662   _dbus_connection_ref_unlocked (connection);
1663
1664   _dbus_connection_acquire_dispatch (connection);
1665   
1666   /* This call may drop the lock during the execution (if waiting for
1667    * borrowed messages to be returned) but the order of message
1668    * dispatch if several threads call dispatch_message is still
1669    * protected by the lock, since only one will get the lock, and that
1670    * one will finish the message dispatching
1671    */
1672   message = _dbus_connection_pop_message_unlocked (connection);
1673   if (message == NULL)
1674     {
1675       _dbus_connection_release_dispatch (connection);
1676       dbus_mutex_unlock (connection->mutex);
1677       dbus_connection_unref (connection);
1678       return FALSE;
1679     }
1680   
1681   message_link->data = message;
1682   
1683   result = DBUS_HANDLER_RESULT_ALLOW_MORE_HANDLERS;
1684
1685   reply_serial = dbus_message_get_reply_serial (message);
1686   reply_handler_data = _dbus_hash_table_lookup_int (connection->pending_replies,
1687                                                     reply_serial);
1688   
1689   if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
1690     {
1691       _dbus_connection_release_dispatch (connection);
1692       dbus_mutex_unlock (connection->mutex);
1693       _dbus_connection_failed_pop (connection, message_link);
1694       dbus_connection_unref (connection);
1695       return FALSE;
1696     }
1697   
1698   _dbus_list_foreach (&filter_list_copy,
1699                       (DBusForeachFunction)dbus_message_handler_ref,
1700                       NULL);
1701
1702   /* We're still protected from dispatch_message reentrancy here
1703    * since we acquired the dispatcher
1704    */
1705   dbus_mutex_unlock (connection->mutex);
1706   
1707   link = _dbus_list_get_first_link (&filter_list_copy);
1708   while (link != NULL)
1709     {
1710       DBusMessageHandler *handler = link->data;
1711       DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
1712
1713       result = _dbus_message_handler_handle_message (handler, connection,
1714                                                      message);
1715
1716       if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1717         break;
1718
1719       link = next;
1720     }
1721
1722   _dbus_list_foreach (&filter_list_copy,
1723                       (DBusForeachFunction)dbus_message_handler_unref,
1724                       NULL);
1725   _dbus_list_clear (&filter_list_copy);
1726   
1727   dbus_mutex_lock (connection->mutex);
1728
1729   /* Did a reply we were waiting on get filtered? */
1730   if (reply_handler_data && result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1731     {
1732       /* Queue the timeout immediately! */
1733       if (reply_handler_data->timeout_link)
1734         {
1735           _dbus_connection_queue_synthesized_message_link (connection,
1736                                                            reply_handler_data->timeout_link);
1737           reply_handler_data->timeout_link = NULL;
1738         }
1739       else
1740         {
1741           /* We already queued the timeout? Then it was filtered! */
1742           _dbus_warn ("The timeout error with reply serial %d was filtered, so the reply handler will never be called.\n", reply_serial);
1743         }
1744     }
1745   
1746   if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1747     goto out;
1748
1749   if (reply_handler_data)
1750     {
1751       dbus_mutex_unlock (connection->mutex);
1752       result = _dbus_message_handler_handle_message (reply_handler_data->handler,
1753                                                      connection, message);
1754       reply_handler_data_free (reply_handler_data);
1755       dbus_mutex_lock (connection->mutex);
1756       goto out;
1757     }
1758   
1759   name = dbus_message_get_name (message);
1760   if (name != NULL)
1761     {
1762       handler = _dbus_hash_table_lookup_string (connection->handler_table,
1763                                                 name);
1764       if (handler != NULL)
1765         {
1766           /* We're still protected from dispatch_message reentrancy here
1767            * since we acquired the dispatcher */
1768           dbus_mutex_unlock (connection->mutex);
1769           result = _dbus_message_handler_handle_message (handler, connection,
1770                                                          message);
1771           dbus_mutex_lock (connection->mutex);
1772           if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1773             goto out;
1774         }
1775     }
1776
1777  out:
1778   _dbus_connection_release_dispatch (connection);
1779   dbus_mutex_unlock (connection->mutex);
1780   _dbus_list_free_link (message_link);
1781   dbus_connection_unref (connection);
1782   dbus_message_unref (message);
1783   
1784   return connection->n_incoming > 0;
1785 }
1786
1787 /**
1788  * Sets the watch functions for the connection. These functions are
1789  * responsible for making the application's main loop aware of file
1790  * descriptors that need to be monitored for events, using select() or
1791  * poll(). When using Qt, typically the DBusAddWatchFunction would
1792  * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
1793  * could call g_io_add_watch(), or could be used as part of a more
1794  * elaborate GSource.
1795  *
1796  * The DBusWatch can be queried for the file descriptor to watch using
1797  * dbus_watch_get_fd(), and for the events to watch for using
1798  * dbus_watch_get_flags(). The flags returned by
1799  * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
1800  * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
1801  * all watches implicitly include a watch for hangups, errors, and
1802  * other exceptional conditions.
1803  *
1804  * Once a file descriptor becomes readable or writable, or an exception
1805  * occurs, dbus_connection_handle_watch() should be called to
1806  * notify the connection of the file descriptor's condition.
1807  *
1808  * dbus_connection_handle_watch() cannot be called during the
1809  * DBusAddWatchFunction, as the connection will not be ready to handle
1810  * that watch yet.
1811  * 
1812  * It is not allowed to reference a DBusWatch after it has been passed
1813  * to remove_function.
1814  *
1815  * If #FALSE is returned due to lack of memory, the failure may be due
1816  * to a #FALSE return from the new add_function. If so, the
1817  * add_function may have been called successfully one or more times,
1818  * but the remove_function will also have been called to remove any
1819  * successful adds. i.e. if #FALSE is returned the net result
1820  * should be that dbus_connection_set_watch_functions() has no effect,
1821  * but the add_function and remove_function may have been called.
1822  * 
1823  * @param connection the connection.
1824  * @param add_function function to begin monitoring a new descriptor.
1825  * @param remove_function function to stop monitoring a descriptor.
1826  * @param data data to pass to add_function and remove_function.
1827  * @param free_data_function function to be called to free the data.
1828  * @returns #FALSE on failure (no memory)
1829  */
1830 dbus_bool_t
1831 dbus_connection_set_watch_functions (DBusConnection              *connection,
1832                                      DBusAddWatchFunction         add_function,
1833                                      DBusRemoveWatchFunction      remove_function,
1834                                      void                        *data,
1835                                      DBusFreeFunction             free_data_function)
1836 {
1837   dbus_bool_t retval;
1838   
1839   dbus_mutex_lock (connection->mutex);
1840   /* ref connection for slightly better reentrancy */
1841   _dbus_connection_ref_unlocked (connection);
1842   
1843   retval = _dbus_watch_list_set_functions (connection->watches,
1844                                            add_function, remove_function,
1845                                            data, free_data_function);
1846   
1847   dbus_mutex_unlock (connection->mutex);
1848   /* drop our paranoid refcount */
1849   dbus_connection_unref (connection);
1850
1851   return retval;
1852 }
1853
1854 /**
1855  * Sets the timeout functions for the connection. These functions are
1856  * responsible for making the application's main loop aware of timeouts.
1857  * When using Qt, typically the DBusAddTimeoutFunction would create a
1858  * QTimer. When using GLib, the DBusAddTimeoutFunction would call
1859  * g_timeout_add.
1860  *
1861  * The DBusTimeout can be queried for the timer interval using
1862  * dbus_timeout_get_interval.
1863  *
1864  * Once a timeout occurs, dbus_timeout_handle should be called to invoke
1865  * the timeout's callback, and the timeout should be automatically
1866  * removed. i.e. timeouts are one-shot.
1867  *
1868  * @param connection the connection.
1869  * @param add_function function to add a timeout.
1870  * @param remove_function function to remove a timeout.
1871  * @param data data to pass to add_function and remove_function.
1872  * @param free_data_function function to be called to free the data.
1873  * @returns #FALSE on failure (no memory)
1874  */
1875 dbus_bool_t
1876 dbus_connection_set_timeout_functions   (DBusConnection            *connection,
1877                                          DBusAddTimeoutFunction     add_function,
1878                                          DBusRemoveTimeoutFunction  remove_function,
1879                                          void                      *data,
1880                                          DBusFreeFunction           free_data_function)
1881 {
1882   dbus_bool_t retval;
1883   
1884   dbus_mutex_lock (connection->mutex);
1885   /* ref connection for slightly better reentrancy */
1886   _dbus_connection_ref_unlocked (connection);
1887   
1888   retval = _dbus_timeout_list_set_functions (connection->timeouts,
1889                                              add_function, remove_function,
1890                                              data, free_data_function);
1891   
1892   dbus_mutex_unlock (connection->mutex);
1893   /* drop our paranoid refcount */
1894   dbus_connection_unref (connection);
1895
1896   return retval;
1897 }
1898
1899 /**
1900  * Sets the mainloop wakeup function for the connection. Thi function is
1901  * responsible for waking up the main loop (if its sleeping) when some some
1902  * change has happened to the connection that the mainloop needs to reconsiders
1903  * (e.g. a message has been queued for writing).
1904  * When using Qt, this typically results in a call to QEventLoop::wakeUp().
1905  * When using GLib, it would call g_main_context_wakeup().
1906  *
1907  *
1908  * @param connection the connection.
1909  * @param wakeup_main_function function to wake up the mainloop
1910  * @param data data to pass wakeup_main_function
1911  * @param free_data_function function to be called to free the data.
1912  */
1913 void
1914 dbus_connection_set_wakeup_main_function (DBusConnection            *connection,
1915                                           DBusWakeupMainFunction     wakeup_main_function,
1916                                           void                      *data,
1917                                           DBusFreeFunction           free_data_function)
1918 {
1919   void *old_data;
1920   DBusFreeFunction old_free_data;
1921   
1922   dbus_mutex_lock (connection->mutex);
1923   old_data = connection->wakeup_main_data;
1924   old_free_data = connection->free_wakeup_main_data;
1925
1926   connection->wakeup_main_function = wakeup_main_function;
1927   connection->wakeup_main_data = data;
1928   connection->free_wakeup_main_data = free_data_function;
1929   
1930   dbus_mutex_unlock (connection->mutex);
1931
1932   /* Callback outside the lock */
1933   if (old_free_data)
1934     (*old_free_data) (old_data);
1935 }
1936
1937 /**
1938  * Called to notify the connection when a previously-added watch
1939  * is ready for reading or writing, or has an exception such
1940  * as a hangup.
1941  *
1942  * @param connection the connection.
1943  * @param watch the watch.
1944  * @param condition the current condition of the file descriptors being watched.
1945  */
1946 void
1947 dbus_connection_handle_watch (DBusConnection              *connection,
1948                               DBusWatch                   *watch,
1949                               unsigned int                 condition)
1950 {
1951   dbus_mutex_lock (connection->mutex);
1952   _dbus_connection_acquire_io_path (connection, -1);
1953   _dbus_transport_handle_watch (connection->transport,
1954                                 watch, condition);
1955   _dbus_connection_release_io_path (connection);
1956   dbus_mutex_unlock (connection->mutex);
1957 }
1958
1959 /**
1960  * Adds a message filter. Filters are handlers that are run on
1961  * all incoming messages, prior to the normal handlers
1962  * registered with dbus_connection_register_handler().
1963  * Filters are run in the order that they were added.
1964  * The same handler can be added as a filter more than once, in
1965  * which case it will be run more than once.
1966  * Filters added during a filter callback won't be run on the
1967  * message being processed.
1968  *
1969  * @param connection the connection
1970  * @param handler the handler
1971  * @returns #TRUE on success, #FALSE if not enough memory.
1972  */
1973 dbus_bool_t
1974 dbus_connection_add_filter (DBusConnection      *connection,
1975                             DBusMessageHandler  *handler)
1976 {
1977   dbus_mutex_lock (connection->mutex);
1978   if (!_dbus_message_handler_add_connection (handler, connection))
1979     {
1980       dbus_mutex_unlock (connection->mutex);
1981       return FALSE;
1982     }
1983
1984   if (!_dbus_list_append (&connection->filter_list,
1985                           handler))
1986     {
1987       _dbus_message_handler_remove_connection (handler, connection);
1988       dbus_mutex_unlock (connection->mutex);
1989       return FALSE;
1990     }
1991
1992   dbus_mutex_unlock (connection->mutex);
1993   return TRUE;
1994 }
1995
1996 /**
1997  * Removes a previously-added message filter. It is a programming
1998  * error to call this function for a handler that has not
1999  * been added as a filter. If the given handler was added
2000  * more than once, only one instance of it will be removed
2001  * (the most recently-added instance).
2002  *
2003  * @param connection the connection
2004  * @param handler the handler to remove
2005  *
2006  */
2007 void
2008 dbus_connection_remove_filter (DBusConnection      *connection,
2009                                DBusMessageHandler  *handler)
2010 {
2011   dbus_mutex_lock (connection->mutex);
2012   if (!_dbus_list_remove_last (&connection->filter_list, handler))
2013     {
2014       _dbus_warn ("Tried to remove a DBusConnection filter that had not been added\n");
2015       dbus_mutex_unlock (connection->mutex);
2016       return;
2017     }
2018
2019   _dbus_message_handler_remove_connection (handler, connection);
2020
2021   dbus_mutex_unlock (connection->mutex);
2022 }
2023
2024 /**
2025  * Registers a handler for a list of message names. A single handler
2026  * can be registered for any number of message names, but each message
2027  * name can only have one handler at a time. It's not allowed to call
2028  * this function with the name of a message that already has a
2029  * handler. If the function returns #FALSE, the handlers were not
2030  * registered due to lack of memory.
2031  *
2032  * @todo the messages_to_handle arg may be more convenient if it's a
2033  * single string instead of an array. Though right now MessageHandler
2034  * is sort of designed to say be associated with an entire object with
2035  * multiple methods, that's why for example the connection only
2036  * weakrefs it.  So maybe the "manual" API should be different.
2037  * 
2038  * @param connection the connection
2039  * @param handler the handler
2040  * @param messages_to_handle the messages to handle
2041  * @param n_messages the number of message names in messages_to_handle
2042  * @returns #TRUE on success, #FALSE if no memory or another handler already exists
2043  * 
2044  **/
2045 dbus_bool_t
2046 dbus_connection_register_handler (DBusConnection     *connection,
2047                                   DBusMessageHandler *handler,
2048                                   const char        **messages_to_handle,
2049                                   int                 n_messages)
2050 {
2051   int i;
2052
2053   dbus_mutex_lock (connection->mutex);
2054   i = 0;
2055   while (i < n_messages)
2056     {
2057       DBusHashIter iter;
2058       char *key;
2059
2060       key = _dbus_strdup (messages_to_handle[i]);
2061       if (key == NULL)
2062         goto failed;
2063       
2064       if (!_dbus_hash_iter_lookup (connection->handler_table,
2065                                    key, TRUE,
2066                                    &iter))
2067         {
2068           dbus_free (key);
2069           goto failed;
2070         }
2071
2072       if (_dbus_hash_iter_get_value (&iter) != NULL)
2073         {
2074           _dbus_warn ("Bug in application: attempted to register a second handler for %s\n",
2075                       messages_to_handle[i]);
2076           dbus_free (key); /* won't have replaced the old key with the new one */
2077           goto failed;
2078         }
2079
2080       if (!_dbus_message_handler_add_connection (handler, connection))
2081         {
2082           _dbus_hash_iter_remove_entry (&iter);
2083           /* key has freed on nuking the entry */
2084           goto failed;
2085         }
2086       
2087       _dbus_hash_iter_set_value (&iter, handler);
2088
2089       ++i;
2090     }
2091   
2092   dbus_mutex_unlock (connection->mutex);
2093   return TRUE;
2094   
2095  failed:
2096   /* unregister everything registered so far,
2097    * so we don't fail partially
2098    */
2099   dbus_connection_unregister_handler (connection,
2100                                       handler,
2101                                       messages_to_handle,
2102                                       i);
2103
2104   dbus_mutex_unlock (connection->mutex);
2105   return FALSE;
2106 }
2107
2108 /**
2109  * Unregisters a handler for a list of message names. The handlers
2110  * must have been previously registered.
2111  *
2112  * @param connection the connection
2113  * @param handler the handler
2114  * @param messages_to_handle the messages to handle
2115  * @param n_messages the number of message names in messages_to_handle
2116  * 
2117  **/
2118 void
2119 dbus_connection_unregister_handler (DBusConnection     *connection,
2120                                     DBusMessageHandler *handler,
2121                                     const char        **messages_to_handle,
2122                                     int                 n_messages)
2123 {
2124   int i;
2125
2126   dbus_mutex_lock (connection->mutex);
2127   i = 0;
2128   while (i < n_messages)
2129     {
2130       DBusHashIter iter;
2131
2132       if (!_dbus_hash_iter_lookup (connection->handler_table,
2133                                    (char*) messages_to_handle[i], FALSE,
2134                                    &iter))
2135         {
2136           _dbus_warn ("Bug in application: attempted to unregister handler for %s which was not registered\n",
2137                       messages_to_handle[i]);
2138         }
2139       else if (_dbus_hash_iter_get_value (&iter) != handler)
2140         {
2141           _dbus_warn ("Bug in application: attempted to unregister handler for %s which was registered by a different handler\n",
2142                       messages_to_handle[i]);
2143         }
2144       else
2145         {
2146           _dbus_hash_iter_remove_entry (&iter);
2147           _dbus_message_handler_remove_connection (handler, connection);
2148         }
2149
2150       ++i;
2151     }
2152
2153   dbus_mutex_unlock (connection->mutex);
2154 }
2155
2156 static DBusDataSlotAllocator slot_allocator;
2157
2158 /**
2159  * Initialize the mutex used for #DBusConnection data
2160  * slot reservations.
2161  *
2162  * @returns the mutex
2163  */
2164 DBusMutex *
2165 _dbus_connection_slots_init_lock (void)
2166 {
2167   if (!_dbus_data_slot_allocator_init (&slot_allocator))
2168     return NULL;
2169   else
2170     return slot_allocator.lock;
2171 }
2172
2173 /**
2174  * Allocates an integer ID to be used for storing application-specific
2175  * data on any DBusConnection. The allocated ID may then be used
2176  * with dbus_connection_set_data() and dbus_connection_get_data().
2177  * If allocation fails, -1 is returned. Again, the allocated
2178  * slot is global, i.e. all DBusConnection objects will
2179  * have a slot with the given integer ID reserved.
2180  *
2181  * @returns -1 on failure, otherwise the data slot ID
2182  */
2183 int
2184 dbus_connection_allocate_data_slot (void)
2185 {
2186   return _dbus_data_slot_allocator_alloc (&slot_allocator);
2187 }
2188
2189 /**
2190  * Deallocates a global ID for connection data slots.
2191  * dbus_connection_get_data() and dbus_connection_set_data()
2192  * may no longer be used with this slot.
2193  * Existing data stored on existing DBusConnection objects
2194  * will be freed when the connection is finalized,
2195  * but may not be retrieved (and may only be replaced
2196  * if someone else reallocates the slot).
2197  *
2198  * @param slot the slot to deallocate
2199  */
2200 void
2201 dbus_connection_free_data_slot (int slot)
2202 {
2203   _dbus_data_slot_allocator_free (&slot_allocator, slot);
2204 }
2205
2206 /**
2207  * Stores a pointer on a DBusConnection, along
2208  * with an optional function to be used for freeing
2209  * the data when the data is set again, or when
2210  * the connection is finalized. The slot number
2211  * must have been allocated with dbus_connection_allocate_data_slot().
2212  *
2213  * @param connection the connection
2214  * @param slot the slot number
2215  * @param data the data to store
2216  * @param free_data_func finalizer function for the data
2217  * @returns #TRUE if there was enough memory to store the data
2218  */
2219 dbus_bool_t
2220 dbus_connection_set_data (DBusConnection   *connection,
2221                           int               slot,
2222                           void             *data,
2223                           DBusFreeFunction  free_data_func)
2224 {
2225   DBusFreeFunction old_free_func;
2226   void *old_data;
2227   dbus_bool_t retval;
2228   
2229   dbus_mutex_lock (connection->mutex);
2230
2231   retval = _dbus_data_slot_list_set (&slot_allocator,
2232                                      &connection->slot_list,
2233                                      slot, data, free_data_func,
2234                                      &old_free_func, &old_data);
2235   
2236   dbus_mutex_unlock (connection->mutex);
2237
2238   if (retval)
2239     {
2240       /* Do the actual free outside the connection lock */
2241       if (old_free_func)
2242         (* old_free_func) (old_data);
2243     }
2244
2245   return retval;
2246 }
2247
2248 /**
2249  * Retrieves data previously set with dbus_connection_set_data().
2250  * The slot must still be allocated (must not have been freed).
2251  *
2252  * @param connection the connection
2253  * @param slot the slot to get data from
2254  * @returns the data, or #NULL if not found
2255  */
2256 void*
2257 dbus_connection_get_data (DBusConnection   *connection,
2258                           int               slot)
2259 {
2260   void *res;
2261   
2262   dbus_mutex_lock (connection->mutex);
2263
2264   res = _dbus_data_slot_list_get (&slot_allocator,
2265                                   &connection->slot_list,
2266                                   slot);
2267   
2268   dbus_mutex_unlock (connection->mutex);
2269
2270   return res;
2271 }
2272
2273 /**
2274  * This function sets a global flag for whether dbus_connection_new()
2275  * will set SIGPIPE behavior to SIG_IGN.
2276  *
2277  * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
2278  */
2279 void
2280 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
2281 {
2282   _dbus_modify_sigpipe = will_modify_sigpipe;
2283 }
2284
2285 /**
2286  * Specifies the maximum size message this connection is allowed to
2287  * receive. Larger messages will result in disconnecting the
2288  * connection.
2289  * 
2290  * @param connection a #DBusConnection
2291  * @param size maximum message size the connection can receive, in bytes
2292  */
2293 void
2294 dbus_connection_set_max_message_size (DBusConnection *connection,
2295                                       long            size)
2296 {
2297   dbus_mutex_lock (connection->mutex);
2298   _dbus_transport_set_max_message_size (connection->transport,
2299                                         size);
2300   dbus_mutex_unlock (connection->mutex);
2301 }
2302
2303 /**
2304  * Gets the value set by dbus_connection_set_max_message_size().
2305  *
2306  * @param connection the connection
2307  * @returns the max size of a single message
2308  */
2309 long
2310 dbus_connection_get_max_message_size (DBusConnection *connection)
2311 {
2312   long res;
2313   dbus_mutex_lock (connection->mutex);
2314   res = _dbus_transport_get_max_message_size (connection->transport);
2315   dbus_mutex_unlock (connection->mutex);
2316   return res;
2317 }
2318
2319 /**
2320  * Sets the maximum total number of bytes that can be used for all messages
2321  * received on this connection. Messages count toward the maximum until
2322  * they are finalized. When the maximum is reached, the connection will
2323  * not read more data until some messages are finalized.
2324  *
2325  * The semantics of the maximum are: if outstanding messages are
2326  * already above the maximum, additional messages will not be read.
2327  * The semantics are not: if the next message would cause us to exceed
2328  * the maximum, we don't read it. The reason is that we don't know the
2329  * size of a message until after we read it.
2330  *
2331  * Thus, the max live messages size can actually be exceeded
2332  * by up to the maximum size of a single message.
2333  * 
2334  * Also, if we read say 1024 bytes off the wire in a single read(),
2335  * and that contains a half-dozen small messages, we may exceed the
2336  * size max by that amount. But this should be inconsequential.
2337  *
2338  * @param connection the connection
2339  * @param size the maximum size in bytes of all outstanding messages
2340  */
2341 void
2342 dbus_connection_set_max_live_messages_size (DBusConnection *connection,
2343                                             long            size)
2344 {
2345   dbus_mutex_lock (connection->mutex);
2346   _dbus_transport_set_max_live_messages_size (connection->transport,
2347                                               size);
2348   dbus_mutex_unlock (connection->mutex);
2349 }
2350
2351 /**
2352  * Gets the value set by dbus_connection_set_max_live_messages_size().
2353  *
2354  * @param connection the connection
2355  * @returns the max size of all live messages
2356  */
2357 long
2358 dbus_connection_get_max_live_messages_size (DBusConnection *connection)
2359 {
2360   long res;
2361   dbus_mutex_lock (connection->mutex);
2362   res = _dbus_transport_get_max_live_messages_size (connection->transport);
2363   dbus_mutex_unlock (connection->mutex);
2364   return res;
2365 }
2366
2367 /** @} */