2003-04-24 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-watch.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-watch.c DBusWatch implementation
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-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 struct DBusWatch
37 {
38   int refcount;                        /**< Reference count */
39   int fd;                              /**< File descriptor. */
40   unsigned int flags;                  /**< Conditions to watch. */
41
42   DBusWatchHandler handler;                    /**< Watch handler. */
43   void *handler_data;                          /**< Watch handler data. */
44   DBusFreeFunction free_handler_data_function; /**< Free the watch handler data. */
45   
46   void *data;                          /**< Application data. */
47   DBusFreeFunction free_data_function; /**< Free the application data. */
48   unsigned int enabled : 1;            /**< Whether it's enabled. */
49 };
50
51 /**
52  * Creates a new DBusWatch. Used to add a file descriptor to be polled
53  * by a main loop.
54  * 
55  * @param fd the file descriptor to be watched.
56  * @param flags the conditions to watch for on the descriptor.
57  * @param enabled the initial enabled state
58  * @param handler the handler function
59  * @param data data for handler function
60  * @param free_data_function function to free the data
61  * @returns the new DBusWatch object.
62  */
63 DBusWatch*
64 _dbus_watch_new (int               fd,
65                  unsigned int      flags,
66                  dbus_bool_t       enabled,
67                  DBusWatchHandler  handler,
68                  void             *data,
69                  DBusFreeFunction  free_data_function)
70 {
71   DBusWatch *watch;
72
73 #define VALID_WATCH_FLAGS (DBUS_WATCH_WRITABLE | DBUS_WATCH_READABLE)
74   
75   _dbus_assert ((flags & VALID_WATCH_FLAGS) == flags);
76   
77   watch = dbus_new0 (DBusWatch, 1);
78   if (watch == NULL)
79     return NULL;
80   
81   watch->refcount = 1;
82   watch->fd = fd;
83   watch->flags = flags;
84   watch->enabled = enabled;
85
86   watch->handler = handler;
87   watch->handler_data = data;
88   watch->free_handler_data_function = free_data_function;
89   
90   return watch;
91 }
92
93 /**
94  * Increments the reference count of a DBusWatch object.
95  *
96  * @param watch the watch object.
97  */
98 void
99 _dbus_watch_ref (DBusWatch *watch)
100 {
101   watch->refcount += 1;
102 }
103
104 /**
105  * Decrements the reference count of a DBusWatch object
106  * and finalizes the object if the count reaches zero.
107  *
108  * @param watch the watch object.
109  */
110 void
111 _dbus_watch_unref (DBusWatch *watch)
112 {
113   _dbus_assert (watch != NULL);
114   _dbus_assert (watch->refcount > 0);
115
116   watch->refcount -= 1;
117   if (watch->refcount == 0)
118     {
119       dbus_watch_set_data (watch, NULL, NULL); /* call free_data_function */
120
121       if (watch->free_handler_data_function)
122         (* watch->free_handler_data_function) (watch->handler_data);
123       
124       dbus_free (watch);
125     }
126 }
127
128 /**
129  * Clears the file descriptor from a now-invalid watch object so that
130  * no one tries to use it.  This is because a watch may stay alive due
131  * to reference counts after the file descriptor is closed.
132  * Invalidation makes it easier to catch bugs. It also
133  * keeps people from doing dorky things like assuming file descriptors
134  * are unique (never recycled).
135  *
136  * @param watch the watch object.
137  */
138 void
139 _dbus_watch_invalidate (DBusWatch *watch)
140 {
141   watch->fd = -1;
142   watch->flags = 0;
143 }
144
145 /**
146  * Sanitizes the given condition so that it only contains
147  * flags that the DBusWatch requested. e.g. if the
148  * watch is a DBUS_WATCH_READABLE watch then
149  * DBUS_WATCH_WRITABLE will be stripped from the condition.
150  *
151  * @param watch the watch object.
152  * @param condition address of the condition to sanitize.
153  */
154 void
155 _dbus_watch_sanitize_condition (DBusWatch    *watch,
156                                 unsigned int *condition)
157 {
158   if (!(watch->flags & DBUS_WATCH_READABLE))
159     *condition &= ~DBUS_WATCH_READABLE;
160   if (!(watch->flags & DBUS_WATCH_WRITABLE))
161     *condition &= ~DBUS_WATCH_WRITABLE;
162 }
163
164
165 /**
166  * @typedef DBusWatchList
167  *
168  * Opaque data type representing a list of watches
169  * and a set of DBusAddWatchFunction/DBusRemoveWatchFunction.
170  * Automatically handles removing/re-adding watches
171  * when the DBusAddWatchFunction is updated or changed.
172  * Holds a reference count to each watch.
173  *
174  * Used in the implementation of both DBusServer and
175  * DBusClient.
176  *
177  */
178
179 /**
180  * DBusWatchList implementation details. All fields
181  * are private.
182  *
183  */
184 struct DBusWatchList
185 {
186   DBusList *watches;           /**< Watch objects. */
187
188   DBusAddWatchFunction add_watch_function;    /**< Callback for adding a watch. */
189   DBusRemoveWatchFunction remove_watch_function; /**< Callback for removing a watch. */
190   DBusWatchToggledFunction watch_toggled_function; /**< Callback on toggling enablement */
191   void *watch_data;                           /**< Data for watch callbacks */
192   DBusFreeFunction watch_free_data_function;  /**< Free function for watch callback data */
193 };
194
195 /**
196  * Creates a new watch list. Returns #NULL if insufficient
197  * memory exists.
198  *
199  * @returns the new watch list, or #NULL on failure.
200  */
201 DBusWatchList*
202 _dbus_watch_list_new (void)
203 {
204   DBusWatchList *watch_list;
205
206   watch_list = dbus_new0 (DBusWatchList, 1);
207   if (watch_list == NULL)
208     return NULL;
209
210   return watch_list;
211 }
212
213 /**
214  * Frees a DBusWatchList.
215  *
216  * @param watch_list the watch list.
217  */
218 void
219 _dbus_watch_list_free (DBusWatchList *watch_list)
220 {
221   /* free watch_data and removes watches as a side effect */
222   _dbus_watch_list_set_functions (watch_list,
223                                   NULL, NULL, NULL, NULL, NULL);
224   _dbus_list_foreach (&watch_list->watches,
225                       (DBusForeachFunction) _dbus_watch_unref,
226                       NULL);
227   _dbus_list_clear (&watch_list->watches);
228
229   dbus_free (watch_list);
230 }
231
232 /**
233  * Sets the watch functions. This function is the "backend"
234  * for dbus_connection_set_watch_functions() and
235  * dbus_server_set_watch_functions().
236  *
237  * @param watch_list the watch list.
238  * @param add_function the add watch function.
239  * @param remove_function the remove watch function.
240  * @param toggled_function function on toggling enabled flag, or #NULL
241  * @param data the data for those functions.
242  * @param free_data_function the function to free the data.
243  * @returns #FALSE if not enough memory
244  *
245  */
246 dbus_bool_t
247 _dbus_watch_list_set_functions (DBusWatchList           *watch_list,
248                                 DBusAddWatchFunction     add_function,
249                                 DBusRemoveWatchFunction  remove_function,
250                                 DBusWatchToggledFunction toggled_function,
251                                 void                    *data,
252                                 DBusFreeFunction         free_data_function)
253 {
254   /* Add watches with the new watch function, failing on OOM */
255   if (add_function != NULL)
256     {
257       DBusList *link;
258       
259       link = _dbus_list_get_first_link (&watch_list->watches);
260       while (link != NULL)
261         {
262           DBusList *next = _dbus_list_get_next_link (&watch_list->watches,
263                                                      link);
264       
265           if (!(* add_function) (link->data, data))
266             {
267               /* remove it all again and return FALSE */
268               DBusList *link2;
269               
270               link2 = _dbus_list_get_first_link (&watch_list->watches);
271               while (link2 != link)
272                 {
273                   DBusList *next = _dbus_list_get_next_link (&watch_list->watches,
274                                                              link2);
275
276                   (* remove_function) (link2->data, data);
277                   
278                   link2 = next;
279                 }
280
281               return FALSE;
282             }
283       
284           link = next;
285         }
286     }
287   
288   /* Remove all current watches from previous watch handlers */
289
290   if (watch_list->remove_watch_function != NULL)
291     {
292       _dbus_list_foreach (&watch_list->watches,
293                           (DBusForeachFunction) watch_list->remove_watch_function,
294                           watch_list->watch_data);
295     }
296
297   if (watch_list->watch_free_data_function != NULL)
298     (* watch_list->watch_free_data_function) (watch_list->watch_data);
299   
300   watch_list->add_watch_function = add_function;
301   watch_list->remove_watch_function = remove_function;
302   watch_list->watch_toggled_function = toggled_function;
303   watch_list->watch_data = data;
304   watch_list->watch_free_data_function = free_data_function;
305
306   return TRUE;
307 }
308
309 /**
310  * Adds a new watch to the watch list, invoking the
311  * application DBusAddWatchFunction if appropriate.
312  *
313  * @param watch_list the watch list.
314  * @param watch the watch to add.
315  * @returns #TRUE on success, #FALSE if no memory.
316  */
317 dbus_bool_t
318 _dbus_watch_list_add_watch (DBusWatchList *watch_list,
319                             DBusWatch     *watch)
320 {
321   if (!_dbus_list_append (&watch_list->watches, watch))
322     return FALSE;
323   
324   _dbus_watch_ref (watch);
325
326   if (watch_list->add_watch_function != NULL)
327     {
328       if (!(* watch_list->add_watch_function) (watch,
329                                                watch_list->watch_data))
330         {
331           _dbus_list_remove_last (&watch_list->watches, watch);
332           _dbus_watch_unref (watch);
333           return FALSE;
334         }
335     }
336   
337   return TRUE;
338 }
339
340 /**
341  * Removes a watch from the watch list, invoking the
342  * application's DBusRemoveWatchFunction if appropriate.
343  *
344  * @param watch_list the watch list.
345  * @param watch the watch to remove.
346  */
347 void
348 _dbus_watch_list_remove_watch  (DBusWatchList *watch_list,
349                                 DBusWatch     *watch)
350 {
351   if (!_dbus_list_remove (&watch_list->watches, watch))
352     _dbus_assert_not_reached ("Nonexistent watch was removed");
353
354   if (watch_list->remove_watch_function != NULL)
355     (* watch_list->remove_watch_function) (watch,
356                                            watch_list->watch_data);
357   
358   _dbus_watch_unref (watch);
359 }
360
361 /**
362  * Sets a watch to the given enabled state, invoking the
363  * application's DBusWatchToggledFunction if appropriate.
364  *
365  * @param watch_list the watch list.
366  * @param watch the watch to toggle.
367  * @param enabled #TRUE to enable
368  */
369 void
370 _dbus_watch_list_toggle_watch (DBusWatchList           *watch_list,
371                                DBusWatch               *watch,
372                                dbus_bool_t              enabled)
373 {
374   enabled = !!enabled;
375   
376   if (enabled == watch->enabled)
377     return;
378
379   watch->enabled = enabled;
380   
381   if (watch_list->watch_toggled_function != NULL)
382     (* watch_list->watch_toggled_function) (watch,
383                                             watch_list->watch_data);
384 }
385
386 /**
387  * Sets the handler for the watch.
388  *
389  * @todo this function only exists because of the weird
390  * way connection watches are done, see the note
391  * in docs for _dbus_connection_handle_watch().
392  *
393  * @param watch the watch
394  * @param handler the new handler
395  * @param data the data
396  * @param free_data_function free data with this
397  */
398 void
399 _dbus_watch_set_handler (DBusWatch        *watch,
400                          DBusWatchHandler  handler,
401                          void             *data,
402                          DBusFreeFunction  free_data_function)
403 {
404   if (watch->free_handler_data_function)
405     (* watch->free_handler_data_function) (watch->handler_data);
406
407   watch->handler = handler;
408   watch->handler_data = data;
409   watch->free_handler_data_function = free_data_function;
410 }
411
412 /** @} */
413
414 /**
415  * @defgroup DBusWatch DBusWatch
416  * @ingroup  DBus
417  * @brief Object representing a file descriptor to be watched.
418  *
419  * Types and functions related to DBusWatch. A watch represents
420  * a file descriptor that the main loop needs to monitor,
421  * as in Qt's QSocketNotifier or GLib's g_io_add_watch().
422  * 
423  * @{
424  */
425
426 /**
427  * @typedef DBusWatch
428  *
429  * Opaque object representing a file descriptor
430  * to be watched for changes in readability,
431  * writability, or hangup.
432  */
433
434 /**
435  * Gets the file descriptor that should be watched.
436  *
437  * @param watch the DBusWatch object.
438  * @returns the file descriptor to watch.
439  */
440 int
441 dbus_watch_get_fd (DBusWatch *watch)
442 {
443   return watch->fd;
444 }
445
446 /**
447  * Gets flags from DBusWatchFlags indicating
448  * what conditions should be monitored on the
449  * file descriptor.
450  * 
451  * The flags returned will only contain DBUS_WATCH_READABLE
452  * and DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or
453  * DBUS_WATCH_ERROR; all watches implicitly include a watch
454  * for hangups, errors, and other exceptional conditions.
455  *
456  * @param watch the DBusWatch object.
457  * @returns the conditions to watch.
458  */
459 unsigned int
460 dbus_watch_get_flags (DBusWatch *watch)
461 {
462   _dbus_assert ((watch->flags & VALID_WATCH_FLAGS) == watch->flags);
463
464   return watch->flags;
465 }
466
467 /**
468  * Gets data previously set with dbus_watch_set_data()
469  * or #NULL if none.
470  *
471  * @param watch the DBusWatch object.
472  * @returns previously-set data.
473  */
474 void*
475 dbus_watch_get_data (DBusWatch *watch)
476 {
477   return watch->data;
478 }
479
480 /**
481  * Sets data which can be retrieved with dbus_watch_get_data().
482  * Intended for use by the DBusAddWatchFunction and
483  * DBusRemoveWatchFunction to store their own data.  For example with
484  * Qt you might store the QSocketNotifier for this watch and with GLib
485  * you might store a GSource.
486  *
487  * @param watch the DBusWatch object.
488  * @param data the data.
489  * @param free_data_function function to be called to free the data.
490  */
491 void
492 dbus_watch_set_data (DBusWatch        *watch,
493                      void             *data,
494                      DBusFreeFunction  free_data_function)
495 {
496   if (watch->free_data_function != NULL)
497     (* watch->free_data_function) (watch->data);
498   
499   watch->data = data;
500   watch->free_data_function = free_data_function;
501 }
502
503 /**
504  * Returns whether a watch is enabled or not. If not
505  * enabled, it should not be polled by the main loop.
506  *
507  * @param watch the DBusWatch object
508  * @returns #TRUE if the watch is enabled
509  */
510 dbus_bool_t
511 dbus_watch_get_enabled (DBusWatch *watch)
512 {
513   return watch->enabled;
514 }
515
516
517 /**
518  * Called to notify the D-BUS library when a previously-added watch is
519  * ready for reading or writing, or has an exception such as a hangup.
520  * 
521  * If this function returns #FALSE, then the file descriptor may still
522  * be ready for reading or writing, but more memory is needed in order
523  * to do the reading or writing. If you ignore the #FALSE return, your
524  * application may spin in a busy loop on the file descriptor until
525  * memory becomes available, but nothing more catastrophic should
526  * happen.
527  *
528  * dbus_watch_handle() cannot be called during the
529  * DBusAddWatchFunction, as the connection will not be ready to handle
530  * that watch yet.
531  * 
532  * It is not allowed to reference a DBusWatch after it has been passed
533  * to remove_function.
534  *
535  * @param watch the DBusWatch object.
536  * @param flags the poll condition using #DBusWatchFlags values
537  * @returns #FALSE if there wasn't enough memory 
538  */
539 dbus_bool_t
540 dbus_watch_handle (DBusWatch    *watch,
541                    unsigned int  flags)
542 {
543   _dbus_watch_sanitize_condition (watch, &flags);
544
545   if (flags == 0)
546     {
547       _dbus_verbose ("After sanitization, watch flags on fd %d were 0\n",
548                      watch->fd);
549       return TRUE;
550     }
551   else
552     return (* watch->handler) (watch, flags,
553                                watch->handler_data);
554 }
555
556
557 /** @} */