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