Bug 575708 - runaway inotify madness ...
[platform/upstream/glib.git] / gio / gfilemonitor.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include "config.h"
24 #include <string.h>
25
26 #include "gfilemonitor.h"
27 #include "gio-marshal.h"
28 #include "gioenumtypes.h"
29 #include "gfile.h"
30 #include "gvfs.h"
31 #include "glibintl.h"
32
33 #include "gioalias.h"
34
35 struct _FileChange;
36 typedef struct _FileChange FileChange;
37 static void file_change_free (FileChange *change);
38
39 /**
40  * SECTION:gfilemonitor
41  * @short_description: File Monitor
42  * @include: gio/gio.h
43  *
44  * Monitors a file or directory for changes.
45  *
46  * To obtain a #GFileMonitor for a file or directory, use
47  * g_file_monitor(), g_file_monitor_file(), or
48  * g_file_monitor_directory().
49  *
50  * To get informed about changes to the file or directory you
51  * are monitoring, connect to the #GFileMonitor::changed signal.
52  **/
53
54 G_LOCK_DEFINE_STATIC(cancelled);
55
56 enum {
57   CHANGED,
58   LAST_SIGNAL
59 };
60
61 /* work around a limitation of the aliasing foo */
62 #undef g_file_monitor
63
64 G_DEFINE_ABSTRACT_TYPE (GFileMonitor, g_file_monitor, G_TYPE_OBJECT);
65
66 typedef struct {
67   GFile *file;
68   guint32 last_sent_change_time; /* 0 == not sent */
69   guint32 send_delayed_change_at; /* 0 == never */
70   guint32 send_virtual_changes_done_at; /* 0 == never */
71 } RateLimiter;
72
73 struct _GFileMonitorPrivate {
74   gboolean cancelled;
75   int rate_limit_msec;
76
77   /* Rate limiting change events */
78   GHashTable *rate_limiter;
79
80   guint pending_file_change_id;
81   GSList *pending_file_changes; /* FileChange */
82
83   GSource *timeout;
84   guint32 timeout_fires_at;
85 };
86
87 enum {
88   PROP_0,
89   PROP_RATE_LIMIT,
90   PROP_CANCELLED
91 };
92
93 static void
94 g_file_monitor_set_property (GObject      *object,
95                              guint         prop_id,
96                              const GValue *value,
97                              GParamSpec   *pspec)
98 {
99   GFileMonitor *monitor;
100
101   monitor = G_FILE_MONITOR (object);
102
103   switch (prop_id)
104     {
105     case PROP_RATE_LIMIT:
106       g_file_monitor_set_rate_limit (monitor, g_value_get_int (value));
107       break;
108
109     default:
110       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
111       break;
112     }
113 }
114
115 static void
116 g_file_monitor_get_property (GObject    *object,
117                              guint       prop_id,
118                              GValue     *value,
119                              GParamSpec *pspec)
120 {
121   GFileMonitor *monitor;
122   GFileMonitorPrivate *priv;
123
124   monitor = G_FILE_MONITOR (object);
125   priv = monitor->priv;
126
127   switch (prop_id)
128     {
129     case PROP_RATE_LIMIT:
130       g_value_set_int (value, priv->rate_limit_msec);
131       break;
132
133     case PROP_CANCELLED:
134       G_LOCK (cancelled);
135       g_value_set_boolean (value, priv->cancelled);
136       G_UNLOCK (cancelled);
137       break;
138
139     default:
140       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
141       break;
142     }
143 }
144
145 #define DEFAULT_RATE_LIMIT_MSECS 800
146 #define DEFAULT_VIRTUAL_CHANGES_DONE_DELAY_SECS 2
147
148 static guint signals[LAST_SIGNAL] = { 0 };
149
150 static void
151 rate_limiter_free (RateLimiter *limiter)
152 {
153   g_object_unref (limiter->file);
154   g_slice_free (RateLimiter, limiter);
155 }
156
157 static void
158 g_file_monitor_finalize (GObject *object)
159 {
160   GFileMonitor *monitor;
161
162   monitor = G_FILE_MONITOR (object);
163
164   if (monitor->priv->timeout)
165     {
166       g_source_destroy (monitor->priv->timeout);
167       g_source_unref (monitor->priv->timeout);
168     }
169
170   g_hash_table_destroy (monitor->priv->rate_limiter);
171
172   G_OBJECT_CLASS (g_file_monitor_parent_class)->finalize (object);
173 }
174
175 static void
176 g_file_monitor_dispose (GObject *object)
177 {
178   GFileMonitor *monitor;
179   GFileMonitorPrivate *priv;
180   
181   monitor = G_FILE_MONITOR (object);
182   priv = monitor->priv;
183
184   if (priv->pending_file_change_id)
185     {
186       g_source_remove (priv->pending_file_change_id);
187       priv->pending_file_change_id = 0;
188     }
189   g_slist_foreach (priv->pending_file_changes, (GFunc) file_change_free, NULL);
190   g_slist_free (priv->pending_file_changes);
191   priv->pending_file_changes = NULL;
192
193   /* Make sure we cancel on last unref */
194   g_file_monitor_cancel (monitor);
195
196   G_OBJECT_CLASS (g_file_monitor_parent_class)->dispose (object);
197 }
198
199 static void
200 g_file_monitor_class_init (GFileMonitorClass *klass)
201 {
202   GObjectClass *object_class;
203   
204   g_type_class_add_private (klass, sizeof (GFileMonitorPrivate));
205   
206   object_class = G_OBJECT_CLASS (klass);
207   object_class->finalize = g_file_monitor_finalize;
208   object_class->dispose = g_file_monitor_dispose;
209   object_class->get_property = g_file_monitor_get_property;
210   object_class->set_property = g_file_monitor_set_property;
211
212   /**
213    * GFileMonitor::changed:
214    * @monitor: a #GFileMonitor.
215    * @file: a #GFile.
216    * @other_file: a #GFile.
217    * @event_type: a #GFileMonitorEvent.
218    * 
219    * Emitted when a file has been changed. 
220    **/
221   signals[CHANGED] =
222     g_signal_new (I_("changed"),
223                   G_TYPE_FILE_MONITOR,
224                   G_SIGNAL_RUN_LAST,
225                   G_STRUCT_OFFSET (GFileMonitorClass, changed),
226                   NULL, NULL,
227                   _gio_marshal_VOID__OBJECT_OBJECT_ENUM,
228                   G_TYPE_NONE, 3,
229                   G_TYPE_FILE, G_TYPE_FILE, G_TYPE_FILE_MONITOR_EVENT);
230
231   g_object_class_install_property (object_class,
232                                    PROP_RATE_LIMIT,
233                                    g_param_spec_int ("rate-limit",
234                                                      P_("Rate limit"),
235                                                      P_("The limit of the monitor to watch for changes, in milliseconds"),
236                                                      0, G_MAXINT,
237                                                      DEFAULT_RATE_LIMIT_MSECS,
238                                                      G_PARAM_READWRITE|
239                                                      G_PARAM_STATIC_NAME|G_PARAM_STATIC_NICK|G_PARAM_STATIC_BLURB));
240
241   g_object_class_install_property (object_class,
242                                    PROP_CANCELLED,
243                                    g_param_spec_boolean ("cancelled",
244                                                          P_("Cancelled"),
245                                                          P_("Whether the monitor has been cancelled"),
246                                                          FALSE,
247                                                          G_PARAM_READABLE|
248                                                          G_PARAM_STATIC_NAME|G_PARAM_STATIC_NICK|G_PARAM_STATIC_BLURB));
249 }
250
251 static void
252 g_file_monitor_init (GFileMonitor *monitor)
253 {
254   monitor->priv = G_TYPE_INSTANCE_GET_PRIVATE (monitor,
255                                                G_TYPE_FILE_MONITOR,
256                                                GFileMonitorPrivate);
257   monitor->priv->rate_limit_msec = DEFAULT_RATE_LIMIT_MSECS;
258   monitor->priv->rate_limiter = g_hash_table_new_full (g_file_hash, (GEqualFunc)g_file_equal,
259                                                        NULL, (GDestroyNotify) rate_limiter_free);
260 }
261
262 /**
263  * g_file_monitor_is_cancelled:
264  * @monitor: a #GFileMonitor
265  * 
266  * Returns whether the monitor is canceled.
267  *
268  * Returns: %TRUE if monitor is canceled. %FALSE otherwise.
269  **/
270 gboolean
271 g_file_monitor_is_cancelled (GFileMonitor *monitor)
272 {
273   gboolean res;
274
275   g_return_val_if_fail (G_IS_FILE_MONITOR (monitor), FALSE);
276
277   G_LOCK (cancelled);
278   res = monitor->priv->cancelled;
279   G_UNLOCK (cancelled);
280   
281   return res;
282 }
283
284 /**
285  * g_file_monitor_cancel:
286  * @monitor: a #GFileMonitor.
287  * 
288  * Cancels a file monitor.
289  * 
290  * Returns: %TRUE if monitor was cancelled.
291  **/
292 gboolean
293 g_file_monitor_cancel (GFileMonitor* monitor)
294 {
295   GFileMonitorClass *klass;
296   
297   g_return_val_if_fail (G_IS_FILE_MONITOR (monitor), FALSE);
298   
299   G_LOCK (cancelled);
300   if (monitor->priv->cancelled)
301     {
302       G_UNLOCK (cancelled);
303       return TRUE;
304     }
305   
306   monitor->priv->cancelled = TRUE;
307   G_UNLOCK (cancelled);
308   
309   g_object_notify (G_OBJECT (monitor), "cancelled");
310
311   klass = G_FILE_MONITOR_GET_CLASS (monitor);
312   return (* klass->cancel) (monitor);
313 }
314
315 /**
316  * g_file_monitor_set_rate_limit:
317  * @monitor: a #GFileMonitor.
318  * @limit_msecs: a integer with the limit in milliseconds to 
319  * poll for changes.
320  *
321  * Sets the rate limit to which the @monitor will report
322  * consecutive change events to the same file. 
323  * 
324  **/
325 void
326 g_file_monitor_set_rate_limit (GFileMonitor *monitor,
327                                int           limit_msecs)
328 {
329   GFileMonitorPrivate *priv;
330   
331   g_return_if_fail (G_IS_FILE_MONITOR (monitor));
332   
333   priv = monitor->priv;
334   if (priv->rate_limit_msec != limit_msecs)
335     {
336       monitor->priv->rate_limit_msec = limit_msecs;
337       g_object_notify (G_OBJECT (monitor), "rate-limit");
338     }
339 }
340
341 struct _FileChange {
342   GFile             *child;
343   GFile             *other_file;
344   GFileMonitorEvent  event_type;
345 };
346
347 static void
348 file_change_free (FileChange *change)
349 {
350   g_object_unref (change->child);
351   if (change->other_file)
352     g_object_unref (change->other_file);
353   
354   g_slice_free (FileChange, change);
355 }
356
357 static gboolean
358 emit_cb (gpointer data)
359 {
360   GFileMonitor *monitor = G_FILE_MONITOR (data);
361   GSList *pending, *iter;
362   
363   pending = g_slist_reverse (monitor->priv->pending_file_changes);
364   monitor->priv->pending_file_changes = NULL;
365   monitor->priv->pending_file_change_id = 0;
366
367   for (iter = pending; iter; iter = iter->next)
368     {
369        FileChange *change = iter->data;
370        g_signal_emit (monitor, signals[CHANGED], 0,
371                       change->child, change->other_file, change->event_type);
372        file_change_free (change);
373     }
374   g_slist_free (pending);
375   return FALSE;
376 }
377
378 static void
379 emit_in_idle (GFileMonitor      *monitor,
380               GFile             *child,
381               GFile             *other_file,
382               GFileMonitorEvent  event_type)
383 {
384   GSource *source;
385   FileChange *change;
386   GFileMonitorPrivate *priv;
387
388   priv = monitor->priv;
389
390   change = g_slice_new (FileChange);
391
392   change->child = g_object_ref (child);
393   if (other_file)
394     change->other_file = g_object_ref (other_file);
395   else
396     change->other_file = NULL;
397   change->event_type = event_type;
398
399   if (!priv->pending_file_change_id)
400     {
401       source = g_idle_source_new ();
402       g_source_set_priority (source, 0);
403
404       /* We don't ref here - instead dispose will free any
405        * pending idles.
406        */
407       g_source_set_callback (source, emit_cb, monitor, NULL);
408       priv->pending_file_change_id = g_source_attach (source, NULL);
409       g_source_unref (source);
410     }
411   /* We reverse this in the processor */
412   priv->pending_file_changes = g_slist_prepend (priv->pending_file_changes, change);
413 }
414
415 static guint32
416 get_time_msecs (void)
417 {
418   return g_thread_gettime() / (1000 * 1000);
419 }
420
421 static guint32
422 time_difference (guint32 from, guint32 to)
423 {
424   if (from > to)
425     return 0;
426   return to - from;
427 }
428
429 /* Change event rate limiting support: */
430
431 static RateLimiter *
432 new_limiter (GFileMonitor *monitor,
433              GFile             *file)
434 {
435   RateLimiter *limiter;
436
437   limiter = g_slice_new0 (RateLimiter);
438   limiter->file = g_object_ref (file);
439   g_hash_table_insert (monitor->priv->rate_limiter, file, limiter);
440   
441   return limiter;
442 }
443
444 static void
445 rate_limiter_send_virtual_changes_done_now (GFileMonitor *monitor, 
446                                             RateLimiter  *limiter)
447 {
448   if (limiter->send_virtual_changes_done_at != 0)
449     {
450       emit_in_idle (monitor, limiter->file, NULL,
451                     G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT);
452       limiter->send_virtual_changes_done_at = 0;
453     }
454 }
455
456 static void
457 rate_limiter_send_delayed_change_now (GFileMonitor *monitor, 
458                                       RateLimiter *limiter, 
459                                       guint32 time_now)
460 {
461   if (limiter->send_delayed_change_at != 0)
462     {
463       emit_in_idle (monitor, 
464                     limiter->file, NULL,
465                     G_FILE_MONITOR_EVENT_CHANGED);
466       limiter->send_delayed_change_at = 0;
467       limiter->last_sent_change_time = time_now;
468     }
469 }
470
471 typedef struct {
472   guint32 min_time;
473   guint32 time_now;
474   GFileMonitor *monitor;
475 } ForEachData;
476
477 static gboolean
478 calc_min_time (GFileMonitor *monitor, 
479                RateLimiter *limiter, 
480                guint32 time_now, 
481                guint32 *min_time)
482 {
483   gboolean delete_me;
484   guint32 expire_at;
485
486   delete_me = TRUE;
487
488   if (limiter->last_sent_change_time != 0)
489     {
490       /* Set a timeout at 2*rate limit so that we can clear out the change from the hash eventualy */
491       expire_at = limiter->last_sent_change_time + 2 * monitor->priv->rate_limit_msec;
492
493       if (time_difference (time_now, expire_at) > 0)
494         {
495           delete_me = FALSE;
496           *min_time = MIN (*min_time,
497                            time_difference (time_now, expire_at));
498         }
499     }
500
501   if (limiter->send_delayed_change_at != 0)
502     {
503       delete_me = FALSE;
504       *min_time = MIN (*min_time,
505                        time_difference (time_now, limiter->send_delayed_change_at));
506     }
507
508   if (limiter->send_virtual_changes_done_at != 0)
509     {
510       delete_me = FALSE;
511       *min_time = MIN (*min_time,
512                        time_difference (time_now, limiter->send_virtual_changes_done_at));
513     }
514
515   return delete_me;
516 }
517
518 static gboolean
519 foreach_rate_limiter_fire (gpointer key,
520                            gpointer value,
521                            gpointer user_data)
522 {
523   RateLimiter *limiter = value;
524   ForEachData *data = user_data;
525
526   if (limiter->send_delayed_change_at != 0 &&
527       time_difference (data->time_now, limiter->send_delayed_change_at) == 0)
528     rate_limiter_send_delayed_change_now (data->monitor, limiter, data->time_now);
529   
530   if (limiter->send_virtual_changes_done_at != 0 &&
531       time_difference (data->time_now, limiter->send_virtual_changes_done_at) == 0)
532     rate_limiter_send_virtual_changes_done_now (data->monitor, limiter);
533   
534   return calc_min_time (data->monitor, limiter, data->time_now, &data->min_time);
535 }
536
537 static gboolean 
538 rate_limiter_timeout (gpointer timeout_data)
539 {
540   GFileMonitor *monitor = timeout_data;
541   ForEachData data;
542   GSource *source;
543   
544   data.min_time = G_MAXUINT32;
545   data.monitor = monitor;
546   data.time_now = get_time_msecs ();
547   g_hash_table_foreach_remove (monitor->priv->rate_limiter,
548                                foreach_rate_limiter_fire,
549                                &data);
550   
551   /* Remove old timeout */
552   if (monitor->priv->timeout)
553     {
554       g_source_destroy (monitor->priv->timeout);
555       g_source_unref (monitor->priv->timeout);
556       monitor->priv->timeout = NULL;
557       monitor->priv->timeout_fires_at = 0;
558     }
559   
560   /* Set up new timeout */
561   if (data.min_time != G_MAXUINT32)
562     {
563       source = g_timeout_source_new (data.min_time + 1); /* + 1 to make sure we've really passed the time */
564       g_source_set_callback (source, rate_limiter_timeout, monitor, NULL);
565       g_source_attach (source, NULL);
566       
567       monitor->priv->timeout = source;
568       monitor->priv->timeout_fires_at = data.time_now + data.min_time; 
569     }
570   
571   return FALSE;
572 }
573
574 static gboolean
575 foreach_rate_limiter_update (gpointer key,
576                              gpointer value,
577                              gpointer user_data)
578 {
579   RateLimiter *limiter = value;
580   ForEachData *data = user_data;
581
582   return calc_min_time (data->monitor, limiter, data->time_now, &data->min_time);
583 }
584
585 static void
586 update_rate_limiter_timeout (GFileMonitor *monitor, 
587                              guint new_time)
588 {
589   ForEachData data;
590   GSource *source;
591   
592   if (monitor->priv->timeout_fires_at != 0 && new_time != 0 &&
593       time_difference (new_time, monitor->priv->timeout_fires_at) == 0)
594     return; /* Nothing to do, we already fire earlier than that */
595
596   data.min_time = G_MAXUINT32;
597   data.monitor = monitor;
598   data.time_now = get_time_msecs ();
599   g_hash_table_foreach_remove (monitor->priv->rate_limiter,
600                                foreach_rate_limiter_update,
601                                &data);
602
603   /* Remove old timeout */
604   if (monitor->priv->timeout)
605     {
606       g_source_destroy (monitor->priv->timeout);
607       g_source_unref (monitor->priv->timeout);
608       monitor->priv->timeout_fires_at = 0;
609       monitor->priv->timeout = NULL;
610     }
611
612   /* Set up new timeout */
613   if (data.min_time != G_MAXUINT32)
614     {
615       source = g_timeout_source_new (data.min_time + 1);  /* + 1 to make sure we've really passed the time */
616       g_source_set_callback (source, rate_limiter_timeout, monitor, NULL);
617       g_source_attach (source, NULL);
618       
619       monitor->priv->timeout = source;
620       monitor->priv->timeout_fires_at = data.time_now + data.min_time; 
621     }
622 }
623
624 /**
625  * g_file_monitor_emit_event:
626  * @monitor: a #GFileMonitor.
627  * @child: a #GFile.
628  * @other_file: a #GFile.
629  * @event_type: a set of #GFileMonitorEvent flags.
630  * 
631  * Emits the #GFileMonitor::changed signal if a change
632  * has taken place. Should be called from file monitor 
633  * implementations only.
634  *
635  * The signal will be emitted from an idle handler.
636  **/
637 void
638 g_file_monitor_emit_event (GFileMonitor      *monitor,
639                            GFile             *child,
640                            GFile             *other_file,
641                            GFileMonitorEvent  event_type)
642 {
643   guint32 time_now, since_last;
644   gboolean emit_now;
645   RateLimiter *limiter;
646
647   g_return_if_fail (G_IS_FILE_MONITOR (monitor));
648   g_return_if_fail (G_IS_FILE (child));
649
650   limiter = g_hash_table_lookup (monitor->priv->rate_limiter, child);
651
652   if (event_type != G_FILE_MONITOR_EVENT_CHANGED)
653     {
654       if (limiter)
655         {
656           rate_limiter_send_delayed_change_now (monitor, limiter, get_time_msecs ());
657           if (event_type == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT)
658             limiter->send_virtual_changes_done_at = 0;
659           else
660             rate_limiter_send_virtual_changes_done_now (monitor, limiter);
661           update_rate_limiter_timeout (monitor, 0);
662         }
663       emit_in_idle (monitor, child, other_file, event_type);
664     }
665   else
666     {
667       /* Changed event, rate limit */
668       time_now = get_time_msecs ();
669       emit_now = TRUE;
670       
671       if (limiter)
672         {
673           since_last = time_difference (limiter->last_sent_change_time, time_now);
674           if (since_last < monitor->priv->rate_limit_msec)
675             {
676               /* We ignore this change, but arm a timer so that we can fire it later if we
677                  don't get any other events (that kill this timeout) */
678               emit_now = FALSE;
679               if (limiter->send_delayed_change_at == 0)
680                 {
681                   limiter->send_delayed_change_at = time_now + monitor->priv->rate_limit_msec;
682                   update_rate_limiter_timeout (monitor, limiter->send_delayed_change_at);
683                 }
684             }
685         }
686       
687       if (limiter == NULL)
688         limiter = new_limiter (monitor, child);
689       
690       if (emit_now)
691         {
692           emit_in_idle (monitor, child, other_file, event_type);
693           
694           limiter->last_sent_change_time = time_now;
695           limiter->send_delayed_change_at = 0;
696           /* Set a timeout of 2*rate limit so that we can clear out the change from the hash eventualy */
697           update_rate_limiter_timeout (monitor, time_now + 2 * monitor->priv->rate_limit_msec);
698         }
699       
700       /* Schedule a virtual change done. This is removed if we get a real one, and
701          postponed if we get more change events. */
702       
703       limiter->send_virtual_changes_done_at = time_now + DEFAULT_VIRTUAL_CHANGES_DONE_DELAY_SECS * 1000;
704       update_rate_limiter_timeout (monitor, limiter->send_virtual_changes_done_at);
705     }
706 }
707
708 #define __G_FILE_MONITOR_C__
709 #include "gioaliasdef.c"