Merge remote branch 'gvdb/master'
[platform/upstream/glib.git] / gio / giostream.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright © 2008 codethink
4  * Copyright © 2009 Red Hat, Inc.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General
17  * Public License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *
21  * Authors: Ryan Lortie <desrt@desrt.ca>
22  *          Alexander Larsson <alexl@redhat.com>
23  */
24
25 #include "config.h"
26 #include <glib.h>
27 #include "glibintl.h"
28
29 #include "giostream.h"
30 #include <gio/gsimpleasyncresult.h>
31 #include <gio/gasyncresult.h>
32
33 #include "gioalias.h"
34
35 G_DEFINE_TYPE (GIOStream, g_io_stream, G_TYPE_OBJECT);
36
37 /**
38  * SECTION:giostream
39  * @short_description: Base class for implementing read/write streams
40  * @include: gio/gio.h
41  * @see_also: #GInputStream, #GOutputStream
42  *
43  * GIOStream represents an object that has both read and write streams.
44  * Generally the two streams acts as separate input and output streams,
45  * but they share some common resources and state. For instance, for
46  * seekable streams they may use the same position in both streams.
47  *
48  * Examples of #GIOStream objects are #GSocketConnection which represents
49  * a two-way network connection, and #GFileIOStream which represent a
50  * file handle opened in read-write mode.
51  *
52  * To do the actual reading and writing you need to get the substreams
53  * with g_io_stream_get_input_stream() and g_io_stream_get_output_stream().
54  *
55  * The #GIOStream object owns the input and the output streams, not the other
56  * way around, so keeping the substreams alive will not keep the #GIOStream
57  * object alive. If the #GIOStream object is freed it will be closed, thus
58  * closing the substream, so even if the substreams stay alive they will
59  * always just return a %G_IO_ERROR_CLOSED for all operations.
60  *
61  * To close a stream use g_io_stream_close() which will close the common
62  * stream object and also the individual substreams. You can also close
63  * the substreams themselves. In most cases this only marks the
64  * substream as closed, so further I/O on it fails. However, some streams
65  * may support "half-closed" states where one direction of the stream
66  * is actually shut down.
67  *
68  * Since: 2.22
69  */
70
71 enum
72 {
73   PROP_0,
74   PROP_INPUT_STREAM,
75   PROP_OUTPUT_STREAM,
76   PROP_CLOSED
77 };
78
79 struct _GIOStreamPrivate {
80   guint closed : 1;
81   guint pending : 1;
82   GAsyncReadyCallback outstanding_callback;
83 };
84
85 static gboolean g_io_stream_real_close        (GIOStream            *stream,
86                                                GCancellable         *cancellable,
87                                                GError              **error);
88 static void     g_io_stream_real_close_async  (GIOStream            *stream,
89                                                int                   io_priority,
90                                                GCancellable         *cancellable,
91                                                GAsyncReadyCallback   callback,
92                                                gpointer              user_data);
93 static gboolean g_io_stream_real_close_finish (GIOStream            *stream,
94                                                GAsyncResult         *result,
95                                                GError              **error);
96
97 static void
98 g_io_stream_finalize (GObject *object)
99 {
100   G_OBJECT_CLASS (g_io_stream_parent_class)->finalize (object);
101 }
102
103 static void
104 g_io_stream_dispose (GObject *object)
105 {
106   GIOStream *stream;
107
108   stream = G_IO_STREAM (object);
109
110   if (!stream->priv->closed)
111     g_io_stream_close (stream, NULL, NULL);
112
113   G_OBJECT_CLASS (g_io_stream_parent_class)->dispose (object);
114 }
115
116 static void
117 g_io_stream_init (GIOStream *stream)
118 {
119   stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (stream,
120                                               G_TYPE_IO_STREAM,
121                                               GIOStreamPrivate);
122 }
123
124 static void
125 g_io_stream_get_property (GObject    *object,
126                           guint       prop_id,
127                           GValue     *value,
128                           GParamSpec *pspec)
129 {
130   GIOStream *stream = G_IO_STREAM (object);
131
132   switch (prop_id)
133     {
134       case PROP_CLOSED:
135         g_value_set_boolean (value, stream->priv->closed);
136         break;
137
138       case PROP_INPUT_STREAM:
139         g_value_set_object (value, g_io_stream_get_input_stream (stream));
140         break;
141
142       case PROP_OUTPUT_STREAM:
143         g_value_set_object (value, g_io_stream_get_output_stream (stream));
144         break;
145
146       default:
147         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
148     }
149 }
150
151 static void
152 g_io_stream_set_property (GObject      *object,
153                           guint         prop_id,
154                           const GValue *value,
155                           GParamSpec   *pspec)
156 {
157   switch (prop_id)
158     {
159     default:
160       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
161     }
162 }
163
164 static void
165 g_io_stream_class_init (GIOStreamClass *klass)
166 {
167   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
168
169   g_type_class_add_private (klass, sizeof (GIOStreamPrivate));
170
171   gobject_class->finalize = g_io_stream_finalize;
172   gobject_class->dispose = g_io_stream_dispose;
173   gobject_class->set_property = g_io_stream_set_property;
174   gobject_class->get_property = g_io_stream_get_property;
175
176   klass->close_fn = g_io_stream_real_close;
177   klass->close_async = g_io_stream_real_close_async;
178   klass->close_finish = g_io_stream_real_close_finish;
179
180   g_object_class_install_property (gobject_class, PROP_CLOSED,
181                                    g_param_spec_boolean ("closed",
182                                                          P_("Closed"),
183                                                          P_("Is the stream closed"),
184                                                          FALSE,
185                                                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
186
187   g_object_class_install_property (gobject_class, PROP_INPUT_STREAM,
188                                    g_param_spec_object ("input-stream",
189                                                         P_("Input stream"),
190                                                         P_("The GInputStream to read from"),
191                                                         G_TYPE_INPUT_STREAM,
192                                                         G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
193   g_object_class_install_property (gobject_class, PROP_OUTPUT_STREAM,
194                                    g_param_spec_object ("output-stream",
195                                                         P_("Output stream"),
196                                                         P_("The GOutputStream to write to"),
197                                                         G_TYPE_OUTPUT_STREAM,
198                                                         G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
199 }
200
201 /**
202  * g_io_stream_is_closed:
203  * @stream: a #GIOStream
204  *
205  * Checks if a stream is closed.
206  *
207  * Returns: %TRUE if the stream is closed.
208  *
209  * Since: 2.22
210  */
211 gboolean
212 g_io_stream_is_closed (GIOStream *stream)
213 {
214   g_return_val_if_fail (G_IS_IO_STREAM (stream), TRUE);
215
216   return stream->priv->closed;
217 }
218
219 /**
220  * g_io_stream_get_input_stream:
221  * @stream: a #GIOStream
222  *
223  * Gets the input stream for this object. This is used
224  * for reading.
225  *
226  * Returns: a #GInputStream, owned by the #GIOStream. Do not free.
227  *
228  * Since: 2.22
229  */
230 GInputStream *
231 g_io_stream_get_input_stream (GIOStream *stream)
232 {
233   GIOStreamClass *klass;
234
235   klass = G_IO_STREAM_GET_CLASS (stream);
236
237   g_assert (klass->get_input_stream != NULL);
238
239   return klass->get_input_stream (stream);
240 }
241
242 /**
243  * g_io_stream_get_output_stream:
244  * @stream: a #GIOStream
245  *
246  * Gets the output stream for this object. This is used for
247  * writing.
248  *
249  * Returns: a #GOutputStream, owned by the #GIOStream. Do not free.
250  *
251  * Since: 2.22
252  */
253 GOutputStream *
254 g_io_stream_get_output_stream (GIOStream *stream)
255 {
256   GIOStreamClass *klass;
257
258   klass = G_IO_STREAM_GET_CLASS (stream);
259
260   g_assert (klass->get_output_stream != NULL);
261   return klass->get_output_stream (stream);
262 }
263
264 /**
265  * g_io_stream_has_pending:
266  * @stream: a #GIOStream
267  *
268  * Checks if a stream has pending actions.
269  *
270  * Returns: %TRUE if @stream has pending actions.
271  *
272  * Since: 2.22
273  **/
274 gboolean
275 g_io_stream_has_pending (GIOStream *stream)
276 {
277   g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
278
279   return stream->priv->pending;
280 }
281
282 /**
283  * g_io_stream_set_pending:
284  * @stream: a #GIOStream
285  * @error: a #GError location to store the error occuring, or %NULL to
286  *     ignore
287  *
288  * Sets @stream to have actions pending. If the pending flag is
289  * already set or @stream is closed, it will return %FALSE and set
290  * @error.
291  *
292  * Return value: %TRUE if pending was previously unset and is now set.
293  *
294  * Since: 2.22
295  */
296 gboolean
297 g_io_stream_set_pending (GIOStream  *stream,
298                          GError    **error)
299 {
300   g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
301
302   if (stream->priv->closed)
303     {
304       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
305                            _("Stream is already closed"));
306       return FALSE;
307     }
308
309   if (stream->priv->pending)
310     {
311       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
312                            /* Translators: This is an error you get if there is
313                             * already an operation running against this stream when
314                             * you try to start one */
315                            _("Stream has outstanding operation"));
316       return FALSE;
317     }
318
319   stream->priv->pending = TRUE;
320   return TRUE;
321 }
322
323 /**
324  * g_io_stream_clear_pending:
325  * @stream: a #GIOStream
326  *
327  * Clears the pending flag on @stream.
328  *
329  * Since: 2.22
330  */
331 void
332 g_io_stream_clear_pending (GIOStream *stream)
333 {
334   g_return_if_fail (G_IS_IO_STREAM (stream));
335
336   stream->priv->pending = FALSE;
337 }
338
339 static gboolean
340 g_io_stream_real_close (GIOStream     *stream,
341                         GCancellable  *cancellable,
342                         GError       **error)
343 {
344   gboolean res;
345
346   res = g_output_stream_close (g_io_stream_get_output_stream (stream),
347                                cancellable, error);
348
349   /* If this errored out, unset error so that we don't report
350      further errors, but still do the following ops */
351   if (error != NULL && *error != NULL)
352     error = NULL;
353
354   res &= g_input_stream_close (g_io_stream_get_input_stream (stream),
355                                cancellable, error);
356
357   return res;
358 }
359
360 /**
361  * g_io_stream_close:
362  * @stream: a #GIOStream
363  * @cancellable: optional #GCancellable object, %NULL to ignore
364  * @error: location to store the error occuring, or %NULL to ignore
365  *
366  * Closes the stream, releasing resources related to it. This will also
367  * closes the individual input and output streams, if they are not already
368  * closed.
369  *
370  * Once the stream is closed, all other operations will return
371  * %G_IO_ERROR_CLOSED. Closing a stream multiple times will not
372  * return an error.
373  *
374  * Closing a stream will automatically flush any outstanding buffers
375  * in the stream.
376  *
377  * Streams will be automatically closed when the last reference
378  * is dropped, but you might want to call this function to make sure
379  * resources are released as early as possible.
380  *
381  * Some streams might keep the backing store of the stream (e.g. a file
382  * descriptor) open after the stream is closed. See the documentation for
383  * the individual stream for details.
384  *
385  * On failure the first error that happened will be reported, but the
386  * close operation will finish as much as possible. A stream that failed
387  * to close will still return %G_IO_ERROR_CLOSED for all operations.
388  * Still, it is important to check and report the error to the user,
389  * otherwise there might be a loss of data as all data might not be written.
390  *
391  * If @cancellable is not NULL, then the operation can be cancelled by
392  * triggering the cancellable object from another thread. If the operation
393  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
394  * Cancelling a close will still leave the stream closed, but some streams
395  * can use a faster close that doesn't block to e.g. check errors.
396  *
397  * The default implementation of this method just calls close on the
398  * individual input/output streams.
399  *
400  * Return value: %TRUE on success, %FALSE on failure
401  *
402  * Since: 2.22
403  */
404 gboolean
405 g_io_stream_close (GIOStream     *stream,
406                    GCancellable  *cancellable,
407                    GError       **error)
408 {
409   GIOStreamClass *class;
410   gboolean res;
411
412   g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
413
414   class = G_IO_STREAM_GET_CLASS (stream);
415
416   if (stream->priv->closed)
417     return TRUE;
418
419   if (!g_io_stream_set_pending (stream, error))
420     return FALSE;
421
422   if (cancellable)
423     g_cancellable_push_current (cancellable);
424
425   res = TRUE;
426   if (class->close_fn)
427     res = class->close_fn (stream, cancellable, error);
428
429   if (cancellable)
430     g_cancellable_pop_current (cancellable);
431
432   stream->priv->closed = TRUE;
433   g_io_stream_clear_pending (stream);
434
435   return res;
436 }
437
438 static void
439 async_ready_close_callback_wrapper (GObject      *source_object,
440                                     GAsyncResult *res,
441                                     gpointer      user_data)
442 {
443   GIOStream *stream = G_IO_STREAM (source_object);
444
445   stream->priv->closed = TRUE;
446   g_io_stream_clear_pending (stream);
447   if (stream->priv->outstanding_callback)
448     (*stream->priv->outstanding_callback) (source_object, res, user_data);
449   g_object_unref (stream);
450 }
451
452 /**
453  * g_io_stream_close_async:
454  * @stream: a #GIOStream
455  * @io_priority: the io priority of the request
456  * @callback: callback to call when the request is satisfied
457  * @user_data: the data to pass to callback function
458  * @cancellable: optional cancellable object
459  *
460  * Requests an asynchronous close of the stream, releasing resources
461  * related to it. When the operation is finished @callback will be
462  * called. You can then call g_io_stream_close_finish() to get
463  * the result of the operation.
464  *
465  * For behaviour details see g_io_stream_close().
466  *
467  * The asynchronous methods have a default fallback that uses threads
468  * to implement asynchronicity, so they are optional for inheriting
469  * classes. However, if you override one you must override all.
470  *
471  * Since: 2.22
472  */
473 void
474 g_io_stream_close_async (GIOStream           *stream,
475                          int                  io_priority,
476                          GCancellable        *cancellable,
477                          GAsyncReadyCallback  callback,
478                          gpointer             user_data)
479 {
480   GIOStreamClass *class;
481   GSimpleAsyncResult *simple;
482   GError *error = NULL;
483
484   g_return_if_fail (G_IS_IO_STREAM (stream));
485
486   if (stream->priv->closed)
487     {
488       simple = g_simple_async_result_new (G_OBJECT (stream),
489                                           callback,
490                                           user_data,
491                                           g_io_stream_close_async);
492       g_simple_async_result_complete_in_idle (simple);
493       g_object_unref (simple);
494       return;
495     }
496
497   if (!g_io_stream_set_pending (stream, &error))
498     {
499       g_simple_async_report_gerror_in_idle (G_OBJECT (stream),
500                                             callback,
501                                             user_data,
502                                             error);
503       g_error_free (error);
504       return;
505     }
506
507   class = G_IO_STREAM_GET_CLASS (stream);
508   stream->priv->outstanding_callback = callback;
509   g_object_ref (stream);
510   class->close_async (stream, io_priority, cancellable,
511                       async_ready_close_callback_wrapper, user_data);
512 }
513
514 /**
515  * g_io_stream_close_finish:
516  * @stream: a #GIOStream
517  * @result: a #GAsyncResult
518  * @error: a #GError location to store the error occuring, or %NULL to
519  *    ignore
520  *
521  * Closes a stream.
522  *
523  * Returns: %TRUE if stream was successfully closed, %FALSE otherwise.
524  *
525  * Since: 2.22
526  */
527 gboolean
528 g_io_stream_close_finish (GIOStream     *stream,
529                           GAsyncResult  *result,
530                           GError       **error)
531 {
532   GSimpleAsyncResult *simple;
533   GIOStreamClass *class;
534
535   g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
536   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
537
538   if (G_IS_SIMPLE_ASYNC_RESULT (result))
539     {
540       simple = G_SIMPLE_ASYNC_RESULT (result);
541       if (g_simple_async_result_propagate_error (simple, error))
542         return FALSE;
543
544       /* Special case already closed */
545       if (g_simple_async_result_get_source_tag (simple) == g_io_stream_close_async)
546         return TRUE;
547     }
548
549   class = G_IO_STREAM_GET_CLASS (stream);
550   return class->close_finish (stream, result, error);
551 }
552
553
554 static void
555 close_async_thread (GSimpleAsyncResult *res,
556                     GObject            *object,
557                     GCancellable       *cancellable)
558 {
559   GIOStreamClass *class;
560   GError *error = NULL;
561   gboolean result;
562
563   /* Auto handling of cancelation disabled, and ignore cancellation,
564    * since we want to close things anyway, although possibly in a
565    * quick-n-dirty way. At least we never want to leak open handles
566    */
567   class = G_IO_STREAM_GET_CLASS (object);
568   if (class->close_fn)
569     {
570       result = class->close_fn (G_IO_STREAM (object), cancellable, &error);
571       if (!result)
572         {
573           g_simple_async_result_set_from_error (res, error);
574           g_error_free (error);
575         }
576     }
577 }
578
579 static void
580 g_io_stream_real_close_async (GIOStream           *stream,
581                               int                  io_priority,
582                               GCancellable        *cancellable,
583                               GAsyncReadyCallback  callback,
584                               gpointer             user_data)
585 {
586   GSimpleAsyncResult *res;
587
588   res = g_simple_async_result_new (G_OBJECT (stream),
589                                    callback,
590                                    user_data,
591                                    g_io_stream_real_close_async);
592
593   g_simple_async_result_set_handle_cancellation (res, FALSE);
594
595   g_simple_async_result_run_in_thread (res,
596                                        close_async_thread,
597                                        io_priority,
598                                        cancellable);
599   g_object_unref (res);
600 }
601
602 static gboolean
603 g_io_stream_real_close_finish (GIOStream     *stream,
604                                GAsyncResult  *result,
605                                GError       **error)
606 {
607   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
608   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) ==
609                   g_io_stream_real_close_async);
610   return TRUE;
611 }
612
613 #define __G_IO_STREAM_C__
614 #include "gioaliasdef.c"