2003-03-16 Havoc Pennington <hp@pobox.com>
[platform/upstream/dbus.git] / bus / connection.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* connection.c  Client connections
3  *
4  * Copyright (C) 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 #include "connection.h"
24 #include "dispatch.h"
25 #include "loop.h"
26 #include "services.h"
27 #include "utils.h"
28 #include <dbus/dbus-list.h>
29
30 static void bus_connection_remove_transactions (DBusConnection *connection);
31
32 struct BusConnections
33 {
34   int refcount;
35   DBusList *list; /**< List of all the connections */
36   BusContext *context;
37 };
38
39 static int connection_data_slot = -1;
40
41 typedef struct
42 {
43   BusConnections *connections;
44   DBusConnection *connection;
45   DBusList *services_owned;
46   char *name;
47   DBusList *transaction_messages; /**< Stuff we need to send as part of a transaction */
48   DBusMessage *oom_message;
49   DBusPreallocatedSend *oom_preallocated;
50 } BusConnectionData;
51
52 #define BUS_CONNECTION_DATA(connection) (dbus_connection_get_data ((connection), connection_data_slot))
53
54 void
55 bus_connection_disconnected (DBusConnection *connection)
56 {
57   BusConnectionData *d;
58   BusService *service;
59
60   d = BUS_CONNECTION_DATA (connection);
61   _dbus_assert (d != NULL);
62
63   _dbus_verbose ("%s disconnected, dropping all service ownership and releasing\n",
64                  d->name ? d->name : "(inactive)");
65   
66   /* Drop any service ownership. FIXME Unfortunately, this requires
67    * memory allocation and there doesn't seem to be a good way to
68    * handle it other than sleeping; we can't "fail" the operation of
69    * disconnecting a client, and preallocating a broadcast "service is
70    * now gone" message for every client-service pair seems kind of
71    * involved. Probably we need to do that though, and also
72    * extend BusTransaction to be able to revert generic
73    * stuff, not just sending a message (so we can e.g. revert
74    * removal of service owners).
75    */
76   while ((service = _dbus_list_get_last (&d->services_owned)))
77     {
78       BusTransaction *transaction;
79       DBusError error;
80
81     retry:
82       
83       dbus_error_init (&error);
84         
85       transaction = NULL;
86       while (transaction == NULL)
87         {
88           transaction = bus_transaction_new (d->connections->context);
89           bus_wait_for_memory ();
90         }
91         
92       if (!bus_service_remove_owner (service, connection,
93                                      transaction, &error))
94         {
95           if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY))
96             {
97               dbus_error_free (&error);
98               bus_transaction_cancel_and_free (transaction);
99               bus_wait_for_memory ();
100               goto retry;
101             }
102           else
103             _dbus_assert_not_reached ("Removing service owner failed for non-memory-related reason");
104         }
105         
106       bus_transaction_execute_and_free (transaction);
107     }
108
109   bus_dispatch_remove_connection (connection);
110   
111   /* no more watching */
112   if (!dbus_connection_set_watch_functions (connection,
113                                             NULL, NULL, NULL,
114                                             connection,
115                                             NULL))
116     _dbus_assert_not_reached ("setting watch functions to NULL failed");
117
118   if (!dbus_connection_set_timeout_functions (connection,
119                                               NULL, NULL, NULL,
120                                               connection,
121                                               NULL))
122     _dbus_assert_not_reached ("setting timeout functions to NULL failed");
123   
124   bus_connection_remove_transactions (connection);
125
126   _dbus_list_remove (&d->connections->list, connection);
127
128   /* frees "d" as side effect */
129   dbus_connection_set_data (connection,
130                             connection_data_slot,
131                             NULL, NULL);
132
133   dbus_connection_unref (connection);
134 }
135
136 static dbus_bool_t
137 connection_watch_callback (DBusWatch     *watch,
138                            unsigned int   condition,
139                            void          *data)
140 {
141   DBusConnection *connection = data;
142   dbus_bool_t retval;
143
144   dbus_connection_ref (connection);
145   
146   retval = dbus_connection_handle_watch (connection, watch, condition);
147
148   bus_connection_dispatch_all_messages (connection);
149   
150   dbus_connection_unref (connection);
151
152   return retval;
153 }
154
155 static dbus_bool_t
156 add_connection_watch (DBusWatch      *watch,
157                       DBusConnection *connection)
158 {
159   return bus_loop_add_watch (watch, connection_watch_callback, connection,
160                              NULL);
161 }
162
163 static void
164 remove_connection_watch (DBusWatch      *watch,
165                          DBusConnection *connection)
166 {
167   bus_loop_remove_watch (watch, connection_watch_callback, connection);
168 }
169
170 static void
171 connection_timeout_callback (DBusTimeout   *timeout,
172                              void          *data)
173 {
174   DBusConnection *connection = data;
175
176   dbus_connection_ref (connection);
177
178   /* can return FALSE on OOM but we just let it fire again later */
179   dbus_timeout_handle (timeout);
180
181   bus_connection_dispatch_all_messages (connection);
182   
183   dbus_connection_unref (connection);
184 }
185
186 static dbus_bool_t
187 add_connection_timeout (DBusTimeout    *timeout,
188                         DBusConnection *connection)
189 {
190   return bus_loop_add_timeout (timeout, connection_timeout_callback, connection, NULL);
191 }
192
193 static void
194 remove_connection_timeout (DBusTimeout    *timeout,
195                            DBusConnection *connection)
196 {
197   bus_loop_remove_timeout (timeout, connection_timeout_callback, connection);
198 }
199
200 static void
201 free_connection_data (void *data)
202 {
203   BusConnectionData *d = data;
204
205   /* services_owned should be NULL since we should be disconnected */
206   _dbus_assert (d->services_owned == NULL);
207   /* similarly */
208   _dbus_assert (d->transaction_messages == NULL);
209
210   if (d->oom_preallocated)
211     dbus_connection_free_preallocated_send (d->connection, d->oom_preallocated);
212   if (d->oom_message)
213     dbus_message_unref (d->oom_message);
214   
215   dbus_free (d->name);
216   
217   dbus_free (d);
218 }
219
220 BusConnections*
221 bus_connections_new (BusContext *context)
222 {
223   BusConnections *connections;
224
225   if (connection_data_slot < 0)
226     {
227       connection_data_slot = dbus_connection_allocate_data_slot ();
228       
229       if (connection_data_slot < 0)
230         return NULL;
231     }
232
233   connections = dbus_new0 (BusConnections, 1);
234   if (connections == NULL)
235     return NULL;
236   
237   connections->refcount = 1;
238   connections->context = context;
239   
240   return connections;
241 }
242
243 void
244 bus_connections_ref (BusConnections *connections)
245 {
246   _dbus_assert (connections->refcount > 0);
247   connections->refcount += 1;
248 }
249
250 void
251 bus_connections_unref (BusConnections *connections)
252 {
253   _dbus_assert (connections->refcount > 0);
254   connections->refcount -= 1;
255   if (connections->refcount == 0)
256     {
257       while (connections->list != NULL)
258         {
259           DBusConnection *connection;
260
261           connection = connections->list->data;
262
263           dbus_connection_ref (connection);
264           dbus_connection_disconnect (connection);
265           bus_connection_disconnected (connection);
266           dbus_connection_unref (connection);
267         }
268       
269       _dbus_list_clear (&connections->list);
270       
271       dbus_free (connections);      
272     }
273 }
274
275 dbus_bool_t
276 bus_connections_setup_connection (BusConnections *connections,
277                                   DBusConnection *connection)
278 {
279   BusConnectionData *d;
280   dbus_bool_t retval;
281   
282   d = dbus_new0 (BusConnectionData, 1);
283   
284   if (d == NULL)
285     return FALSE;
286
287   d->connections = connections;
288   d->connection = connection;
289   
290   if (!dbus_connection_set_data (connection,
291                                  connection_data_slot,
292                                  d, free_connection_data))
293     {
294       dbus_free (d);
295       return FALSE;
296     }
297
298   retval = FALSE;
299   
300   if (!dbus_connection_set_watch_functions (connection,
301                                             (DBusAddWatchFunction) add_connection_watch,
302                                             (DBusRemoveWatchFunction) remove_connection_watch,
303                                             NULL,
304                                             connection,
305                                             NULL))
306     goto out;
307   
308   if (!dbus_connection_set_timeout_functions (connection,
309                                               (DBusAddTimeoutFunction) add_connection_timeout,
310                                               (DBusRemoveTimeoutFunction) remove_connection_timeout,
311                                               NULL,
312                                               connection, NULL))
313     goto out;
314
315   
316   /* Setup the connection with the dispatcher */
317   if (!bus_dispatch_add_connection (connection))
318     goto out;
319   
320   if (!_dbus_list_append (&connections->list, connection))
321     {
322       bus_dispatch_remove_connection (connection);
323       goto out;
324     }
325   
326   dbus_connection_ref (connection);
327   retval = TRUE;
328
329  out:
330   if (!retval)
331     {
332       if (!dbus_connection_set_watch_functions (connection,
333                                                 NULL, NULL, NULL,
334                                                 connection,
335                                                 NULL))
336         _dbus_assert_not_reached ("setting watch functions to NULL failed");
337       
338       if (!dbus_connection_set_timeout_functions (connection,
339                                                   NULL, NULL, NULL,
340                                                   connection,
341                                                   NULL))
342         _dbus_assert_not_reached ("setting timeout functions to NULL failed");
343     }
344   
345   return retval;
346 }
347
348
349 /**
350  * Calls function on each connection; if the function returns
351  * #FALSE, stops iterating.
352  *
353  * @param connections the connections object
354  * @param function the function
355  * @param data data to pass to it as a second arg
356  */
357 void
358 bus_connections_foreach (BusConnections               *connections,
359                          BusConnectionForeachFunction  function,
360                         void                          *data)
361 {
362   DBusList *link;
363   
364   link = _dbus_list_get_first_link (&connections->list);
365   while (link != NULL)
366     {
367       DBusConnection *connection = link->data;
368       DBusList *next = _dbus_list_get_next_link (&connections->list, link);
369
370       if (!(* function) (connection, data))
371         break;
372       
373       link = next;
374     }
375 }
376
377 BusContext*
378 bus_connections_get_context (BusConnections *connections)
379 {
380   return connections->context;
381 }
382
383 BusContext*
384 bus_connection_get_context (DBusConnection *connection)
385 {
386   BusConnectionData *d;
387
388   d = BUS_CONNECTION_DATA (connection);
389
390   _dbus_assert (d != NULL);
391
392   return d->connections->context;
393 }
394
395 BusConnections*
396 bus_connection_get_connections (DBusConnection *connection)
397 {
398   BusConnectionData *d;
399     
400   d = BUS_CONNECTION_DATA (connection);
401
402   _dbus_assert (d != NULL);
403
404   return d->connections;
405 }
406
407 BusRegistry*
408 bus_connection_get_registry (DBusConnection *connection)
409 {
410   BusConnectionData *d;
411
412   d = BUS_CONNECTION_DATA (connection);
413
414   _dbus_assert (d != NULL);
415
416   return bus_context_get_registry (d->connections->context);
417 }
418
419 BusActivation*
420 bus_connection_get_activation (DBusConnection *connection)
421 {
422   BusConnectionData *d;
423
424   d = BUS_CONNECTION_DATA (connection);
425
426   _dbus_assert (d != NULL);
427
428   return bus_context_get_activation (d->connections->context);
429 }
430
431 /**
432  * Checks whether the connection is registered with the message bus.
433  *
434  * @param connection the connection
435  * @returns #TRUE if we're an active message bus participant
436  */
437 dbus_bool_t
438 bus_connection_is_active (DBusConnection *connection)
439 {
440   BusConnectionData *d;
441
442   d = BUS_CONNECTION_DATA (connection);
443   
444   return d != NULL && d->name != NULL;
445 }
446
447 dbus_bool_t
448 bus_connection_preallocate_oom_error (DBusConnection *connection)
449 {
450   DBusMessage *message;
451   DBusPreallocatedSend *preallocated;
452   BusConnectionData *d;
453
454   d = BUS_CONNECTION_DATA (connection);  
455
456   _dbus_assert (d != NULL);
457
458   if (d->oom_preallocated != NULL)
459     return TRUE;
460   
461   preallocated = dbus_connection_preallocate_send (connection);
462   if (preallocated == NULL)
463     return FALSE;
464
465   message = dbus_message_new (DBUS_SERVICE_DBUS,
466                               DBUS_ERROR_NO_MEMORY);
467   if (message == NULL)
468     {
469       dbus_connection_free_preallocated_send (connection, preallocated);
470       return FALSE;
471     }
472
473   dbus_message_set_is_error (message, TRUE);
474   
475   /* set reply serial to placeholder value just so space is already allocated
476    * for it.
477    */
478   if (!dbus_message_set_reply_serial (message, 14))
479     {
480       dbus_connection_free_preallocated_send (connection, preallocated);
481       dbus_message_unref (message);
482       return FALSE;
483     }
484
485   d->oom_message = message;
486   d->oom_preallocated = preallocated;
487   
488   return TRUE;
489 }
490
491 void
492 bus_connection_send_oom_error (DBusConnection *connection,
493                                DBusMessage    *in_reply_to)
494 {
495   BusConnectionData *d;
496
497   d = BUS_CONNECTION_DATA (connection);  
498
499   _dbus_assert (d != NULL);  
500   _dbus_assert (d->oom_message != NULL);
501
502   /* should always succeed since we set it to a placeholder earlier */
503   if (!dbus_message_set_reply_serial (d->oom_message,
504                                       dbus_message_get_serial (in_reply_to)))
505     _dbus_assert_not_reached ("Failed to set reply serial for preallocated oom message");
506
507   dbus_connection_send_preallocated (connection, d->oom_preallocated,
508                                      d->oom_message, NULL);
509
510   dbus_message_unref (d->oom_message);
511   d->oom_message = NULL;
512   d->oom_preallocated = NULL;
513 }
514
515 dbus_bool_t
516 bus_connection_add_owned_service (DBusConnection *connection,
517                                   BusService     *service)
518 {
519   BusConnectionData *d;
520
521   d = BUS_CONNECTION_DATA (connection);
522   _dbus_assert (d != NULL);
523
524   if (!_dbus_list_append (&d->services_owned,
525                           service))
526     return FALSE;
527
528   return TRUE;
529 }
530
531 void
532 bus_connection_remove_owned_service (DBusConnection *connection,
533                                      BusService     *service)
534 {
535   BusConnectionData *d;
536
537   d = BUS_CONNECTION_DATA (connection);
538   _dbus_assert (d != NULL);
539
540   _dbus_list_remove_last (&d->services_owned, service);
541 }
542
543 dbus_bool_t
544 bus_connection_set_name (DBusConnection   *connection,
545                          const DBusString *name)
546 {
547   const char *c_name;
548   BusConnectionData *d;
549   
550   d = BUS_CONNECTION_DATA (connection);
551   _dbus_assert (d != NULL);
552   _dbus_assert (d->name == NULL);
553
554   _dbus_string_get_const_data (name, &c_name);
555
556   d->name = _dbus_strdup (c_name);
557
558   if (d->name == NULL)
559     return FALSE;
560
561   _dbus_verbose ("Name %s assigned to %p\n", d->name, connection);
562   
563   return TRUE;
564 }
565
566 const char *
567 bus_connection_get_name (DBusConnection *connection)
568 {
569   BusConnectionData *d;
570   
571   d = BUS_CONNECTION_DATA (connection);
572   _dbus_assert (d != NULL);
573   
574   return d->name;
575 }
576
577 typedef struct
578 {
579   BusTransaction *transaction;
580   DBusMessage    *message;
581   DBusPreallocatedSend *preallocated;
582 } MessageToSend;
583
584 struct BusTransaction
585 {
586   DBusList *connections;
587   BusContext *context;
588 };
589
590 static void
591 message_to_send_free (DBusConnection *connection,
592                       MessageToSend  *to_send)
593 {
594   if (to_send->message)
595     dbus_message_unref (to_send->message);
596
597   if (to_send->preallocated)
598     dbus_connection_free_preallocated_send (connection, to_send->preallocated);
599
600   dbus_free (to_send);
601 }
602
603 BusTransaction*
604 bus_transaction_new (BusContext *context)
605 {
606   BusTransaction *transaction;
607
608   transaction = dbus_new0 (BusTransaction, 1);
609   if (transaction == NULL)
610     return NULL;
611
612   transaction->context = context;
613   
614   return transaction;
615 }
616
617 BusContext*
618 bus_transaction_get_context (BusTransaction  *transaction)
619 {
620   return transaction->context;
621 }
622
623 BusConnections*
624 bus_transaction_get_connections (BusTransaction  *transaction)
625 {
626   return bus_context_get_connections (transaction->context);
627 }
628
629 dbus_bool_t
630 bus_transaction_send_message (BusTransaction *transaction,
631                               DBusConnection *connection,
632                               DBusMessage    *message)
633 {
634   MessageToSend *to_send;
635   BusConnectionData *d;
636   DBusList *link;
637
638   _dbus_verbose ("  trying to add message %s to transaction%s\n",
639                  dbus_message_get_name (message),
640                  dbus_connection_get_is_connected (connection) ?
641                  "" : " (disconnected)");
642   
643   if (!dbus_connection_get_is_connected (connection))
644     return TRUE; /* silently ignore disconnected connections */
645   
646   d = BUS_CONNECTION_DATA (connection);
647   _dbus_assert (d != NULL);
648   
649   to_send = dbus_new (MessageToSend, 1);
650   if (to_send == NULL)
651     {
652       return FALSE;
653     }
654
655   to_send->preallocated = dbus_connection_preallocate_send (connection);
656   if (to_send->preallocated == NULL)
657     {
658       dbus_free (to_send);
659       return FALSE;
660     }  
661   
662   dbus_message_ref (message);
663   to_send->message = message;
664   to_send->transaction = transaction;
665
666   _dbus_verbose ("about to prepend message\n");
667   
668   if (!_dbus_list_prepend (&d->transaction_messages, to_send))
669     {
670       message_to_send_free (connection, to_send);
671       return FALSE;
672     }
673
674   _dbus_verbose ("prepended message\n");
675   
676   /* See if we already had this connection in the list
677    * for this transaction. If we have a pending message,
678    * then we should already be in transaction->connections
679    */
680   link = _dbus_list_get_first_link (&d->transaction_messages);
681   _dbus_assert (link->data == to_send);
682   link = _dbus_list_get_next_link (&d->transaction_messages, link);
683   while (link != NULL)
684     {
685       MessageToSend *m = link->data;
686       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
687       
688       if (m->transaction == transaction)
689         break;
690         
691       link = next;
692     }
693
694   if (link == NULL)
695     {
696       if (!_dbus_list_prepend (&transaction->connections, connection))
697         {
698           _dbus_list_remove (&d->transaction_messages, to_send);
699           message_to_send_free (connection, to_send);
700           return FALSE;
701         }
702     }
703
704   return TRUE;
705 }
706
707 static void
708 connection_cancel_transaction (DBusConnection *connection,
709                                BusTransaction *transaction)
710 {
711   DBusList *link;
712   BusConnectionData *d;
713   
714   d = BUS_CONNECTION_DATA (connection);
715   _dbus_assert (d != NULL);
716   
717   link = _dbus_list_get_first_link (&d->transaction_messages);
718   while (link != NULL)
719     {
720       MessageToSend *m = link->data;
721       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
722       
723       if (m->transaction == transaction)
724         {
725           _dbus_list_remove_link (&d->transaction_messages,
726                                   link);
727           
728           message_to_send_free (connection, m);
729         }
730         
731       link = next;
732     }
733 }
734
735 void
736 bus_transaction_cancel_and_free (BusTransaction *transaction)
737 {
738   DBusConnection *connection;
739
740   _dbus_verbose ("TRANSACTION: cancelled\n");
741   
742   while ((connection = _dbus_list_pop_first (&transaction->connections)))
743     connection_cancel_transaction (connection, transaction);
744
745   _dbus_assert (transaction->connections == NULL);
746
747   dbus_free (transaction);
748 }
749
750 static void
751 connection_execute_transaction (DBusConnection *connection,
752                                 BusTransaction *transaction)
753 {
754   DBusList *link;
755   BusConnectionData *d;
756   
757   d = BUS_CONNECTION_DATA (connection);
758   _dbus_assert (d != NULL);
759
760   /* Send the queue in order (FIFO) */
761   link = _dbus_list_get_last_link (&d->transaction_messages);
762   while (link != NULL)
763     {
764       MessageToSend *m = link->data;
765       DBusList *prev = _dbus_list_get_prev_link (&d->transaction_messages, link);
766       
767       if (m->transaction == transaction)
768         {
769           _dbus_list_remove_link (&d->transaction_messages,
770                                   link);
771
772           dbus_connection_send_preallocated (connection,
773                                              m->preallocated,
774                                              m->message,
775                                              NULL);
776
777           m->preallocated = NULL; /* so we don't double-free it */
778           
779           message_to_send_free (connection, m);
780         }
781         
782       link = prev;
783     }
784 }
785
786 void
787 bus_transaction_execute_and_free (BusTransaction *transaction)
788 {
789   /* For each connection in transaction->connections
790    * send the messages
791    */
792   DBusConnection *connection;
793
794   _dbus_verbose ("TRANSACTION: executing\n");
795   
796   while ((connection = _dbus_list_pop_first (&transaction->connections)))
797     connection_execute_transaction (connection, transaction);
798
799   _dbus_assert (transaction->connections == NULL);
800
801   dbus_free (transaction);
802 }
803
804 static void
805 bus_connection_remove_transactions (DBusConnection *connection)
806 {
807   MessageToSend *to_send;
808   BusConnectionData *d;
809   
810   d = BUS_CONNECTION_DATA (connection);
811   _dbus_assert (d != NULL);
812   
813   while ((to_send = _dbus_list_get_first (&d->transaction_messages)))
814     {
815       /* only has an effect for the first MessageToSend listing this transaction */
816       _dbus_list_remove (&to_send->transaction->connections,
817                          connection);
818
819       _dbus_list_remove (&d->transaction_messages, to_send);
820       message_to_send_free (connection, to_send);
821     }
822 }
823
824 /**
825  * Converts the DBusError to a message reply
826  */
827 dbus_bool_t
828 bus_transaction_send_error_reply (BusTransaction  *transaction,
829                                   DBusConnection  *connection,
830                                   const DBusError *error,
831                                   DBusMessage     *in_reply_to)
832 {
833   DBusMessage *reply;
834
835   _dbus_assert (error != NULL);
836   _DBUS_ASSERT_ERROR_IS_SET (error);
837   
838   reply = dbus_message_new_error_reply (in_reply_to,
839                                         error->name,
840                                         error->message);
841   if (reply == NULL)
842     return FALSE;
843
844   if (!bus_transaction_send_message (transaction, connection, reply))
845     {
846       dbus_message_unref (reply);
847       return FALSE;
848     }
849
850   return TRUE;
851 }