1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2008 codethink
4 * Copyright © 2009 Red Hat, Inc.
6 * SPDX-License-Identifier: LGPL-2.1-or-later
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library 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 GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General
19 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Authors: Ryan Lortie <desrt@desrt.ca>
22 * Alexander Larsson <alexl@redhat.com>
29 #include "giostream.h"
30 #include "gasyncresult.h"
31 #include "gioprivate.h"
36 * @short_description: Base class for implementing read/write streams
38 * @see_also: #GInputStream, #GOutputStream
40 * GIOStream represents an object that has both read and write streams.
41 * Generally the two streams act as separate input and output streams,
42 * but they share some common resources and state. For instance, for
43 * seekable streams, both streams may use the same position.
45 * Examples of #GIOStream objects are #GSocketConnection, which represents
46 * a two-way network connection; and #GFileIOStream, which represents a
47 * file handle opened in read-write mode.
49 * To do the actual reading and writing you need to get the substreams
50 * with g_io_stream_get_input_stream() and g_io_stream_get_output_stream().
52 * The #GIOStream object owns the input and the output streams, not the other
53 * way around, so keeping the substreams alive will not keep the #GIOStream
54 * object alive. If the #GIOStream object is freed it will be closed, thus
55 * closing the substreams, so even if the substreams stay alive they will
56 * always return %G_IO_ERROR_CLOSED for all operations.
58 * To close a stream use g_io_stream_close() which will close the common
59 * stream object and also the individual substreams. You can also close
60 * the substreams themselves. In most cases this only marks the
61 * substream as closed, so further I/O on it fails but common state in the
62 * #GIOStream may still be open. However, some streams may support
63 * "half-closed" states where one direction of the stream is actually shut down.
65 * Operations on #GIOStreams cannot be started while another operation on the
66 * #GIOStream or its substreams is in progress. Specifically, an application can
67 * read from the #GInputStream and write to the #GOutputStream simultaneously
68 * (either in separate threads, or as asynchronous operations in the same
69 * thread), but an application cannot start any #GIOStream operation while there
70 * is a #GIOStream, #GInputStream or #GOutputStream operation in progress, and
71 * an application can’t start any #GInputStream or #GOutputStream operation
72 * while there is a #GIOStream operation in progress.
74 * This is a product of individual stream operations being associated with a
75 * given #GMainContext (the thread-default context at the time the operation was
76 * started), rather than entire streams being associated with a single
79 * GIO may run operations on #GIOStreams from other (worker) threads, and this
80 * may be exposed to application code in the behaviour of wrapper streams, such
81 * as #GBufferedInputStream or #GTlsConnection. With such wrapper APIs,
82 * application code may only run operations on the base (wrapped) stream when
83 * the wrapper stream is idle. Note that the semantics of such operations may
84 * not be well-defined due to the state the wrapper stream leaves the base
85 * stream in (though they are guaranteed not to crash).
98 struct _GIOStreamPrivate {
103 static gboolean g_io_stream_real_close (GIOStream *stream,
104 GCancellable *cancellable,
106 static void g_io_stream_real_close_async (GIOStream *stream,
108 GCancellable *cancellable,
109 GAsyncReadyCallback callback,
111 static gboolean g_io_stream_real_close_finish (GIOStream *stream,
112 GAsyncResult *result,
115 G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE (GIOStream, g_io_stream, G_TYPE_OBJECT)
118 g_io_stream_dispose (GObject *object)
122 stream = G_IO_STREAM (object);
124 if (!stream->priv->closed)
125 g_io_stream_close (stream, NULL, NULL);
127 G_OBJECT_CLASS (g_io_stream_parent_class)->dispose (object);
131 g_io_stream_init (GIOStream *stream)
133 stream->priv = g_io_stream_get_instance_private (stream);
137 g_io_stream_get_property (GObject *object,
142 GIOStream *stream = G_IO_STREAM (object);
147 g_value_set_boolean (value, stream->priv->closed);
150 case PROP_INPUT_STREAM:
151 g_value_set_object (value, g_io_stream_get_input_stream (stream));
154 case PROP_OUTPUT_STREAM:
155 g_value_set_object (value, g_io_stream_get_output_stream (stream));
159 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
164 g_io_stream_class_init (GIOStreamClass *klass)
166 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
168 gobject_class->dispose = g_io_stream_dispose;
169 gobject_class->get_property = g_io_stream_get_property;
171 klass->close_fn = g_io_stream_real_close;
172 klass->close_async = g_io_stream_real_close_async;
173 klass->close_finish = g_io_stream_real_close_finish;
175 g_object_class_install_property (gobject_class, PROP_CLOSED,
176 g_param_spec_boolean ("closed",
178 P_("Is the stream closed"),
180 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
182 g_object_class_install_property (gobject_class, PROP_INPUT_STREAM,
183 g_param_spec_object ("input-stream",
185 P_("The GInputStream to read from"),
187 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
188 g_object_class_install_property (gobject_class, PROP_OUTPUT_STREAM,
189 g_param_spec_object ("output-stream",
191 P_("The GOutputStream to write to"),
192 G_TYPE_OUTPUT_STREAM,
193 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
197 * g_io_stream_is_closed:
198 * @stream: a #GIOStream
200 * Checks if a stream is closed.
202 * Returns: %TRUE if the stream is closed.
207 g_io_stream_is_closed (GIOStream *stream)
209 g_return_val_if_fail (G_IS_IO_STREAM (stream), TRUE);
211 return stream->priv->closed;
215 * g_io_stream_get_input_stream:
216 * @stream: a #GIOStream
218 * Gets the input stream for this object. This is used
221 * Returns: (transfer none): a #GInputStream, owned by the #GIOStream.
227 g_io_stream_get_input_stream (GIOStream *stream)
229 GIOStreamClass *klass;
231 klass = G_IO_STREAM_GET_CLASS (stream);
233 g_assert (klass->get_input_stream != NULL);
235 return klass->get_input_stream (stream);
239 * g_io_stream_get_output_stream:
240 * @stream: a #GIOStream
242 * Gets the output stream for this object. This is used for
245 * Returns: (transfer none): a #GOutputStream, owned by the #GIOStream.
251 g_io_stream_get_output_stream (GIOStream *stream)
253 GIOStreamClass *klass;
255 klass = G_IO_STREAM_GET_CLASS (stream);
257 g_assert (klass->get_output_stream != NULL);
258 return klass->get_output_stream (stream);
262 * g_io_stream_has_pending:
263 * @stream: a #GIOStream
265 * Checks if a stream has pending actions.
267 * Returns: %TRUE if @stream has pending actions.
272 g_io_stream_has_pending (GIOStream *stream)
274 g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
276 return stream->priv->pending;
280 * g_io_stream_set_pending:
281 * @stream: a #GIOStream
282 * @error: a #GError location to store the error occurring, or %NULL to
285 * Sets @stream to have actions pending. If the pending flag is
286 * already set or @stream is closed, it will return %FALSE and set
289 * Returns: %TRUE if pending was previously unset and is now set.
294 g_io_stream_set_pending (GIOStream *stream,
297 g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
299 if (stream->priv->closed)
301 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
302 _("Stream is already closed"));
306 if (stream->priv->pending)
308 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
309 /* Translators: This is an error you get if there is
310 * already an operation running against this stream when
311 * you try to start one */
312 _("Stream has outstanding operation"));
316 stream->priv->pending = TRUE;
321 * g_io_stream_clear_pending:
322 * @stream: a #GIOStream
324 * Clears the pending flag on @stream.
329 g_io_stream_clear_pending (GIOStream *stream)
331 g_return_if_fail (G_IS_IO_STREAM (stream));
333 stream->priv->pending = FALSE;
337 g_io_stream_real_close (GIOStream *stream,
338 GCancellable *cancellable,
343 res = g_output_stream_close (g_io_stream_get_output_stream (stream),
346 /* If this errored out, unset error so that we don't report
347 further errors, but still do the following ops */
348 if (error != NULL && *error != NULL)
351 res &= g_input_stream_close (g_io_stream_get_input_stream (stream),
359 * @stream: a #GIOStream
360 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore
361 * @error: location to store the error occurring, or %NULL to ignore
363 * Closes the stream, releasing resources related to it. This will also
364 * close the individual input and output streams, if they are not already
367 * Once the stream is closed, all other operations will return
368 * %G_IO_ERROR_CLOSED. Closing a stream multiple times will not
371 * Closing a stream will automatically flush any outstanding buffers
374 * Streams will be automatically closed when the last reference
375 * is dropped, but you might want to call this function to make sure
376 * resources are released as early as possible.
378 * Some streams might keep the backing store of the stream (e.g. a file
379 * descriptor) open after the stream is closed. See the documentation for
380 * the individual stream for details.
382 * On failure the first error that happened will be reported, but the
383 * close operation will finish as much as possible. A stream that failed
384 * to close will still return %G_IO_ERROR_CLOSED for all operations.
385 * Still, it is important to check and report the error to the user,
386 * otherwise there might be a loss of data as all data might not be written.
388 * If @cancellable is not NULL, then the operation can be cancelled by
389 * triggering the cancellable object from another thread. If the operation
390 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
391 * Cancelling a close will still leave the stream closed, but some streams
392 * can use a faster close that doesn't block to e.g. check errors.
394 * The default implementation of this method just calls close on the
395 * individual input/output streams.
397 * Returns: %TRUE on success, %FALSE on failure
402 g_io_stream_close (GIOStream *stream,
403 GCancellable *cancellable,
406 GIOStreamClass *class;
409 g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
411 class = G_IO_STREAM_GET_CLASS (stream);
413 if (stream->priv->closed)
416 if (!g_io_stream_set_pending (stream, error))
420 g_cancellable_push_current (cancellable);
424 res = class->close_fn (stream, cancellable, error);
427 g_cancellable_pop_current (cancellable);
429 stream->priv->closed = TRUE;
430 g_io_stream_clear_pending (stream);
436 async_ready_close_callback_wrapper (GObject *source_object,
440 GIOStream *stream = G_IO_STREAM (source_object);
441 GIOStreamClass *klass = G_IO_STREAM_GET_CLASS (stream);
442 GTask *task = user_data;
443 GError *error = NULL;
446 stream->priv->closed = TRUE;
447 g_io_stream_clear_pending (stream);
449 if (g_async_result_legacy_propagate_error (res, &error))
452 success = klass->close_finish (stream, res, &error);
455 g_task_return_error (task, error);
457 g_task_return_boolean (task, success);
459 g_object_unref (task);
463 * g_io_stream_close_async:
464 * @stream: a #GIOStream
465 * @io_priority: the io priority of the request
466 * @cancellable: (nullable): optional cancellable object
467 * @callback: (scope async): a #GAsyncReadyCallback
468 * to call when the request is satisfied
469 * @user_data: the data to pass to callback function
471 * Requests an asynchronous close of the stream, releasing resources
472 * related to it. When the operation is finished @callback will be
473 * called. You can then call g_io_stream_close_finish() to get
474 * the result of the operation.
476 * For behaviour details see g_io_stream_close().
478 * The asynchronous methods have a default fallback that uses threads
479 * to implement asynchronicity, so they are optional for inheriting
480 * classes. However, if you override one you must override all.
485 g_io_stream_close_async (GIOStream *stream,
487 GCancellable *cancellable,
488 GAsyncReadyCallback callback,
491 GIOStreamClass *class;
492 GError *error = NULL;
495 g_return_if_fail (G_IS_IO_STREAM (stream));
497 task = g_task_new (stream, cancellable, callback, user_data);
498 g_task_set_source_tag (task, g_io_stream_close_async);
500 if (stream->priv->closed)
502 g_task_return_boolean (task, TRUE);
503 g_object_unref (task);
507 if (!g_io_stream_set_pending (stream, &error))
509 g_task_return_error (task, error);
510 g_object_unref (task);
514 class = G_IO_STREAM_GET_CLASS (stream);
516 class->close_async (stream, io_priority, cancellable,
517 async_ready_close_callback_wrapper, task);
521 * g_io_stream_close_finish:
522 * @stream: a #GIOStream
523 * @result: a #GAsyncResult
524 * @error: a #GError location to store the error occurring, or %NULL to
529 * Returns: %TRUE if stream was successfully closed, %FALSE otherwise.
534 g_io_stream_close_finish (GIOStream *stream,
535 GAsyncResult *result,
538 g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
539 g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
541 return g_task_propagate_boolean (G_TASK (result), error);
546 close_async_thread (GTask *task,
547 gpointer source_object,
549 GCancellable *cancellable)
551 GIOStream *stream = source_object;
552 GIOStreamClass *class;
553 GError *error = NULL;
556 class = G_IO_STREAM_GET_CLASS (stream);
559 result = class->close_fn (stream,
560 g_task_get_cancellable (task),
564 g_task_return_error (task, error);
569 g_task_return_boolean (task, TRUE);
579 stream_close_complete (GObject *source,
580 GAsyncResult *result,
583 GTask *task = user_data;
584 CloseAsyncData *data;
586 data = g_task_get_task_data (task);
589 if (G_IS_OUTPUT_STREAM (source))
591 GError *error = NULL;
593 /* Match behaviour with the sync route and give precedent to the
594 * error returned from closing the output stream.
596 g_output_stream_close_finish (G_OUTPUT_STREAM (source), result, &error);
600 g_error_free (data->error);
605 g_input_stream_close_finish (G_INPUT_STREAM (source), result, data->error ? NULL : &data->error);
607 if (data->pending == 0)
610 g_task_return_error (task, data->error);
612 g_task_return_boolean (task, TRUE);
614 g_slice_free (CloseAsyncData, data);
615 g_object_unref (task);
620 g_io_stream_real_close_async (GIOStream *stream,
622 GCancellable *cancellable,
623 GAsyncReadyCallback callback,
627 GOutputStream *output;
630 task = g_task_new (stream, cancellable, callback, user_data);
631 g_task_set_source_tag (task, g_io_stream_real_close_async);
632 g_task_set_check_cancellable (task, FALSE);
633 g_task_set_priority (task, io_priority);
635 input = g_io_stream_get_input_stream (stream);
636 output = g_io_stream_get_output_stream (stream);
638 if (g_input_stream_async_close_is_via_threads (input) && g_output_stream_async_close_is_via_threads (output))
640 /* No sense in dispatching to the thread twice -- just do it all
643 g_task_run_in_thread (task, close_async_thread);
644 g_object_unref (task);
648 CloseAsyncData *data;
650 /* We should avoid dispatching to another thread in case either
651 * object that would not do it for itself because it may not be
654 data = g_slice_new (CloseAsyncData);
658 g_task_set_task_data (task, data, NULL);
659 g_input_stream_close_async (input, io_priority, cancellable, stream_close_complete, task);
660 g_output_stream_close_async (output, io_priority, cancellable, stream_close_complete, task);
665 g_io_stream_real_close_finish (GIOStream *stream,
666 GAsyncResult *result,
669 g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
671 return g_task_propagate_boolean (G_TASK (result), error);
678 GIOStreamSpliceFlags flags;
680 GCancellable *cancellable;
682 GCancellable *op1_cancellable;
683 GCancellable *op2_cancellable;
689 splice_context_free (SpliceContext *ctx)
691 g_object_unref (ctx->stream1);
692 g_object_unref (ctx->stream2);
693 if (ctx->cancellable != NULL)
694 g_object_unref (ctx->cancellable);
695 g_object_unref (ctx->op1_cancellable);
696 g_object_unref (ctx->op2_cancellable);
697 g_clear_error (&ctx->error);
698 g_slice_free (SpliceContext, ctx);
702 splice_complete (GTask *task,
705 if (ctx->cancelled_id != 0)
706 g_cancellable_disconnect (ctx->cancellable, ctx->cancelled_id);
707 ctx->cancelled_id = 0;
709 if (ctx->error != NULL)
711 g_task_return_error (task, ctx->error);
715 g_task_return_boolean (task, TRUE);
719 splice_close_cb (GObject *iostream,
723 GTask *task = user_data;
724 SpliceContext *ctx = g_task_get_task_data (task);
725 GError *error = NULL;
727 g_io_stream_close_finish (G_IO_STREAM (iostream), res, &error);
731 /* Keep the first error that occurred */
732 if (error != NULL && ctx->error == NULL)
735 g_clear_error (&error);
737 /* If all operations are done, complete now */
738 if (ctx->completed == 4)
739 splice_complete (task, ctx);
741 g_object_unref (task);
745 splice_cb (GObject *ostream,
749 GTask *task = user_data;
750 SpliceContext *ctx = g_task_get_task_data (task);
751 GError *error = NULL;
753 g_output_stream_splice_finish (G_OUTPUT_STREAM (ostream), res, &error);
757 /* ignore cancellation error if it was not requested by the user */
759 g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) &&
760 (ctx->cancellable == NULL ||
761 !g_cancellable_is_cancelled (ctx->cancellable)))
762 g_clear_error (&error);
764 /* Keep the first error that occurred */
765 if (error != NULL && ctx->error == NULL)
768 g_clear_error (&error);
770 if (ctx->completed == 1 &&
771 (ctx->flags & G_IO_STREAM_SPLICE_WAIT_FOR_BOTH) == 0)
773 /* We don't want to wait for the 2nd operation to finish, cancel it */
774 g_cancellable_cancel (ctx->op1_cancellable);
775 g_cancellable_cancel (ctx->op2_cancellable);
777 else if (ctx->completed == 2)
779 if (ctx->cancellable == NULL ||
780 !g_cancellable_is_cancelled (ctx->cancellable))
782 g_cancellable_reset (ctx->op1_cancellable);
783 g_cancellable_reset (ctx->op2_cancellable);
786 /* Close the IO streams if needed */
787 if ((ctx->flags & G_IO_STREAM_SPLICE_CLOSE_STREAM1) != 0)
789 g_io_stream_close_async (ctx->stream1,
790 g_task_get_priority (task),
791 ctx->op1_cancellable,
792 splice_close_cb, g_object_ref (task));
797 if ((ctx->flags & G_IO_STREAM_SPLICE_CLOSE_STREAM2) != 0)
799 g_io_stream_close_async (ctx->stream2,
800 g_task_get_priority (task),
801 ctx->op2_cancellable,
802 splice_close_cb, g_object_ref (task));
807 /* If all operations are done, complete now */
808 if (ctx->completed == 4)
809 splice_complete (task, ctx);
812 g_object_unref (task);
816 splice_cancelled_cb (GCancellable *cancellable,
821 ctx = g_task_get_task_data (task);
822 g_cancellable_cancel (ctx->op1_cancellable);
823 g_cancellable_cancel (ctx->op2_cancellable);
827 * g_io_stream_splice_async:
828 * @stream1: a #GIOStream.
829 * @stream2: a #GIOStream.
830 * @flags: a set of #GIOStreamSpliceFlags.
831 * @io_priority: the io priority of the request.
832 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
833 * @callback: (scope async): a #GAsyncReadyCallback
834 * to call when the request is satisfied
835 * @user_data: the data to pass to callback function
837 * Asynchronously splice the output stream of @stream1 to the input stream of
838 * @stream2, and splice the output stream of @stream2 to the input stream of
841 * When the operation is finished @callback will be called.
842 * You can then call g_io_stream_splice_finish() to get the
843 * result of the operation.
848 g_io_stream_splice_async (GIOStream *stream1,
850 GIOStreamSpliceFlags flags,
852 GCancellable *cancellable,
853 GAsyncReadyCallback callback,
858 GInputStream *istream;
859 GOutputStream *ostream;
861 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
863 g_task_report_new_error (NULL, callback, user_data,
864 g_io_stream_splice_async,
865 G_IO_ERROR, G_IO_ERROR_CANCELLED,
866 "Operation has been cancelled");
870 ctx = g_slice_new0 (SpliceContext);
871 ctx->stream1 = g_object_ref (stream1);
872 ctx->stream2 = g_object_ref (stream2);
874 ctx->op1_cancellable = g_cancellable_new ();
875 ctx->op2_cancellable = g_cancellable_new ();
878 task = g_task_new (NULL, cancellable, callback, user_data);
879 g_task_set_source_tag (task, g_io_stream_splice_async);
880 g_task_set_task_data (task, ctx, (GDestroyNotify) splice_context_free);
882 if (cancellable != NULL)
884 ctx->cancellable = g_object_ref (cancellable);
885 ctx->cancelled_id = g_cancellable_connect (cancellable,
886 G_CALLBACK (splice_cancelled_cb), g_object_ref (task),
890 istream = g_io_stream_get_input_stream (stream1);
891 ostream = g_io_stream_get_output_stream (stream2);
892 g_output_stream_splice_async (ostream, istream, G_OUTPUT_STREAM_SPLICE_NONE,
893 io_priority, ctx->op1_cancellable, splice_cb,
894 g_object_ref (task));
896 istream = g_io_stream_get_input_stream (stream2);
897 ostream = g_io_stream_get_output_stream (stream1);
898 g_output_stream_splice_async (ostream, istream, G_OUTPUT_STREAM_SPLICE_NONE,
899 io_priority, ctx->op2_cancellable, splice_cb,
900 g_object_ref (task));
902 g_object_unref (task);
906 * g_io_stream_splice_finish:
907 * @result: a #GAsyncResult.
908 * @error: a #GError location to store the error occurring, or %NULL to
911 * Finishes an asynchronous io stream splice operation.
913 * Returns: %TRUE on success, %FALSE otherwise.
918 g_io_stream_splice_finish (GAsyncResult *result,
921 g_return_val_if_fail (g_task_is_valid (result, NULL), FALSE);
923 return g_task_propagate_boolean (G_TASK (result), error);