Add support for abstract unix socket addresses
[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   GIOStream *stream;
101
102   stream = G_IO_STREAM (object);
103
104   G_OBJECT_CLASS (g_io_stream_parent_class)->finalize (object);
105 }
106
107 static void
108 g_io_stream_dispose (GObject *object)
109 {
110   GIOStream *stream;
111
112   stream = G_IO_STREAM (object);
113
114   if (!stream->priv->closed)
115     g_io_stream_close (stream, NULL, NULL);
116
117   G_OBJECT_CLASS (g_io_stream_parent_class)->dispose (object);
118 }
119
120 static void
121 g_io_stream_init (GIOStream *stream)
122 {
123   stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (stream,
124                                               G_TYPE_IO_STREAM,
125                                               GIOStreamPrivate);
126 }
127
128 static void
129 g_io_stream_get_property (GObject    *object,
130                           guint       prop_id,
131                           GValue     *value,
132                           GParamSpec *pspec)
133 {
134   GIOStream *stream = G_IO_STREAM (object);
135
136   switch (prop_id)
137     {
138       case PROP_CLOSED:
139         g_value_set_boolean (value, stream->priv->closed);
140         break;
141
142       case PROP_INPUT_STREAM:
143         g_value_set_object (value, g_io_stream_get_input_stream (stream));
144         break;
145
146       case PROP_OUTPUT_STREAM:
147         g_value_set_object (value, g_io_stream_get_output_stream (stream));
148         break;
149
150       default:
151         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
152     }
153 }
154
155 static void
156 g_io_stream_set_property (GObject      *object,
157                           guint         prop_id,
158                           const GValue *value,
159                           GParamSpec   *pspec)
160 {
161   switch (prop_id)
162     {
163     default:
164       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
165     }
166 }
167
168 static void
169 g_io_stream_class_init (GIOStreamClass *klass)
170 {
171   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
172
173   g_type_class_add_private (klass, sizeof (GIOStreamPrivate));
174
175   gobject_class->finalize = g_io_stream_finalize;
176   gobject_class->dispose = g_io_stream_dispose;
177   gobject_class->set_property = g_io_stream_set_property;
178   gobject_class->get_property = g_io_stream_get_property;
179
180   klass->close_fn = g_io_stream_real_close;
181   klass->close_async = g_io_stream_real_close_async;
182   klass->close_finish = g_io_stream_real_close_finish;
183
184   g_object_class_install_property (gobject_class, PROP_CLOSED,
185                                    g_param_spec_boolean ("closed",
186                                                          P_("Closed"),
187                                                          P_("Is the stream closed"),
188                                                          FALSE,
189                                                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
190
191   g_object_class_install_property (gobject_class, PROP_INPUT_STREAM,
192                                    g_param_spec_object ("input-stream",
193                                                         P_("Input stream"),
194                                                         P_("The GInputStream to read from"),
195                                                         G_TYPE_INPUT_STREAM,
196                                                         G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
197   g_object_class_install_property (gobject_class, PROP_OUTPUT_STREAM,
198                                    g_param_spec_object ("output-stream",
199                                                         P_("Output stream"),
200                                                         P_("The GOutputStream to write to"),
201                                                         G_TYPE_OUTPUT_STREAM,
202                                                         G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
203 }
204
205 /**
206  * g_io_stream_is_closed:
207  * @stream: a #GIOStream.
208  *
209  * Checks if a stream is closed.
210  *
211  * Returns: %TRUE if the stream is closed.
212  *
213  * Since: 2.22
214  **/
215 gboolean
216 g_io_stream_is_closed (GIOStream *stream)
217 {
218   g_return_val_if_fail (G_IS_IO_STREAM (stream), TRUE);
219
220   return stream->priv->closed;
221 }
222
223 /**
224  * g_io_stream_get_input_stream:
225  * @stream: input #GIOStream.
226  *
227  * Gets the input stream for this object. This is used
228  * for reading.
229  *
230  * Returns: a #GInputStream, owned by the #GIOStream do not free.
231  *
232  * Since: 2.22
233  **/
234 GInputStream *
235 g_io_stream_get_input_stream (GIOStream *io_stream)
236 {
237   GIOStreamClass *klass;
238
239   klass = G_IO_STREAM_GET_CLASS (io_stream);
240
241   g_assert (klass->get_input_stream != NULL);
242
243   return klass->get_input_stream (io_stream);
244 }
245
246 /**
247  * g_io_stream_get_output_stream:
248  * @stream: input #GIOStream.
249  *
250  * Gets the output stream for this object. This is used for
251  * writing.
252  *
253  * Returns: a #GOutputStream, owned by the #GIOStream do not free.
254  *
255  * Since: 2.22
256  **/
257 GOutputStream *
258 g_io_stream_get_output_stream (GIOStream *io_stream)
259 {
260   GIOStreamClass *klass;
261
262   klass = G_IO_STREAM_GET_CLASS (io_stream);
263
264   g_assert (klass->get_output_stream != NULL);
265   return klass->get_output_stream (io_stream);
266 }
267
268 /**
269  * g_io_stream_has_pending:
270  * @stream: a #GIOStream.
271  *
272  * Checks if a stream has pending actions.
273  *
274  * Returns: %TRUE if @stream has pending actions. 
275  *
276  * Since: 2.22
277  **/
278 gboolean
279 g_io_stream_has_pending (GIOStream *stream)
280 {
281   g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
282
283   return stream->priv->pending;
284 }
285
286 /**
287  * g_io_stream_set_pending:
288  * @stream: a #GIOStream.
289  * @error: a #GError location to store the error occuring, or %NULL to 
290  * ignore.
291  *
292  * Sets @stream to have actions pending. If the pending flag is
293  * already set or @stream is closed, it will return %FALSE and set
294  * @error.
295  *
296  * Return value: %TRUE if pending was previously unset and is now set.
297  *
298  * Since: 2.22
299  **/
300 gboolean
301 g_io_stream_set_pending (GIOStream *stream,
302                          GError **error)
303 {
304   g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
305
306   if (stream->priv->closed)
307     {
308       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
309                            _("Stream is already closed"));
310       return FALSE;
311     }
312
313   if (stream->priv->pending)
314     {
315       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
316                            /* Translators: This is an error you get if there is
317                             * already an operation running against this stream when
318                             * you try to start one */
319                            _("Stream has outstanding operation"));
320       return FALSE;
321     }
322
323   stream->priv->pending = TRUE;
324   return TRUE;
325 }
326
327 /**
328  * g_io_stream_clear_pending:
329  * @stream: output stream
330  *
331  * Clears the pending flag on @stream.
332  *
333  * Since: 2.22
334  **/
335 void
336 g_io_stream_clear_pending (GIOStream *stream)
337 {
338   g_return_if_fail (G_IS_IO_STREAM (stream));
339
340   stream->priv->pending = FALSE;
341 }
342
343 static gboolean
344 g_io_stream_real_close (GIOStream            *stream,
345                         GCancellable         *cancellable,
346                         GError              **error)
347 {
348   gboolean res;
349
350   res = g_output_stream_close (g_io_stream_get_output_stream (stream),
351                                cancellable, error);
352
353   /* If this errored out, unset error so that we don't report
354      further errors, but still do the following ops */
355   if (error != NULL && *error != NULL)
356     error = NULL;
357
358   res &= g_input_stream_close (g_io_stream_get_input_stream (stream),
359                                cancellable, error);
360
361   return res;
362 }
363
364 /**
365  * g_io_stream_close:
366  * @stream: A #GIOStream.
367  * @cancellable: optional #GCancellable object, %NULL to ignore.
368  * @error: location to store the error occuring, or %NULL to ignore
369  *
370  * Closes the stream, releasing resources related to it. This will also
371  * closes the individual input and output streams, if they are not already
372  * closed.
373  *
374  * Once the stream is closed, all other operations will return %G_IO_ERROR_CLOSED.
375  * Closing a stream multiple times will not return an error.
376  *
377  * Closing a stream will automatically flush any outstanding buffers in the
378  * stream.
379  *
380  * Streams will be automatically closed when the last reference
381  * is dropped, but you might want to call this function to make sure
382  * resources are released as early as possible.
383  *
384  * Some streams might keep the backing store of the stream (e.g. a file descriptor)
385  * open after the stream is closed. See the documentation for the individual
386  * stream for details.
387  *
388  * On failure the first error that happened will be reported, but the close
389  * operation will finish as much as possible. A stream that failed to
390  * close will still return %G_IO_ERROR_CLOSED for all operations. Still, it
391  * is important to check and report the error to the user, otherwise
392  * there might be a loss of data as all data might not be written.
393  *
394  * If @cancellable is not NULL, then the operation can be cancelled by
395  * triggering the cancellable object from another thread. If the operation
396  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
397  * Cancelling a close will still leave the stream closed, but some streams
398  * can use a faster close that doesn't block to e.g. check errors.
399  *
400  * The default implementation of this method just calls close on the
401  * individual input/output streams.
402  *
403  * Return value: %TRUE on success, %FALSE on failure
404  *
405  * Since: 2.22
406  **/
407 gboolean
408 g_io_stream_close (GIOStream  *stream,
409                    GCancellable  *cancellable,
410                    GError       **error)
411 {
412   GIOStreamClass *class;
413   gboolean res;
414
415   g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
416
417   class = G_IO_STREAM_GET_CLASS (stream);
418
419   if (stream->priv->closed)
420     return TRUE;
421
422   if (!g_io_stream_set_pending (stream, error))
423     return FALSE;
424
425   if (cancellable)
426     g_cancellable_push_current (cancellable);
427
428   res = TRUE;
429   if (class->close_fn)
430     res = class->close_fn (stream, cancellable, error);
431
432   if (cancellable)
433     g_cancellable_pop_current (cancellable);
434
435   stream->priv->closed = TRUE;
436   g_io_stream_clear_pending (stream);
437
438   return res;
439 }
440
441 static void
442 async_ready_close_callback_wrapper (GObject      *source_object,
443                                     GAsyncResult *res,
444                                     gpointer      user_data)
445 {
446   GIOStream *stream = G_IO_STREAM (source_object);
447
448   stream->priv->closed = TRUE;
449   g_io_stream_clear_pending (stream);
450   if (stream->priv->outstanding_callback)
451     (*stream->priv->outstanding_callback) (source_object, res, user_data);
452   g_object_unref (stream);
453 }
454
455 /**
456  * g_io_stream_close_async:
457  * @stream: A #GIOStream.
458  * @io_priority: the io priority of the request.
459  * @callback: callback to call when the request is satisfied
460  * @user_data: the data to pass to callback function
461  * @cancellable: optional cancellable object
462  *
463  * Requests an asynchronous close of the stream, releasing resources
464  * related to it. When the operation is finished @callback will be
465  * called. You can then call g_io_stream_close_finish() to get
466  * the result of the operation.
467  *
468  * For behaviour details see g_io_stream_close().
469  *
470  * The asyncronous methods have a default fallback that uses threads
471  * to implement asynchronicity, so they are optional for inheriting
472  * classes. However, if you override one you must override all.
473  *
474  * Since: 2.22
475  **/
476 void
477 g_io_stream_close_async (GIOStream           *stream,
478                          int                  io_priority,
479                          GCancellable        *cancellable,
480                          GAsyncReadyCallback  callback,
481                          gpointer             user_data)
482 {
483   GIOStreamClass *class;
484   GSimpleAsyncResult *simple;
485   GError *error = NULL;
486
487   g_return_if_fail (G_IS_IO_STREAM (stream));
488
489   if (stream->priv->closed)
490     {
491       simple = g_simple_async_result_new (G_OBJECT (stream),
492                                           callback,
493                                           user_data,
494                                           g_io_stream_close_async);
495       g_simple_async_result_complete_in_idle (simple);
496       g_object_unref (simple);
497       return;
498     }
499
500   if (!g_io_stream_set_pending (stream, &error))
501     {
502       g_simple_async_report_gerror_in_idle (G_OBJECT (stream),
503                                             callback,
504                                             user_data,
505                                             error);
506       g_error_free (error);
507       return;
508     }
509
510   class = G_IO_STREAM_GET_CLASS (stream);
511   stream->priv->outstanding_callback = callback;
512   g_object_ref (stream);
513   class->close_async (stream, io_priority, cancellable,
514                       async_ready_close_callback_wrapper, user_data);
515 }
516
517 /**
518  * g_io_stream_close_finish:
519  * @stream: a #GIOStream.
520  * @result: a #GAsyncResult.
521  * @error: a #GError location to store the error occuring, or %NULL to
522  * ignore.
523  *
524  * Closes a stream.
525  *
526  * Returns: %TRUE if stream was successfully closed, %FALSE otherwise.
527  *
528  * Since: 2.22
529  **/
530 gboolean
531 g_io_stream_close_finish (GIOStream  *stream,
532                           GAsyncResult   *result,
533                           GError        **error)
534 {
535   GSimpleAsyncResult *simple;
536   GIOStreamClass *class;
537
538   g_return_val_if_fail (G_IS_IO_STREAM (stream), FALSE);
539   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
540
541   if (G_IS_SIMPLE_ASYNC_RESULT (result))
542     {
543       simple = G_SIMPLE_ASYNC_RESULT (result);
544       if (g_simple_async_result_propagate_error (simple, error))
545         return FALSE;
546
547       /* Special case already closed */
548       if (g_simple_async_result_get_source_tag (simple) == g_io_stream_close_async)
549         return TRUE;
550     }
551
552   class = G_IO_STREAM_GET_CLASS (stream);
553   return class->close_finish (stream, result, error);
554 }
555
556
557 static void
558 close_async_thread (GSimpleAsyncResult *res,
559                     GObject            *object,
560                     GCancellable       *cancellable)
561 {
562   GIOStreamClass *class;
563   GError *error = NULL;
564   gboolean result;
565
566   /* Auto handling of cancelation disabled, and ignore
567      cancellation, since we want to close things anyway, although
568      possibly in a quick-n-dirty way. At least we never want to leak
569      open handles */
570
571   class = G_IO_STREAM_GET_CLASS (object);
572   result = class->close_fn (G_IO_STREAM (object), cancellable, &error);
573   if (!result)
574     {
575       g_simple_async_result_set_from_error (res, error);
576       g_error_free (error);
577     }
578 }
579
580 static void
581 g_io_stream_real_close_async (GIOStream        *stream,
582                               int               io_priority,
583                               GCancellable     *cancellable,
584                               GAsyncReadyCallback callback,
585                               gpointer          user_data)
586 {
587   GSimpleAsyncResult *res;
588
589   res = g_simple_async_result_new (G_OBJECT (stream),
590                                    callback,
591                                    user_data,
592                                    g_io_stream_real_close_async);
593
594   g_simple_async_result_set_handle_cancellation (res, FALSE);
595
596   g_simple_async_result_run_in_thread (res,
597                                        close_async_thread,
598                                        io_priority,
599                                        cancellable);
600   g_object_unref (res);
601 }
602
603 static gboolean
604 g_io_stream_real_close_finish (GIOStream  *stream,
605                                GAsyncResult  *result,
606                                GError       **error)
607 {
608   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
609   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) ==
610                   g_io_stream_real_close_async);
611   return TRUE;
612 }
613
614 #define __G_IO_STREAM_C__
615 #include "gioaliasdef.c"