Implement g_cancellable_release_fd()
[platform/upstream/glib.git] / gio / gcancellable.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 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #include <fcntl.h>
28 #include <gioerror.h>
29 #ifdef G_OS_WIN32
30 #include <windows.h>
31 #include <io.h>
32 #endif
33 #include "gcancellable.h"
34 #include "glibintl.h"
35
36 #include "gioalias.h"
37
38 /**
39  * SECTION:gcancellable
40  * @short_description: Thread-safe Operation Cancellation Stack
41  * @include: gio/gio.h
42  *
43  * GCancellable is a thread-safe operation cancellation stack used 
44  * throughout GIO to allow for cancellation of synchronous and
45  * asynchronous operations.
46  */
47
48 enum {
49   CANCELLED,
50   LAST_SIGNAL
51 };
52
53 struct _GCancellablePrivate
54 {
55   guint cancelled : 1;
56   guint cancelled_running : 1;
57   guint cancelled_running_waiting : 1;
58
59   guint fd_refcount;
60   int cancel_pipe[2];
61
62 #ifdef G_OS_WIN32
63   HANDLE event;
64 #endif
65 };
66
67 static guint signals[LAST_SIGNAL] = { 0 };
68
69 G_DEFINE_TYPE (GCancellable, g_cancellable, G_TYPE_OBJECT);
70
71 static GStaticPrivate current_cancellable = G_STATIC_PRIVATE_INIT;
72 G_LOCK_DEFINE_STATIC(cancellable);
73 static GCond *cancellable_cond = NULL;
74   
75 static void
76 g_cancellable_close_pipe (GCancellable *cancellable)
77 {
78   GCancellablePrivate *priv;
79   
80   priv = cancellable->priv;
81
82   if (priv->cancel_pipe[0] != -1)
83     {
84       close (priv->cancel_pipe[0]);
85       priv->cancel_pipe[0] = -1;
86     }
87   
88   if (priv->cancel_pipe[1] != -1)
89     {
90       close (priv->cancel_pipe[1]);
91       priv->cancel_pipe[1] = -1;
92     }
93
94 #ifdef G_OS_WIN32
95   if (priv->event)
96     {
97       CloseHandle (priv->event);
98       priv->event = NULL;
99     }
100 #endif
101 }
102
103 static void
104 g_cancellable_finalize (GObject *object)
105 {
106   GCancellable *cancellable = G_CANCELLABLE (object);
107
108   g_cancellable_close_pipe (cancellable);
109
110   G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
111 }
112
113 static void
114 g_cancellable_class_init (GCancellableClass *klass)
115 {
116   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
117
118   g_type_class_add_private (klass, sizeof (GCancellablePrivate));
119
120   if (cancellable_cond == NULL && g_thread_supported ())
121     cancellable_cond = g_cond_new ();
122   
123   gobject_class->finalize = g_cancellable_finalize;
124
125   /**
126    * GCancellable::cancelled:
127    * @cancellable: a #GCancellable.
128    * 
129    * Emitted when the operation has been cancelled.
130    * 
131    * Can be used by implementations of cancellable operations. If the
132    * operation is cancelled from another thread, the signal will be
133    * emitted in the thread that cancelled the operation, not the
134    * thread that is running the operation.
135    *
136    * Note that disconnecting from this signal (or any signal) in a
137    * multi-threaded program is prone to race conditions. For instance
138    * it is possible that a signal handler may be invoked even
139    * <emphasis>after</emphasis> a call to
140    * g_signal_handler_disconnect() for that handler has already
141    * returned.
142    * 
143    * There is also a problem when cancellation happen
144    * right before connecting to the signal. If this happens the
145    * signal will unexpectedly not be emitted, and checking before
146    * connecting to the signal leaves a race condition where this is
147    * still happening.
148    *
149    * In order to make it safe and easy to connect handlers there
150    * are two helper functions: g_cancellable_connect() and
151    * g_cancellable_disconnect() which protect against problems
152    * like this.
153    *
154    * An example of how to us this:
155    * |[
156    *     /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
157    *     if (g_cancellable_set_error_if_cancelled (cancellable))
158    *       return;
159    *
160    *     /<!-- -->* Set up all the data needed to be able to
161    *      * handle cancellation of the operation *<!-- -->/
162    *     my_data = my_data_new (...);
163    *
164    *     id = 0;
165    *     if (cancellable)
166    *       id = g_cancellable_connect (cancellable,
167    *                                  G_CALLBACK (cancelled_handler)
168    *                                  data, NULL);
169    *
170    *     /<!-- -->* cancellable operation here... *<!-- -->/
171    *
172    *     g_cancellable_disconnect (cancellable, id);
173    *
174    *     /<!-- -->* cancelled_handler is never called after this, it
175    *      * is now safe to free the data *<!-- -->/
176    *     my_data_free (my_data);  
177    * ]|
178    *
179    * Note that the cancelled signal is emitted in the thread that
180    * the user cancelled from, which may be the main thread. So, the
181    * cancellable signal should not do something that can block.
182    */
183   signals[CANCELLED] =
184     g_signal_new (I_("cancelled"),
185                   G_TYPE_FROM_CLASS (gobject_class),
186                   G_SIGNAL_RUN_LAST,
187                   G_STRUCT_OFFSET (GCancellableClass, cancelled),
188                   NULL, NULL,
189                   g_cclosure_marshal_VOID__VOID,
190                   G_TYPE_NONE, 0);
191   
192 }
193
194 #ifndef G_OS_WIN32
195 static void
196 set_fd_nonblocking (int fd)
197 {
198 #ifdef F_GETFL
199   glong fcntl_flags;
200   fcntl_flags = fcntl (fd, F_GETFL);
201
202 #ifdef O_NONBLOCK
203   fcntl_flags |= O_NONBLOCK;
204 #else
205   fcntl_flags |= O_NDELAY;
206 #endif
207
208   fcntl (fd, F_SETFL, fcntl_flags);
209 #endif
210 }
211
212 static void
213 set_fd_close_exec (int fd)
214 {
215   int flags;
216
217   flags = fcntl (fd, F_GETFD, 0);
218   if (flags != -1 && (flags & FD_CLOEXEC) == 0)
219     {
220       flags |= FD_CLOEXEC;
221       fcntl (fd, F_SETFD, flags);
222     }
223 }
224
225
226 static void
227 g_cancellable_open_pipe (GCancellable *cancellable)
228 {
229   GCancellablePrivate *priv;
230
231   priv = cancellable->priv;
232   if (pipe (priv->cancel_pipe) == 0)
233     {
234       /* Make them nonblocking, just to be sure we don't block
235        * on errors and stuff
236        */
237       set_fd_nonblocking (priv->cancel_pipe[0]);
238       set_fd_nonblocking (priv->cancel_pipe[1]);
239       set_fd_close_exec (priv->cancel_pipe[0]);
240       set_fd_close_exec (priv->cancel_pipe[1]);
241     }
242 }
243 #endif
244
245 static void
246 g_cancellable_init (GCancellable *cancellable)
247 {
248   cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
249                                                    G_TYPE_CANCELLABLE,
250                                                    GCancellablePrivate);
251   cancellable->priv->cancel_pipe[0] = -1;
252   cancellable->priv->cancel_pipe[1] = -1;
253 }
254
255 /**
256  * g_cancellable_new:
257  * 
258  * Creates a new #GCancellable object.
259  *
260  * Applications that want to start one or more operations
261  * that should be cancellable should create a #GCancellable
262  * and pass it to the operations.
263  *
264  * One #GCancellable can be used in multiple consecutive
265  * operations, but not in multiple concurrent operations.
266  *  
267  * Returns: a #GCancellable.
268  **/
269 GCancellable *
270 g_cancellable_new (void)
271 {
272   return g_object_new (G_TYPE_CANCELLABLE, NULL);
273 }
274
275 /**
276  * g_cancellable_push_current:
277  * @cancellable: a #GCancellable object
278  *
279  * Pushes @cancellable onto the cancellable stack. The current
280  * cancllable can then be recieved using g_cancellable_get_current().
281  *
282  * This is useful when implementing cancellable operations in
283  * code that does not allow you to pass down the cancellable object.
284  *
285  * This is typically called automatically by e.g. #GFile operations,
286  * so you rarely have to call this yourself.
287  **/
288 void
289 g_cancellable_push_current (GCancellable *cancellable)
290 {
291   GSList *l;
292
293   g_return_if_fail (cancellable != NULL);
294
295   l = g_static_private_get (&current_cancellable);
296   l = g_slist_prepend (l, cancellable);
297   g_static_private_set (&current_cancellable, l, NULL);
298 }
299
300 /**
301  * g_cancellable_pop_current:
302  * @cancellable: a #GCancellable object
303  *
304  * Pops @cancellable off the cancellable stack (verifying that @cancellable
305  * is on the top of the stack).
306  **/
307 void
308 g_cancellable_pop_current (GCancellable *cancellable)
309 {
310   GSList *l;
311
312   l = g_static_private_get (&current_cancellable);
313
314   g_return_if_fail (l != NULL);
315   g_return_if_fail (l->data == cancellable);
316
317   l = g_slist_delete_link (l, l);
318   g_static_private_set (&current_cancellable, l, NULL);
319 }
320
321 /**
322  * g_cancellable_get_current:
323  *
324  * Gets the top cancellable from the stack.
325  *
326  * Returns: a #GCancellable from the top of the stack, or %NULL
327  * if the stack is empty.
328  **/
329 GCancellable *
330 g_cancellable_get_current  (void)
331 {
332   GSList *l;
333
334   l = g_static_private_get (&current_cancellable);
335   if (l == NULL)
336     return NULL;
337
338   return G_CANCELLABLE (l->data);
339 }
340
341 /**
342  * g_cancellable_reset:
343  * @cancellable: a #GCancellable object.
344  * 
345  * Resets @cancellable to its uncancelled state. 
346  **/
347 void 
348 g_cancellable_reset (GCancellable *cancellable)
349 {
350   GCancellablePrivate *priv;
351
352   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
353
354   G_LOCK(cancellable);
355
356   priv = cancellable->priv;
357   
358   while (priv->cancelled_running)
359     {
360       priv->cancelled_running_waiting = TRUE;
361       g_cond_wait (cancellable_cond,
362                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
363     }
364   
365   if (priv->cancelled)
366     {
367       char ch;
368       
369     /* Make sure we're not leaving old cancel state around */
370       
371 #ifdef G_OS_WIN32
372       if (priv->event)
373         ResetEvent (priv->event);
374       else
375 #endif
376       if (priv->cancel_pipe[0] != -1)
377         read (priv->cancel_pipe[0], &ch, 1);
378       priv->cancelled = FALSE;
379     }
380   G_UNLOCK(cancellable);
381 }
382
383 /**
384  * g_cancellable_is_cancelled:
385  * @cancellable: a #GCancellable or NULL.
386  * 
387  * Checks if a cancellable job has been cancelled.
388  * 
389  * Returns: %TRUE if @cancellable is cancelled, 
390  * FALSE if called with %NULL or if item is not cancelled. 
391  **/
392 gboolean
393 g_cancellable_is_cancelled (GCancellable *cancellable)
394 {
395   return cancellable != NULL && cancellable->priv->cancelled;
396 }
397
398 /**
399  * g_cancellable_set_error_if_cancelled:
400  * @cancellable: a #GCancellable object.
401  * @error: #GError to append error state to.
402  * 
403  * If the @cancellable is cancelled, sets the error to notify
404  * that the operation was cancelled.
405  * 
406  * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
407  **/
408 gboolean
409 g_cancellable_set_error_if_cancelled (GCancellable  *cancellable,
410                                       GError       **error)
411 {
412   if (g_cancellable_is_cancelled (cancellable))
413     {
414       g_set_error_literal (error,
415                            G_IO_ERROR,
416                            G_IO_ERROR_CANCELLED,
417                            _("Operation was cancelled"));
418       return TRUE;
419     }
420   
421   return FALSE;
422 }
423
424 /**
425  * g_cancellable_get_fd:
426  * @cancellable: a #GCancellable.
427  * 
428  * Gets the file descriptor for a cancellable job. This can be used to
429  * implement cancellable operations on Unix systems. The returned fd will
430  * turn readable when @cancellable is cancelled.
431  *
432  * You are not supposed to read from the fd yourself, just check for
433  * readable status. Reading to unset the readable status is done
434  * with g_cancellable_reset().
435  * 
436  * After a successful return from this function, you should use 
437  * g_cancellable_release_fd() to free up resources allocated for 
438  * the returned file descriptor.
439  *
440  * See also g_cancellable_make_pollfd().
441  *
442  * Returns: A valid file descriptor. %-1 if the file descriptor 
443  * is not supported, or on errors. 
444  **/
445 int
446 g_cancellable_get_fd (GCancellable *cancellable)
447 {
448   GCancellablePrivate *priv;
449   int fd;
450
451   if (cancellable == NULL)
452     return -1;
453
454   priv = cancellable->priv;
455
456 #ifdef G_OS_WIN32
457   return -1;
458 #else
459   G_LOCK(cancellable);
460   if (priv->cancel_pipe[0] == -1)
461     g_cancellable_open_pipe (cancellable);
462   fd = priv->cancel_pipe[0];
463   if (fd != -1)
464     priv->fd_refcount++;
465   G_UNLOCK(cancellable);
466 #endif
467
468   return fd;
469 }
470
471 /**
472  * g_cancellable_make_pollfd:
473  * @cancellable: a #GCancellable or %NULL
474  * @pollfd: a pointer to a #GPollFD
475  * 
476  * Creates a #GPollFD corresponding to @cancellable; this can be passed
477  * to g_poll() and used to poll for cancellation. This is useful both
478  * for unix systems without a native poll and for portability to
479  * windows.
480  *
481  * When this function returns %TRUE, you should use 
482  * g_cancellable_release_fd() to free up resources allocated for the 
483  * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
484  *
485  * If this function returns %FALSE, either no @cancellable was given or
486  * resource limits prevent this function from allocating the necessary 
487  * structures for polling. (On Linux, you will likely have reached 
488  * the maximum number of file descriptors.) The suggested way to handle
489  * these cases is to ignore the @cancellable.
490  *
491  * You are not supposed to read from the fd yourself, just check for
492  * readable status. Reading to unset the readable status is done
493  * with g_cancellable_reset().
494  *
495  * @Returns: %TRUE if @pollfd was successfully initialized, %FALSE on 
496  *           failure to prepare the cancellable.
497  * 
498  * @Since: 2.22
499  **/
500 gboolean
501 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
502 {
503   GCancellablePrivate *priv;
504
505   g_return_val_if_fail (pollfd != NULL, FALSE);
506   if (cancellable == NULL)
507     return FALSE;
508   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
509
510   priv = cancellable->priv;
511
512 #ifdef G_OS_WIN32
513   G_LOCK(cancellable);
514   if (priv->event == NULL)
515     {
516       /* A manual reset anonymous event, starting unset */
517       priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
518       if (priv->event == NULL)
519         {
520           G_UNLOCK(cancellable);
521           return FALSE;
522         }
523     }
524
525   priv->fd_refcount++;
526   G_UNLOCK(cancellable);
527
528   pollfd->fd = (gintptr)priv->event;
529 #else /* !G_OS_WIN32 */
530   {
531     int fd = g_cancellable_get_fd (cancellable);
532     if (fd == -1)
533       return FALSE;
534     pollfd->fd = fd;
535   }
536 #endif /* G_OS_WIN32 */
537   pollfd->events = G_IO_IN;
538   pollfd->revents = 0;
539
540   return TRUE;
541 }
542
543 /**
544  * g_cancellable_release_fd:
545  * @cancellable: a #GCancellable
546  *
547  * Releases a resources previously allocated by g_cancellable_get_fd()
548  * or g_cancellable_make_pollfd().
549  *
550  * For compatibility reasons with older releases, calling this function 
551  * is not strictly required, the resources will be automatically freed
552  * when the @cancellable is finalized. However, the @cancellable will
553  * block scarce file descriptors until it is finalized if this function
554  * is not called. This can cause the application to run out of file 
555  * descriptors when many #GCancellables are used at the same time.
556  * 
557  * @Since: 2.22
558  **/
559 void
560 g_cancellable_release_fd (GCancellable *cancellable)
561 {
562   GCancellablePrivate *priv;
563
564   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
565   g_return_if_fail (cancellable->priv->fd_refcount > 0);
566
567   priv = cancellable->priv;
568
569   G_LOCK (cancellable);
570   priv->fd_refcount--;
571   if (priv->fd_refcount == 0)
572     g_cancellable_close_pipe (cancellable);
573   G_UNLOCK (cancellable);
574 }
575
576 /**
577  * g_cancellable_cancel:
578  * @cancellable: a #GCancellable object.
579  * 
580  * Will set @cancellable to cancelled, and will emit the
581  * #GCancellable::cancelled signal. (However, see the warning about
582  * race conditions in the documentation for that signal if you are
583  * planning to connect to it.)
584  *
585  * This function is thread-safe. In other words, you can safely call
586  * it from a thread other than the one running the operation that was
587  * passed the @cancellable.
588  *
589  * The convention within gio is that cancelling an asynchronous
590  * operation causes it to complete asynchronously. That is, if you
591  * cancel the operation from the same thread in which it is running,
592  * then the operation's #GAsyncReadyCallback will not be invoked until
593  * the application returns to the main loop.
594  **/
595 void
596 g_cancellable_cancel (GCancellable *cancellable)
597 {
598   const char ch = 'x';
599   gboolean cancel;
600   GCancellablePrivate *priv;
601
602   if (cancellable == NULL ||
603       cancellable->priv->cancelled)
604     return;
605
606   priv = cancellable->priv;
607   cancel = FALSE;
608
609   G_LOCK(cancellable);
610   cancel = TRUE;
611   priv->cancelled = TRUE;
612   priv->cancelled_running = TRUE;
613 #ifdef G_OS_WIN32
614   if (priv->event)
615     SetEvent (priv->event);
616 #endif
617   if (priv->cancel_pipe[1] != -1)
618     write (priv->cancel_pipe[1], &ch, 1);
619   G_UNLOCK(cancellable);
620
621   if (cancel)
622     {
623       g_object_ref (cancellable);
624       g_signal_emit (cancellable, signals[CANCELLED], 0);
625
626       G_LOCK(cancellable);
627
628       priv->cancelled_running = FALSE;
629       if (priv->cancelled_running_waiting)
630         g_cond_broadcast (cancellable_cond);
631       priv->cancelled_running_waiting = FALSE;
632
633       G_UNLOCK(cancellable);
634
635       g_object_unref (cancellable);
636     }
637 }
638
639 /**
640  * g_cancellable_connect:
641  * @cancellable: A #GCancellable.
642  * @callback: The #GCallback to connect.
643  * @data: Data to pass to @callback.
644  * @data_destroy_func: Free function for @data or %NULL.
645  *
646  * Convenience function to connect to the #GCancellable::cancelled
647  * signal. Also handles the race condition that may happen
648  * if the cancellable is cancelled right before connecting.
649  *
650  * @callback is called at most once, either directly at the
651  * time of the connect if @cancellable is already cancelled,
652  * or when @cancellable is cancelled in some thread.
653  *
654  * @data_destroy_func will be called when the handler is
655  * disconnected, or immediately if the cancellable is already
656  * cancelled.
657  *
658  * See #GCancellable::cancelled for details on how to use this.
659  *
660  * Returns: The id of the signal handler or 0 if @cancellable has already
661  *          been cancelled.
662  *
663  * Since: 2.22
664  */
665 gulong
666 g_cancellable_connect (GCancellable   *cancellable,
667                        GCallback       callback,
668                        gpointer        data,
669                        GDestroyNotify  data_destroy_func)
670 {
671   gulong id;
672
673   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
674
675   G_LOCK (cancellable);
676
677   if (cancellable->priv->cancelled)
678     {
679       void (*_callback) (GCancellable *cancellable,
680                          gpointer      user_data);
681
682       _callback = (void *)callback;
683       id = 0;
684
685       _callback (cancellable, data);
686
687       if (data_destroy_func)
688         data_destroy_func (data);
689     }
690   else
691     {
692       id = g_signal_connect_data (cancellable, "cancelled",
693                                   callback, data,
694                                   (GClosureNotify) data_destroy_func,
695                                   0);
696     }
697   G_UNLOCK (cancellable);
698
699   return id;
700 }
701
702 /**
703  * g_cancellable_disconnect:
704  * @cancellable: A #GCancellable or %NULL.
705  * @handler_id: Handler id of the handler to be disconnected, or %0.
706  *
707  * Disconnects a handler from an cancellable instance similar to
708  * g_signal_handler_disconnect() but ensures that once this
709  * function returns the handler will not run anymore in any thread.
710  *
711  * This avoids a race condition where a thread cancels at the
712  * same time as the cancellable operation is finished and the
713  * signal handler is removed. See #GCancellable::cancelled for
714  * details on how to use this.
715  *
716  * If @cancellable is %NULL or @handler_id is %0 this function does
717  * nothing.
718  *
719  * Since: 2.22
720  */
721 void
722 g_cancellable_disconnect (GCancellable  *cancellable,
723                           gulong         handler_id)
724 {
725   GCancellablePrivate *priv;
726
727   if (handler_id == 0 ||  cancellable == NULL)
728     return;
729
730   G_LOCK (cancellable);
731
732   priv = cancellable->priv;
733
734   while (priv->cancelled_running)
735     {
736       priv->cancelled_running_waiting = TRUE;
737       g_cond_wait (cancellable_cond,
738                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
739     }
740
741   g_signal_handler_disconnect (cancellable, handler_id);
742   G_UNLOCK (cancellable);
743 }
744
745 #define __G_CANCELLABLE_C__
746 #include "gioaliasdef.c"