Merge remote-tracking branch 'gvdb/master'
[platform/upstream/glib.git] / gio / gunixoutputstream.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
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 #include <errno.h>
29 #include <stdio.h>
30 #include <fcntl.h>
31
32 #include <glib.h>
33 #include <glib/gstdio.h>
34 #include "gioerror.h"
35 #include "gunixoutputstream.h"
36 #include "gcancellable.h"
37 #include "gsimpleasyncresult.h"
38 #include "gasynchelper.h"
39 #include "gfiledescriptorbased.h"
40 #include "glibintl.h"
41
42
43 /**
44  * SECTION:gunixoutputstream
45  * @short_description: Streaming output operations for UNIX file descriptors
46  * @include: gio/gunixoutputstream.h
47  * @see_also: #GOutputStream
48  *
49  * #GUnixOutputStream implements #GOutputStream for writing to a UNIX
50  * file descriptor, including asynchronous operations. (If the file
51  * descriptor refers to a socket or pipe, this will use poll() to do
52  * asynchronous I/O. If it refers to a regular file, it will fall back
53  * to doing asynchronous I/O in another thread.)
54  *
55  * Note that <filename>&lt;gio/gunixoutputstream.h&gt;</filename> belongs
56  * to the UNIX-specific GIO interfaces, thus you have to use the
57  * <filename>gio-unix-2.0.pc</filename> pkg-config file when using it.
58  */
59
60 enum {
61   PROP_0,
62   PROP_FD,
63   PROP_CLOSE_FD
64 };
65
66 static void g_unix_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface);
67 static void g_unix_output_stream_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface);
68
69 G_DEFINE_TYPE_WITH_CODE (GUnixOutputStream, g_unix_output_stream, G_TYPE_OUTPUT_STREAM,
70                          G_IMPLEMENT_INTERFACE (G_TYPE_POLLABLE_OUTPUT_STREAM,
71                                                 g_unix_output_stream_pollable_iface_init)
72                          G_IMPLEMENT_INTERFACE (G_TYPE_FILE_DESCRIPTOR_BASED,
73                                                 g_unix_output_stream_file_descriptor_based_iface_init)
74                          )
75
76 struct _GUnixOutputStreamPrivate {
77   int fd;
78   guint close_fd : 1;
79   guint is_pipe_or_socket : 1;
80 };
81
82 static void     g_unix_output_stream_set_property (GObject              *object,
83                                                    guint                 prop_id,
84                                                    const GValue         *value,
85                                                    GParamSpec           *pspec);
86 static void     g_unix_output_stream_get_property (GObject              *object,
87                                                    guint                 prop_id,
88                                                    GValue               *value,
89                                                    GParamSpec           *pspec);
90 static gssize   g_unix_output_stream_write        (GOutputStream        *stream,
91                                                    const void           *buffer,
92                                                    gsize                 count,
93                                                    GCancellable         *cancellable,
94                                                    GError              **error);
95 static gboolean g_unix_output_stream_close        (GOutputStream        *stream,
96                                                    GCancellable         *cancellable,
97                                                    GError              **error);
98 static void     g_unix_output_stream_write_async  (GOutputStream        *stream,
99                                                    const void           *buffer,
100                                                    gsize                 count,
101                                                    int                   io_priority,
102                                                    GCancellable         *cancellable,
103                                                    GAsyncReadyCallback   callback,
104                                                    gpointer              data);
105 static gssize   g_unix_output_stream_write_finish (GOutputStream        *stream,
106                                                    GAsyncResult         *result,
107                                                    GError              **error);
108 static void     g_unix_output_stream_close_async  (GOutputStream        *stream,
109                                                    int                   io_priority,
110                                                    GCancellable         *cancellable,
111                                                    GAsyncReadyCallback   callback,
112                                                    gpointer              data);
113 static gboolean g_unix_output_stream_close_finish (GOutputStream        *stream,
114                                                    GAsyncResult         *result,
115                                                    GError              **error);
116
117 static gboolean g_unix_output_stream_pollable_is_writable   (GPollableOutputStream *stream);
118 static GSource *g_unix_output_stream_pollable_create_source (GPollableOutputStream *stream,
119                                                              GCancellable         *cancellable);
120
121 static void
122 g_unix_output_stream_finalize (GObject *object)
123 {
124   G_OBJECT_CLASS (g_unix_output_stream_parent_class)->finalize (object);
125 }
126
127 static void
128 g_unix_output_stream_class_init (GUnixOutputStreamClass *klass)
129 {
130   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
131   GOutputStreamClass *stream_class = G_OUTPUT_STREAM_CLASS (klass);
132   
133   g_type_class_add_private (klass, sizeof (GUnixOutputStreamPrivate));
134
135   gobject_class->get_property = g_unix_output_stream_get_property;
136   gobject_class->set_property = g_unix_output_stream_set_property;
137   gobject_class->finalize = g_unix_output_stream_finalize;
138
139   stream_class->write_fn = g_unix_output_stream_write;
140   stream_class->close_fn = g_unix_output_stream_close;
141   stream_class->write_async = g_unix_output_stream_write_async;
142   stream_class->write_finish = g_unix_output_stream_write_finish;
143   stream_class->close_async = g_unix_output_stream_close_async;
144   stream_class->close_finish = g_unix_output_stream_close_finish;
145
146    /**
147    * GUnixOutputStream:fd:
148    *
149    * The file descriptor that the stream writes to.
150    *
151    * Since: 2.20
152    */
153   g_object_class_install_property (gobject_class,
154                                    PROP_FD,
155                                    g_param_spec_int ("fd",
156                                                      P_("File descriptor"),
157                                                      P_("The file descriptor to write to"),
158                                                      G_MININT, G_MAXINT, -1,
159                                                      G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
160
161   /**
162    * GUnixOutputStream:close-fd:
163    *
164    * Whether to close the file descriptor when the stream is closed.
165    *
166    * Since: 2.20
167    */
168   g_object_class_install_property (gobject_class,
169                                    PROP_CLOSE_FD,
170                                    g_param_spec_boolean ("close-fd",
171                                                          P_("Close file descriptor"),
172                                                          P_("Whether to close the file descriptor when the stream is closed"),
173                                                          TRUE,
174                                                          G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
175 }
176
177 static void
178 g_unix_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface)
179 {
180   iface->is_writable = g_unix_output_stream_pollable_is_writable;
181   iface->create_source = g_unix_output_stream_pollable_create_source;
182 }
183
184 static void
185 g_unix_output_stream_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface)
186 {
187   iface->get_fd = (int (*) (GFileDescriptorBased *))g_unix_output_stream_get_fd;
188 }
189
190 static void
191 g_unix_output_stream_set_property (GObject         *object,
192                                    guint            prop_id,
193                                    const GValue    *value,
194                                    GParamSpec      *pspec)
195 {
196   GUnixOutputStream *unix_stream;
197
198   unix_stream = G_UNIX_OUTPUT_STREAM (object);
199
200   switch (prop_id)
201     {
202     case PROP_FD:
203       unix_stream->priv->fd = g_value_get_int (value);
204       if (lseek (unix_stream->priv->fd, 0, SEEK_CUR) == -1 && errno == ESPIPE)
205         unix_stream->priv->is_pipe_or_socket = TRUE;
206       else
207         unix_stream->priv->is_pipe_or_socket = FALSE;
208       break;
209     case PROP_CLOSE_FD:
210       unix_stream->priv->close_fd = g_value_get_boolean (value);
211       break;
212     default:
213       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
214       break;
215     }
216 }
217
218 static void
219 g_unix_output_stream_get_property (GObject    *object,
220                                    guint       prop_id,
221                                    GValue     *value,
222                                    GParamSpec *pspec)
223 {
224   GUnixOutputStream *unix_stream;
225
226   unix_stream = G_UNIX_OUTPUT_STREAM (object);
227
228   switch (prop_id)
229     {
230     case PROP_FD:
231       g_value_set_int (value, unix_stream->priv->fd);
232       break;
233     case PROP_CLOSE_FD:
234       g_value_set_boolean (value, unix_stream->priv->close_fd);
235       break;
236     default:
237       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
238     }
239 }
240
241 static void
242 g_unix_output_stream_init (GUnixOutputStream *unix_stream)
243 {
244   unix_stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (unix_stream,
245                                                    G_TYPE_UNIX_OUTPUT_STREAM,
246                                                    GUnixOutputStreamPrivate);
247
248   unix_stream->priv->fd = -1;
249   unix_stream->priv->close_fd = TRUE;
250 }
251
252 /**
253  * g_unix_output_stream_new:
254  * @fd: a UNIX file descriptor
255  * @close_fd: %TRUE to close the file descriptor when done
256  * 
257  * Creates a new #GUnixOutputStream for the given @fd. 
258  * 
259  * If @close_fd, is %TRUE, the file descriptor will be closed when 
260  * the output stream is destroyed.
261  * 
262  * Returns: a new #GOutputStream
263  **/
264 GOutputStream *
265 g_unix_output_stream_new (gint     fd,
266                           gboolean close_fd)
267 {
268   GUnixOutputStream *stream;
269
270   g_return_val_if_fail (fd != -1, NULL);
271
272   stream = g_object_new (G_TYPE_UNIX_OUTPUT_STREAM,
273                          "fd", fd,
274                          "close-fd", close_fd,
275                          NULL);
276   
277   return G_OUTPUT_STREAM (stream);
278 }
279
280 /**
281  * g_unix_output_stream_set_close_fd:
282  * @stream: a #GUnixOutputStream
283  * @close_fd: %TRUE to close the file descriptor when done
284  *
285  * Sets whether the file descriptor of @stream shall be closed
286  * when the stream is closed.
287  *
288  * Since: 2.20
289  */
290 void
291 g_unix_output_stream_set_close_fd (GUnixOutputStream *stream,
292                                    gboolean           close_fd)
293 {
294   g_return_if_fail (G_IS_UNIX_OUTPUT_STREAM (stream));
295
296   close_fd = close_fd != FALSE;
297   if (stream->priv->close_fd != close_fd)
298     {
299       stream->priv->close_fd = close_fd;
300       g_object_notify (G_OBJECT (stream), "close-fd");
301     }
302 }
303
304 /**
305  * g_unix_output_stream_get_close_fd:
306  * @stream: a #GUnixOutputStream
307  *
308  * Returns whether the file descriptor of @stream will be
309  * closed when the stream is closed.
310  *
311  * Return value: %TRUE if the file descriptor is closed when done
312  *
313  * Since: 2.20
314  */
315 gboolean
316 g_unix_output_stream_get_close_fd (GUnixOutputStream *stream)
317 {
318   g_return_val_if_fail (G_IS_UNIX_OUTPUT_STREAM (stream), FALSE);
319
320   return stream->priv->close_fd;
321 }
322
323 /**
324  * g_unix_output_stream_get_fd:
325  * @stream: a #GUnixOutputStream
326  *
327  * Return the UNIX file descriptor that the stream writes to.
328  *
329  * Return value: The file descriptor of @stream
330  *
331  * Since: 2.20
332  */
333 gint
334 g_unix_output_stream_get_fd (GUnixOutputStream *stream)
335 {
336   g_return_val_if_fail (G_IS_UNIX_OUTPUT_STREAM (stream), -1);
337
338   return stream->priv->fd;
339 }
340
341 static gssize
342 g_unix_output_stream_write (GOutputStream  *stream,
343                             const void     *buffer,
344                             gsize           count,
345                             GCancellable   *cancellable,
346                             GError        **error)
347 {
348   GUnixOutputStream *unix_stream;
349   gssize res = -1;
350   GPollFD poll_fds[2];
351   int nfds;
352   int poll_ret;
353
354   unix_stream = G_UNIX_OUTPUT_STREAM (stream);
355
356   poll_fds[0].fd = unix_stream->priv->fd;
357   poll_fds[0].events = G_IO_OUT;
358
359   if (unix_stream->priv->is_pipe_or_socket &&
360       g_cancellable_make_pollfd (cancellable, &poll_fds[1]))
361     nfds = 2;
362   else
363     nfds = 1;
364
365   while (1)
366     {
367       poll_fds[0].revents = poll_fds[1].revents = 0;
368       do
369         poll_ret = g_poll (poll_fds, nfds, -1);
370       while (poll_ret == -1 && errno == EINTR);
371
372       if (poll_ret == -1)
373         {
374           int errsv = errno;
375
376           g_set_error (error, G_IO_ERROR,
377                        g_io_error_from_errno (errsv),
378                        _("Error writing to file descriptor: %s"),
379                        g_strerror (errsv));
380           break;
381         }
382
383       if (g_cancellable_set_error_if_cancelled (cancellable, error))
384         break;
385
386       if (!poll_fds[0].revents)
387         continue;
388
389       res = write (unix_stream->priv->fd, buffer, count);
390       if (res == -1)
391         {
392           int errsv = errno;
393
394           if (errsv == EINTR || errsv == EAGAIN)
395             continue;
396
397           g_set_error (error, G_IO_ERROR,
398                        g_io_error_from_errno (errsv),
399                        _("Error writing to file descriptor: %s"),
400                        g_strerror (errsv));
401         }
402
403       break;
404     }
405
406   g_cancellable_release_fd (cancellable);
407   return res;
408 }
409
410 static gboolean
411 g_unix_output_stream_close (GOutputStream  *stream,
412                             GCancellable   *cancellable,
413                             GError        **error)
414 {
415   GUnixOutputStream *unix_stream;
416   int res;
417
418   unix_stream = G_UNIX_OUTPUT_STREAM (stream);
419
420   if (!unix_stream->priv->close_fd)
421     return TRUE;
422   
423   while (1)
424     {
425       /* This might block during the close. Doesn't seem to be a way to avoid it though. */
426       res = close (unix_stream->priv->fd);
427       if (res == -1)
428         {
429           int errsv = errno;
430
431           g_set_error (error, G_IO_ERROR,
432                        g_io_error_from_errno (errsv),
433                        _("Error closing file descriptor: %s"),
434                        g_strerror (errsv));
435         }
436       break;
437     }
438
439   return res != -1;
440 }
441
442 typedef struct {
443   gsize count;
444   const void *buffer;
445   GAsyncReadyCallback callback;
446   gpointer user_data;
447   GCancellable *cancellable;
448   GUnixOutputStream *stream;
449 } WriteAsyncData;
450
451 static gboolean
452 write_async_cb (int             fd,
453                 GIOCondition    condition,
454                 WriteAsyncData *data)
455 {
456   GSimpleAsyncResult *simple;
457   GError *error = NULL;
458   gssize count_written;
459
460   while (1)
461     {
462       if (g_cancellable_set_error_if_cancelled (data->cancellable, &error))
463         {
464           count_written = -1;
465           break;
466         }
467       
468       count_written = write (data->stream->priv->fd, data->buffer, data->count);
469       if (count_written == -1)
470         {
471           int errsv = errno;
472
473           if (errsv == EINTR || errsv == EAGAIN)
474             return TRUE;
475           
476           g_set_error (&error, G_IO_ERROR,
477                        g_io_error_from_errno (errsv),
478                        _("Error writing to file descriptor: %s"),
479                        g_strerror (errsv));
480         }
481       break;
482     }
483
484   simple = g_simple_async_result_new (G_OBJECT (data->stream),
485                                       data->callback,
486                                       data->user_data,
487                                       g_unix_output_stream_write_async);
488   
489   g_simple_async_result_set_op_res_gssize (simple, count_written);
490
491   if (count_written == -1)
492     g_simple_async_result_take_error (simple, error);
493
494   /* Complete immediately, not in idle, since we're already in a mainloop callout */
495   g_simple_async_result_complete (simple);
496   g_object_unref (simple);
497
498   return FALSE;
499 }
500
501 static void
502 g_unix_output_stream_write_async (GOutputStream       *stream,
503                                   const void          *buffer,
504                                   gsize                count,
505                                   int                  io_priority,
506                                   GCancellable        *cancellable,
507                                   GAsyncReadyCallback  callback,
508                                   gpointer             user_data)
509 {
510   GSource *source;
511   GUnixOutputStream *unix_stream;
512   WriteAsyncData *data;
513
514   unix_stream = G_UNIX_OUTPUT_STREAM (stream);
515
516   if (!unix_stream->priv->is_pipe_or_socket)
517     {
518       G_OUTPUT_STREAM_CLASS (g_unix_output_stream_parent_class)->
519         write_async (stream, buffer, count, io_priority,
520                      cancellable, callback, user_data);
521       return;
522     }
523
524   data = g_new0 (WriteAsyncData, 1);
525   data->count = count;
526   data->buffer = buffer;
527   data->callback = callback;
528   data->user_data = user_data;
529   data->cancellable = cancellable;
530   data->stream = unix_stream;
531
532   source = _g_fd_source_new (unix_stream->priv->fd,
533                              G_IO_OUT,
534                              cancellable);
535   g_source_set_name (source, "GUnixOutputStream");
536   
537   g_source_set_callback (source, (GSourceFunc)write_async_cb, data, g_free);
538   g_source_attach (source, g_main_context_get_thread_default ());
539   
540   g_source_unref (source);
541 }
542
543 static gssize
544 g_unix_output_stream_write_finish (GOutputStream  *stream,
545                                    GAsyncResult   *result,
546                                    GError        **error)
547 {
548   GUnixOutputStream *unix_stream = G_UNIX_OUTPUT_STREAM (stream);
549   GSimpleAsyncResult *simple;
550   gssize nwritten;
551
552   if (!unix_stream->priv->is_pipe_or_socket)
553     {
554       return G_OUTPUT_STREAM_CLASS (g_unix_output_stream_parent_class)->
555         write_finish (stream, result, error);
556     }
557
558   simple = G_SIMPLE_ASYNC_RESULT (result);
559   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_unix_output_stream_write_async);
560   
561   nwritten = g_simple_async_result_get_op_res_gssize (simple);
562   return nwritten;
563 }
564
565 typedef struct {
566   GOutputStream *stream;
567   GAsyncReadyCallback callback;
568   gpointer user_data;
569 } CloseAsyncData;
570
571 static gboolean
572 close_async_cb (CloseAsyncData *data)
573 {
574   GUnixOutputStream *unix_stream;
575   GSimpleAsyncResult *simple;
576   GError *error = NULL;
577   gboolean result;
578   int res;
579
580   unix_stream = G_UNIX_OUTPUT_STREAM (data->stream);
581
582   if (!unix_stream->priv->close_fd)
583     {
584       result = TRUE;
585       goto out;
586     }
587   
588   while (1)
589     {
590       res = close (unix_stream->priv->fd);
591       if (res == -1)
592         {
593           int errsv = errno;
594
595           g_set_error (&error, G_IO_ERROR,
596                        g_io_error_from_errno (errsv),
597                        _("Error closing file descriptor: %s"),
598                        g_strerror (errsv));
599         }
600       break;
601     }
602   
603   result = res != -1;
604   
605  out:
606   simple = g_simple_async_result_new (G_OBJECT (data->stream),
607                                       data->callback,
608                                       data->user_data,
609                                       g_unix_output_stream_close_async);
610
611   if (!result)
612     g_simple_async_result_take_error (simple, error);
613
614   /* Complete immediately, not in idle, since we're already in a mainloop callout */
615   g_simple_async_result_complete (simple);
616   g_object_unref (simple);
617   
618   return FALSE;
619 }
620
621 static void
622 g_unix_output_stream_close_async (GOutputStream        *stream,
623                                   int                  io_priority,
624                                   GCancellable        *cancellable,
625                                   GAsyncReadyCallback  callback,
626                                   gpointer             user_data)
627 {
628   GSource *idle;
629   CloseAsyncData *data;
630
631   data = g_new0 (CloseAsyncData, 1);
632
633   data->stream = stream;
634   data->callback = callback;
635   data->user_data = user_data;
636   
637   idle = g_idle_source_new ();
638   g_source_set_callback (idle, (GSourceFunc)close_async_cb, data, g_free);
639   g_source_attach (idle, g_main_context_get_thread_default ());
640   g_source_unref (idle);
641 }
642
643 static gboolean
644 g_unix_output_stream_close_finish (GOutputStream  *stream,
645                                    GAsyncResult   *result,
646                                    GError        **error)
647 {
648   /* Failures handled in generic close_finish code */
649   return TRUE;
650 }
651
652 static gboolean
653 g_unix_output_stream_pollable_is_writable (GPollableOutputStream *stream)
654 {
655   GUnixOutputStream *unix_stream = G_UNIX_OUTPUT_STREAM (stream);
656   GPollFD poll_fd;
657   gint result;
658
659   poll_fd.fd = unix_stream->priv->fd;
660   poll_fd.events = G_IO_OUT;
661
662   do
663     result = g_poll (&poll_fd, 1, 0);
664   while (result == -1 && errno == EINTR);
665
666   return poll_fd.revents != 0;
667 }
668
669 static GSource *
670 g_unix_output_stream_pollable_create_source (GPollableOutputStream *stream,
671                                              GCancellable          *cancellable)
672 {
673   GUnixOutputStream *unix_stream = G_UNIX_OUTPUT_STREAM (stream);
674   GSource *inner_source, *pollable_source;
675
676   pollable_source = g_pollable_source_new (G_OBJECT (stream));
677
678   inner_source = _g_fd_source_new (unix_stream->priv->fd, G_IO_OUT, cancellable);
679   g_source_set_dummy_callback (inner_source);
680   g_source_add_child_source (pollable_source, inner_source);
681   g_source_unref (inner_source);
682
683   return pollable_source;
684 }