2003-05-03 Havoc Pennington <hp@pobox.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           _dbus_verbose ("Adding a watch on fd %d using newly-set add watch function\n",
266                          dbus_watch_get_fd (link->data));
267           
268           if (!(* add_function) (link->data, data))
269             {
270               /* remove it all again and return FALSE */
271               DBusList *link2;
272               
273               link2 = _dbus_list_get_first_link (&watch_list->watches);
274               while (link2 != link)
275                 {
276                   DBusList *next = _dbus_list_get_next_link (&watch_list->watches,
277                                                              link2);
278                   
279                   _dbus_verbose ("Removing watch on fd %d using newly-set remove function because initial add failed\n",
280                                  dbus_watch_get_fd (link2->data));
281                   
282                   (* remove_function) (link2->data, data);
283                   
284                   link2 = next;
285                 }
286
287               return FALSE;
288             }
289       
290           link = next;
291         }
292     }
293   
294   /* Remove all current watches from previous watch handlers */
295
296   if (watch_list->remove_watch_function != NULL)
297     {
298       _dbus_verbose ("Removing all pre-existing watches\n");
299       
300       _dbus_list_foreach (&watch_list->watches,
301                           (DBusForeachFunction) watch_list->remove_watch_function,
302                           watch_list->watch_data);
303     }
304
305   if (watch_list->watch_free_data_function != NULL)
306     (* watch_list->watch_free_data_function) (watch_list->watch_data);
307   
308   watch_list->add_watch_function = add_function;
309   watch_list->remove_watch_function = remove_function;
310   watch_list->watch_toggled_function = toggled_function;
311   watch_list->watch_data = data;
312   watch_list->watch_free_data_function = free_data_function;
313
314   return TRUE;
315 }
316
317 /**
318  * Adds a new watch to the watch list, invoking the
319  * application DBusAddWatchFunction if appropriate.
320  *
321  * @param watch_list the watch list.
322  * @param watch the watch to add.
323  * @returns #TRUE on success, #FALSE if no memory.
324  */
325 dbus_bool_t
326 _dbus_watch_list_add_watch (DBusWatchList *watch_list,
327                             DBusWatch     *watch)
328 {
329   if (!_dbus_list_append (&watch_list->watches, watch))
330     return FALSE;
331   
332   _dbus_watch_ref (watch);
333
334   if (watch_list->add_watch_function != NULL)
335     {
336       _dbus_verbose ("Adding watch on fd %d\n",
337                      dbus_watch_get_fd (watch));
338       
339       if (!(* watch_list->add_watch_function) (watch,
340                                                watch_list->watch_data))
341         {
342           _dbus_list_remove_last (&watch_list->watches, watch);
343           _dbus_watch_unref (watch);
344           return FALSE;
345         }
346     }
347   
348   return TRUE;
349 }
350
351 /**
352  * Removes a watch from the watch list, invoking the
353  * application's DBusRemoveWatchFunction if appropriate.
354  *
355  * @param watch_list the watch list.
356  * @param watch the watch to remove.
357  */
358 void
359 _dbus_watch_list_remove_watch  (DBusWatchList *watch_list,
360                                 DBusWatch     *watch)
361 {
362   if (!_dbus_list_remove (&watch_list->watches, watch))
363     _dbus_assert_not_reached ("Nonexistent watch was removed");
364   
365   if (watch_list->remove_watch_function != NULL)
366     {
367       _dbus_verbose ("Removing watch on fd %d\n",
368                      dbus_watch_get_fd (watch));
369       
370       (* watch_list->remove_watch_function) (watch,
371                                              watch_list->watch_data);
372     }
373   
374   _dbus_watch_unref (watch);
375 }
376
377 /**
378  * Sets a watch to the given enabled state, invoking the
379  * application's DBusWatchToggledFunction if appropriate.
380  *
381  * @param watch_list the watch list.
382  * @param watch the watch to toggle.
383  * @param enabled #TRUE to enable
384  */
385 void
386 _dbus_watch_list_toggle_watch (DBusWatchList           *watch_list,
387                                DBusWatch               *watch,
388                                dbus_bool_t              enabled)
389 {
390   enabled = !!enabled;
391   
392   if (enabled == watch->enabled)
393     return;
394
395   watch->enabled = enabled;
396   
397   if (watch_list->watch_toggled_function != NULL)
398     {
399       _dbus_verbose ("Toggling watch on fd %d to %d\n",
400                      dbus_watch_get_fd (watch), watch->enabled);
401       
402       (* watch_list->watch_toggled_function) (watch,
403                                               watch_list->watch_data);
404     }
405 }
406
407 /**
408  * Sets the handler for the watch.
409  *
410  * @todo this function only exists because of the weird
411  * way connection watches are done, see the note
412  * in docs for _dbus_connection_handle_watch().
413  *
414  * @param watch the watch
415  * @param handler the new handler
416  * @param data the data
417  * @param free_data_function free data with this
418  */
419 void
420 _dbus_watch_set_handler (DBusWatch        *watch,
421                          DBusWatchHandler  handler,
422                          void             *data,
423                          DBusFreeFunction  free_data_function)
424 {
425   if (watch->free_handler_data_function)
426     (* watch->free_handler_data_function) (watch->handler_data);
427
428   watch->handler = handler;
429   watch->handler_data = data;
430   watch->free_handler_data_function = free_data_function;
431 }
432
433 /** @} */
434
435 /**
436  * @defgroup DBusWatch DBusWatch
437  * @ingroup  DBus
438  * @brief Object representing a file descriptor to be watched.
439  *
440  * Types and functions related to DBusWatch. A watch represents
441  * a file descriptor that the main loop needs to monitor,
442  * as in Qt's QSocketNotifier or GLib's g_io_add_watch().
443  * 
444  * @{
445  */
446
447 /**
448  * @typedef DBusWatch
449  *
450  * Opaque object representing a file descriptor
451  * to be watched for changes in readability,
452  * writability, or hangup.
453  */
454
455 /**
456  * Gets the file descriptor that should be watched.
457  *
458  * @param watch the DBusWatch object.
459  * @returns the file descriptor to watch.
460  */
461 int
462 dbus_watch_get_fd (DBusWatch *watch)
463 {
464   return watch->fd;
465 }
466
467 /**
468  * Gets flags from DBusWatchFlags indicating
469  * what conditions should be monitored on the
470  * file descriptor.
471  * 
472  * The flags returned will only contain DBUS_WATCH_READABLE
473  * and DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or
474  * DBUS_WATCH_ERROR; all watches implicitly include a watch
475  * for hangups, errors, and other exceptional conditions.
476  *
477  * @param watch the DBusWatch object.
478  * @returns the conditions to watch.
479  */
480 unsigned int
481 dbus_watch_get_flags (DBusWatch *watch)
482 {
483   _dbus_assert ((watch->flags & VALID_WATCH_FLAGS) == watch->flags);
484
485   return watch->flags;
486 }
487
488 /**
489  * Gets data previously set with dbus_watch_set_data()
490  * or #NULL if none.
491  *
492  * @param watch the DBusWatch object.
493  * @returns previously-set data.
494  */
495 void*
496 dbus_watch_get_data (DBusWatch *watch)
497 {
498   return watch->data;
499 }
500
501 /**
502  * Sets data which can be retrieved with dbus_watch_get_data().
503  * Intended for use by the DBusAddWatchFunction and
504  * DBusRemoveWatchFunction to store their own data.  For example with
505  * Qt you might store the QSocketNotifier for this watch and with GLib
506  * you might store a GSource.
507  *
508  * @param watch the DBusWatch object.
509  * @param data the data.
510  * @param free_data_function function to be called to free the data.
511  */
512 void
513 dbus_watch_set_data (DBusWatch        *watch,
514                      void             *data,
515                      DBusFreeFunction  free_data_function)
516 {
517   _dbus_verbose ("Setting watch fd %d data to data = %p function = %p from data = %p function = %p\n",
518                  dbus_watch_get_fd (watch),
519                  data, free_data_function, watch->data, watch->free_data_function);
520   
521   if (watch->free_data_function != NULL)
522     (* watch->free_data_function) (watch->data);
523   
524   watch->data = data;
525   watch->free_data_function = free_data_function;
526 }
527
528 /**
529  * Returns whether a watch is enabled or not. If not
530  * enabled, it should not be polled by the main loop.
531  *
532  * @param watch the DBusWatch object
533  * @returns #TRUE if the watch is enabled
534  */
535 dbus_bool_t
536 dbus_watch_get_enabled (DBusWatch *watch)
537 {
538   return watch->enabled;
539 }
540
541
542 /**
543  * Called to notify the D-BUS library when a previously-added watch is
544  * ready for reading or writing, or has an exception such as a hangup.
545  * 
546  * If this function returns #FALSE, then the file descriptor may still
547  * be ready for reading or writing, but more memory is needed in order
548  * to do the reading or writing. If you ignore the #FALSE return, your
549  * application may spin in a busy loop on the file descriptor until
550  * memory becomes available, but nothing more catastrophic should
551  * happen.
552  *
553  * dbus_watch_handle() cannot be called during the
554  * DBusAddWatchFunction, as the connection will not be ready to handle
555  * that watch yet.
556  * 
557  * It is not allowed to reference a DBusWatch after it has been passed
558  * to remove_function.
559  *
560  * @param watch the DBusWatch object.
561  * @param flags the poll condition using #DBusWatchFlags values
562  * @returns #FALSE if there wasn't enough memory 
563  */
564 dbus_bool_t
565 dbus_watch_handle (DBusWatch    *watch,
566                    unsigned int  flags)
567 {
568 #ifndef DBUS_DISABLE_CHECKS
569   if (watch->fd < 0 || watch->flags == 0)
570     {
571       _dbus_warn ("%s: Watch is invalid, it should have been removed\n",
572                   _DBUS_FUNCTION_NAME);
573       return TRUE;
574     }
575 #endif
576     
577   _dbus_return_val_if_fail (watch->fd >= 0 /* fails if watch was removed */, TRUE);
578   
579   _dbus_watch_sanitize_condition (watch, &flags);
580
581   if (flags == 0)
582     {
583       _dbus_verbose ("After sanitization, watch flags on fd %d were 0\n",
584                      watch->fd);
585       return TRUE;
586     }
587   else
588     return (* watch->handler) (watch, flags,
589                                watch->handler_data);
590 }
591
592
593 /** @} */