Merge branch 'dbus-1.2'
[platform/upstream/dbus.git] / dbus / dbus-watch.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-watch.c DBusWatch implementation
3  *
4  * Copyright (C) 2002, 2003  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #include "dbus-internals.h"
25 #include "dbus-watch.h"
26 #include "dbus-list.h"
27
28 /**
29  * @defgroup DBusWatchInternals DBusWatch implementation details
30  * @ingroup  DBusInternals
31  * @brief implementation details for DBusWatch
32  * 
33  * @{
34  */
35
36 /**
37  * Implementation of DBusWatch
38  */
39 struct DBusWatch
40 {
41   int refcount;                        /**< Reference count */
42   int fd;                              /**< File descriptor. */
43   unsigned int flags;                  /**< Conditions to watch. */
44
45   DBusWatchHandler handler;                    /**< Watch handler. */
46   void *handler_data;                          /**< Watch handler data. */
47   DBusFreeFunction free_handler_data_function; /**< Free the watch handler data. */
48   
49   void *data;                          /**< Application data. */
50   DBusFreeFunction free_data_function; /**< Free the application data. */
51   unsigned int enabled : 1;            /**< Whether it's enabled. */
52 };
53
54 dbus_bool_t
55 _dbus_watch_get_enabled (DBusWatch *watch)
56 {
57   return watch->enabled;
58 }
59
60 /**
61  * Creates a new DBusWatch. Used to add a file descriptor to be polled
62  * by a main loop.
63  * 
64  * @param fd the file descriptor to be watched.
65  * @param flags the conditions to watch for on the descriptor.
66  * @param enabled the initial enabled state
67  * @param handler the handler function
68  * @param data data for handler function
69  * @param free_data_function function to free the data
70  * @returns the new DBusWatch object.
71  */
72 DBusWatch*
73 _dbus_watch_new (int               fd,
74                  unsigned int      flags,
75                  dbus_bool_t       enabled,
76                  DBusWatchHandler  handler,
77                  void             *data,
78                  DBusFreeFunction  free_data_function)
79 {
80   DBusWatch *watch;
81
82 #define VALID_WATCH_FLAGS (DBUS_WATCH_WRITABLE | DBUS_WATCH_READABLE)
83   
84   _dbus_assert ((flags & VALID_WATCH_FLAGS) == flags);
85   
86   watch = dbus_new0 (DBusWatch, 1);
87   if (watch == NULL)
88     return NULL;
89   
90   watch->refcount = 1;
91   watch->fd = fd;
92   watch->flags = flags;
93   watch->enabled = enabled;
94
95   watch->handler = handler;
96   watch->handler_data = data;
97   watch->free_handler_data_function = free_data_function;
98   
99   return watch;
100 }
101
102 /**
103  * Increments the reference count of a DBusWatch object.
104  *
105  * @param watch the watch object.
106  * @returns the watch object.
107  */
108 DBusWatch *
109 _dbus_watch_ref (DBusWatch *watch)
110 {
111   watch->refcount += 1;
112
113   return watch;
114 }
115
116 /**
117  * Decrements the reference count of a DBusWatch object
118  * and finalizes the object if the count reaches zero.
119  *
120  * @param watch the watch object.
121  */
122 void
123 _dbus_watch_unref (DBusWatch *watch)
124 {
125   _dbus_assert (watch != NULL);
126   _dbus_assert (watch->refcount > 0);
127
128   watch->refcount -= 1;
129   if (watch->refcount == 0)
130     {
131       dbus_watch_set_data (watch, NULL, NULL); /* call free_data_function */
132
133       if (watch->free_handler_data_function)
134         (* watch->free_handler_data_function) (watch->handler_data);
135       
136       dbus_free (watch);
137     }
138 }
139
140 /**
141  * Clears the file descriptor from a now-invalid watch object so that
142  * no one tries to use it.  This is because a watch may stay alive due
143  * to reference counts after the file descriptor is closed.
144  * Invalidation makes it easier to catch bugs. It also
145  * keeps people from doing dorky things like assuming file descriptors
146  * are unique (never recycled).
147  *
148  * @param watch the watch object.
149  */
150 void
151 _dbus_watch_invalidate (DBusWatch *watch)
152 {
153   watch->fd = -1;
154   watch->flags = 0;
155 }
156
157 /**
158  * Sanitizes the given condition so that it only contains
159  * flags that the DBusWatch requested. e.g. if the
160  * watch is a DBUS_WATCH_READABLE watch then
161  * DBUS_WATCH_WRITABLE will be stripped from the condition.
162  *
163  * @param watch the watch object.
164  * @param condition address of the condition to sanitize.
165  */
166 void
167 _dbus_watch_sanitize_condition (DBusWatch    *watch,
168                                 unsigned int *condition)
169 {
170   if (!(watch->flags & DBUS_WATCH_READABLE))
171     *condition &= ~DBUS_WATCH_READABLE;
172   if (!(watch->flags & DBUS_WATCH_WRITABLE))
173     *condition &= ~DBUS_WATCH_WRITABLE;
174 }
175
176
177 /**
178  * @typedef DBusWatchList
179  *
180  * Opaque data type representing a list of watches
181  * and a set of DBusAddWatchFunction/DBusRemoveWatchFunction.
182  * Automatically handles removing/re-adding watches
183  * when the DBusAddWatchFunction is updated or changed.
184  * Holds a reference count to each watch.
185  *
186  * Used in the implementation of both DBusServer and
187  * DBusClient.
188  *
189  */
190
191 /**
192  * DBusWatchList implementation details. All fields
193  * are private.
194  *
195  */
196 struct DBusWatchList
197 {
198   DBusList *watches;           /**< Watch objects. */
199
200   DBusAddWatchFunction add_watch_function;    /**< Callback for adding a watch. */
201   DBusRemoveWatchFunction remove_watch_function; /**< Callback for removing a watch. */
202   DBusWatchToggledFunction watch_toggled_function; /**< Callback on toggling enablement */
203   void *watch_data;                           /**< Data for watch callbacks */
204   DBusFreeFunction watch_free_data_function;  /**< Free function for watch callback data */
205 };
206
207 /**
208  * Creates a new watch list. Returns #NULL if insufficient
209  * memory exists.
210  *
211  * @returns the new watch list, or #NULL on failure.
212  */
213 DBusWatchList*
214 _dbus_watch_list_new (void)
215 {
216   DBusWatchList *watch_list;
217
218   watch_list = dbus_new0 (DBusWatchList, 1);
219   if (watch_list == NULL)
220     return NULL;
221
222   return watch_list;
223 }
224
225 /**
226  * Frees a DBusWatchList.
227  *
228  * @param watch_list the watch list.
229  */
230 void
231 _dbus_watch_list_free (DBusWatchList *watch_list)
232 {
233   /* free watch_data and removes watches as a side effect */
234   _dbus_watch_list_set_functions (watch_list,
235                                   NULL, NULL, NULL, NULL, NULL);
236   _dbus_list_foreach (&watch_list->watches,
237                       (DBusForeachFunction) _dbus_watch_unref,
238                       NULL);
239   _dbus_list_clear (&watch_list->watches);
240
241   dbus_free (watch_list);
242 }
243
244 /**
245  * Sets the watch functions. This function is the "backend"
246  * for dbus_connection_set_watch_functions() and
247  * dbus_server_set_watch_functions().
248  *
249  * @param watch_list the watch list.
250  * @param add_function the add watch function.
251  * @param remove_function the remove watch function.
252  * @param toggled_function function on toggling enabled flag, or #NULL
253  * @param data the data for those functions.
254  * @param free_data_function the function to free the data.
255  * @returns #FALSE if not enough memory
256  *
257  */
258 dbus_bool_t
259 _dbus_watch_list_set_functions (DBusWatchList           *watch_list,
260                                 DBusAddWatchFunction     add_function,
261                                 DBusRemoveWatchFunction  remove_function,
262                                 DBusWatchToggledFunction toggled_function,
263                                 void                    *data,
264                                 DBusFreeFunction         free_data_function)
265 {
266   /* Add watches with the new watch function, failing on OOM */
267   if (add_function != NULL)
268     {
269       DBusList *link;
270       
271       link = _dbus_list_get_first_link (&watch_list->watches);
272       while (link != NULL)
273         {
274           DBusList *next = _dbus_list_get_next_link (&watch_list->watches,
275                                                      link);
276
277 #ifdef DBUS_ENABLE_VERBOSE_MODE
278           {
279             const char *watch_type;
280             int flags;
281
282             flags = dbus_watch_get_flags (link->data);
283             if ((flags & DBUS_WATCH_READABLE) &&
284                 (flags & DBUS_WATCH_WRITABLE))
285               watch_type = "readwrite";
286             else if (flags & DBUS_WATCH_READABLE)
287               watch_type = "read";
288             else if (flags & DBUS_WATCH_WRITABLE)
289               watch_type = "write";
290             else
291               watch_type = "not read or write";
292             
293             _dbus_verbose ("Adding a %s watch on fd %d using newly-set add watch function\n",
294                            watch_type,
295                            dbus_watch_get_socket (link->data));
296           }
297 #endif /* DBUS_ENABLE_VERBOSE_MODE */
298           
299           if (!(* add_function) (link->data, data))
300             {
301               /* remove it all again and return FALSE */
302               DBusList *link2;
303               
304               link2 = _dbus_list_get_first_link (&watch_list->watches);
305               while (link2 != link)
306                 {
307                   DBusList *next = _dbus_list_get_next_link (&watch_list->watches,
308                                                              link2);
309                   
310                   _dbus_verbose ("Removing watch on fd %d using newly-set remove function because initial add failed\n",
311                                  dbus_watch_get_socket (link2->data));
312                   
313                   (* remove_function) (link2->data, data);
314                   
315                   link2 = next;
316                 }
317
318               return FALSE;
319             }
320       
321           link = next;
322         }
323     }
324   
325   /* Remove all current watches from previous watch handlers */
326
327   if (watch_list->remove_watch_function != NULL)
328     {
329       _dbus_verbose ("Removing all pre-existing watches\n");
330       
331       _dbus_list_foreach (&watch_list->watches,
332                           (DBusForeachFunction) watch_list->remove_watch_function,
333                           watch_list->watch_data);
334     }
335
336   if (watch_list->watch_free_data_function != NULL)
337     (* watch_list->watch_free_data_function) (watch_list->watch_data);
338   
339   watch_list->add_watch_function = add_function;
340   watch_list->remove_watch_function = remove_function;
341   watch_list->watch_toggled_function = toggled_function;
342   watch_list->watch_data = data;
343   watch_list->watch_free_data_function = free_data_function;
344
345   return TRUE;
346 }
347
348 /**
349  * Adds a new watch to the watch list, invoking the
350  * application DBusAddWatchFunction if appropriate.
351  *
352  * @param watch_list the watch list.
353  * @param watch the watch to add.
354  * @returns #TRUE on success, #FALSE if no memory.
355  */
356 dbus_bool_t
357 _dbus_watch_list_add_watch (DBusWatchList *watch_list,
358                             DBusWatch     *watch)
359 {
360   if (!_dbus_list_append (&watch_list->watches, watch))
361     return FALSE;
362   
363   _dbus_watch_ref (watch);
364
365   if (watch_list->add_watch_function != NULL)
366     {
367       _dbus_verbose ("Adding watch on fd %d\n",
368                      dbus_watch_get_socket (watch));
369       
370       if (!(* watch_list->add_watch_function) (watch,
371                                                watch_list->watch_data))
372         {
373           _dbus_list_remove_last (&watch_list->watches, watch);
374           _dbus_watch_unref (watch);
375           return FALSE;
376         }
377     }
378   
379   return TRUE;
380 }
381
382 /**
383  * Removes a watch from the watch list, invoking the
384  * application's DBusRemoveWatchFunction if appropriate.
385  *
386  * @param watch_list the watch list.
387  * @param watch the watch to remove.
388  */
389 void
390 _dbus_watch_list_remove_watch  (DBusWatchList *watch_list,
391                                 DBusWatch     *watch)
392 {
393   if (!_dbus_list_remove (&watch_list->watches, watch))
394     _dbus_assert_not_reached ("Nonexistent watch was removed");
395   
396   if (watch_list->remove_watch_function != NULL)
397     {
398       _dbus_verbose ("Removing watch on fd %d\n",
399                      dbus_watch_get_socket (watch));
400       
401       (* watch_list->remove_watch_function) (watch,
402                                              watch_list->watch_data);
403     }
404   
405   _dbus_watch_unref (watch);
406 }
407
408 /**
409  * Sets a watch to the given enabled state, invoking the
410  * application's DBusWatchToggledFunction if appropriate.
411  *
412  * @param watch_list the watch list.
413  * @param watch the watch to toggle.
414  * @param enabled #TRUE to enable
415  */
416 void
417 _dbus_watch_list_toggle_watch (DBusWatchList           *watch_list,
418                                DBusWatch               *watch,
419                                dbus_bool_t              enabled)
420 {
421   enabled = !!enabled;
422   
423   if (enabled == watch->enabled)
424     return;
425
426   watch->enabled = enabled;
427   
428   if (watch_list->watch_toggled_function != NULL)
429     {
430       _dbus_verbose ("Toggling watch %p on fd %d to %d\n",
431                      watch, dbus_watch_get_socket (watch), watch->enabled);
432       
433       (* watch_list->watch_toggled_function) (watch,
434                                               watch_list->watch_data);
435     }
436 }
437
438 /**
439  * Sets the handler for the watch.
440  *
441  * @todo this function only exists because of the weird
442  * way connection watches are done, see the note
443  * in docs for _dbus_connection_handle_watch().
444  *
445  * @param watch the watch
446  * @param handler the new handler
447  * @param data the data
448  * @param free_data_function free data with this
449  */
450 void
451 _dbus_watch_set_handler (DBusWatch        *watch,
452                          DBusWatchHandler  handler,
453                          void             *data,
454                          DBusFreeFunction  free_data_function)
455 {
456   if (watch->free_handler_data_function)
457     (* watch->free_handler_data_function) (watch->handler_data);
458
459   watch->handler = handler;
460   watch->handler_data = data;
461   watch->free_handler_data_function = free_data_function;
462 }
463
464 /** @} */
465
466 /**
467  * @defgroup DBusWatch DBusWatch
468  * @ingroup  DBus
469  * @brief Object representing a file descriptor to be watched.
470  *
471  * Types and functions related to DBusWatch. A watch represents
472  * a file descriptor that the main loop needs to monitor,
473  * as in Qt's QSocketNotifier or GLib's g_io_add_watch().
474  *
475  * Use dbus_connection_set_watch_functions() or dbus_server_set_watch_functions()
476  * to be notified when libdbus needs to add or remove watches.
477  * 
478  * @{
479  */
480
481 /**
482  * @typedef DBusWatch
483  *
484  * Opaque object representing a file descriptor
485  * to be watched for changes in readability,
486  * writability, or hangup.
487  */
488
489 /**
490  * Deprecated former name of dbus_watch_get_unix_fd().
491  * 
492  * @param watch the DBusWatch object.
493  * @returns the file descriptor to watch.
494  */
495 int
496 dbus_watch_get_fd (DBusWatch *watch)
497 {
498   return dbus_watch_get_unix_fd(watch);
499 }
500
501 /**
502  * Returns a UNIX file descriptor to be watched,
503  * which may be a pipe, socket, or other type of
504  * descriptor. On UNIX this is preferred to
505  * dbus_watch_get_socket() since it works with
506  * more kinds of #DBusWatch.
507  *
508  * Always returns -1 on Windows. On Windows you use
509  * dbus_watch_get_socket() to get a Winsock socket to watch.
510  * 
511  * @param watch the DBusWatch object.
512  * @returns the file descriptor to watch.
513  */
514 int
515 dbus_watch_get_unix_fd (DBusWatch *watch)
516 {
517   /* FIXME remove #ifdef and do this on a lower level
518    * (watch should have set_socket and set_unix_fd and track
519    * which it has, and the transport should provide the
520    * appropriate watch type)
521    */
522 #ifdef DBUS_UNIX
523   return watch->fd;
524 #else
525   return dbus_watch_get_socket( watch );
526 #endif
527 }
528
529 /**
530  * Returns a socket to be watched, on UNIX this will return -1 if our
531  * transport is not socket-based so dbus_watch_get_unix_fd() is
532  * preferred.
533  *
534  * On Windows, dbus_watch_get_unix_fd() returns -1 but this function
535  * returns a Winsock socket (assuming the transport is socket-based,
536  * as it always is for now).
537  * 
538  * @param watch the DBusWatch object.
539  * @returns the socket to watch.
540  */
541 int
542 dbus_watch_get_socket (DBusWatch *watch)
543 {
544   return watch->fd;
545 }
546
547 /**
548  * Gets flags from DBusWatchFlags indicating
549  * what conditions should be monitored on the
550  * file descriptor.
551  * 
552  * The flags returned will only contain DBUS_WATCH_READABLE
553  * and DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or
554  * DBUS_WATCH_ERROR; all watches implicitly include a watch
555  * for hangups, errors, and other exceptional conditions.
556  *
557  * @param watch the DBusWatch object.
558  * @returns the conditions to watch.
559  */
560 unsigned int
561 dbus_watch_get_flags (DBusWatch *watch)
562 {
563   _dbus_assert ((watch->flags & VALID_WATCH_FLAGS) == watch->flags);
564
565   return watch->flags;
566 }
567
568 /**
569  * Gets data previously set with dbus_watch_set_data()
570  * or #NULL if none.
571  *
572  * @param watch the DBusWatch object.
573  * @returns previously-set data.
574  */
575 void*
576 dbus_watch_get_data (DBusWatch *watch)
577 {
578   return watch->data;
579 }
580
581 /**
582  * Sets data which can be retrieved with dbus_watch_get_data().
583  * Intended for use by the DBusAddWatchFunction and
584  * DBusRemoveWatchFunction to store their own data.  For example with
585  * Qt you might store the QSocketNotifier for this watch and with GLib
586  * you might store a GSource.
587  *
588  * @param watch the DBusWatch object.
589  * @param data the data.
590  * @param free_data_function function to be called to free the data.
591  */
592 void
593 dbus_watch_set_data (DBusWatch        *watch,
594                      void             *data,
595                      DBusFreeFunction  free_data_function)
596 {
597   _dbus_verbose ("Setting watch fd %d data to data = %p function = %p from data = %p function = %p\n",
598                  dbus_watch_get_socket (watch),
599                  data, free_data_function, watch->data, watch->free_data_function);
600   
601   if (watch->free_data_function != NULL)
602     (* watch->free_data_function) (watch->data);
603   
604   watch->data = data;
605   watch->free_data_function = free_data_function;
606 }
607
608 /**
609  * Returns whether a watch is enabled or not. If not
610  * enabled, it should not be polled by the main loop.
611  *
612  * @param watch the DBusWatch object
613  * @returns #TRUE if the watch is enabled
614  */
615 dbus_bool_t
616 dbus_watch_get_enabled (DBusWatch *watch)
617 {
618   _dbus_assert (watch != NULL);
619   return watch->enabled;
620 }
621
622
623 /**
624  * Called to notify the D-Bus library when a previously-added watch is
625  * ready for reading or writing, or has an exception such as a hangup.
626  * 
627  * If this function returns #FALSE, then the file descriptor may still
628  * be ready for reading or writing, but more memory is needed in order
629  * to do the reading or writing. If you ignore the #FALSE return, your
630  * application may spin in a busy loop on the file descriptor until
631  * memory becomes available, but nothing more catastrophic should
632  * happen.
633  *
634  * dbus_watch_handle() cannot be called during the
635  * DBusAddWatchFunction, as the connection will not be ready to handle
636  * that watch yet.
637  * 
638  * It is not allowed to reference a DBusWatch after it has been passed
639  * to remove_function.
640  *
641  * @param watch the DBusWatch object.
642  * @param flags the poll condition using #DBusWatchFlags values
643  * @returns #FALSE if there wasn't enough memory 
644  */
645 dbus_bool_t
646 dbus_watch_handle (DBusWatch    *watch,
647                    unsigned int  flags)
648 {
649 #ifndef DBUS_DISABLE_CHECKS
650   if (watch->fd < 0 || watch->flags == 0)
651     {
652       _dbus_warn_check_failed ("%s: Watch is invalid, it should have been removed\n",
653                                _DBUS_FUNCTION_NAME);
654       return TRUE;
655     }
656 #endif
657     
658   _dbus_return_val_if_fail (watch->fd >= 0 /* fails if watch was removed */, TRUE);
659   
660   _dbus_watch_sanitize_condition (watch, &flags);
661
662   if (flags == 0)
663     {
664       _dbus_verbose ("After sanitization, watch flags on fd %d were 0\n",
665                      watch->fd);
666       return TRUE;
667     }
668   else
669     return (* watch->handler) (watch, flags,
670                                watch->handler_data);
671 }
672
673
674 /** @} */