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