gio: port unix streams to GUnixFDSource
[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 <glib/glib-unix.h>
35 #include "gioerror.h"
36 #include "gunixoutputstream.h"
37 #include "gcancellable.h"
38 #include "gsimpleasyncresult.h"
39 #include "gasynchelper.h"
40 #include "gfiledescriptorbased.h"
41 #include "glibintl.h"
42
43
44 /**
45  * SECTION:gunixoutputstream
46  * @short_description: Streaming output operations for UNIX file descriptors
47  * @include: gio/gunixoutputstream.h
48  * @see_also: #GOutputStream
49  *
50  * #GUnixOutputStream implements #GOutputStream for writing to a UNIX
51  * file descriptor, including asynchronous operations. (If the file
52  * descriptor refers to a socket or pipe, this will use poll() to do
53  * asynchronous I/O. If it refers to a regular file, it will fall back
54  * to doing asynchronous I/O in another thread.)
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 struct _GUnixOutputStreamPrivate {
68   int fd;
69   guint close_fd : 1;
70   guint is_pipe_or_socket : 1;
71 };
72
73 static void g_unix_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface);
74 static void g_unix_output_stream_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface);
75
76 G_DEFINE_TYPE_WITH_CODE (GUnixOutputStream, g_unix_output_stream, G_TYPE_OUTPUT_STREAM,
77                          G_ADD_PRIVATE (GUnixOutputStream)
78                          G_IMPLEMENT_INTERFACE (G_TYPE_POLLABLE_OUTPUT_STREAM,
79                                                 g_unix_output_stream_pollable_iface_init)
80                          G_IMPLEMENT_INTERFACE (G_TYPE_FILE_DESCRIPTOR_BASED,
81                                                 g_unix_output_stream_file_descriptor_based_iface_init)
82                          )
83
84 static void     g_unix_output_stream_set_property (GObject              *object,
85                                                    guint                 prop_id,
86                                                    const GValue         *value,
87                                                    GParamSpec           *pspec);
88 static void     g_unix_output_stream_get_property (GObject              *object,
89                                                    guint                 prop_id,
90                                                    GValue               *value,
91                                                    GParamSpec           *pspec);
92 static gssize   g_unix_output_stream_write        (GOutputStream        *stream,
93                                                    const void           *buffer,
94                                                    gsize                 count,
95                                                    GCancellable         *cancellable,
96                                                    GError              **error);
97 static gboolean g_unix_output_stream_close        (GOutputStream        *stream,
98                                                    GCancellable         *cancellable,
99                                                    GError              **error);
100 static void     g_unix_output_stream_close_async  (GOutputStream        *stream,
101                                                    int                   io_priority,
102                                                    GCancellable         *cancellable,
103                                                    GAsyncReadyCallback   callback,
104                                                    gpointer              data);
105 static gboolean g_unix_output_stream_close_finish (GOutputStream        *stream,
106                                                    GAsyncResult         *result,
107                                                    GError              **error);
108
109 static gboolean g_unix_output_stream_pollable_can_poll      (GPollableOutputStream *stream);
110 static gboolean g_unix_output_stream_pollable_is_writable   (GPollableOutputStream *stream);
111 static GSource *g_unix_output_stream_pollable_create_source (GPollableOutputStream *stream,
112                                                              GCancellable         *cancellable);
113
114 static void
115 g_unix_output_stream_class_init (GUnixOutputStreamClass *klass)
116 {
117   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
118   GOutputStreamClass *stream_class = G_OUTPUT_STREAM_CLASS (klass);
119
120   gobject_class->get_property = g_unix_output_stream_get_property;
121   gobject_class->set_property = g_unix_output_stream_set_property;
122
123   stream_class->write_fn = g_unix_output_stream_write;
124   stream_class->close_fn = g_unix_output_stream_close;
125   stream_class->close_async = g_unix_output_stream_close_async;
126   stream_class->close_finish = g_unix_output_stream_close_finish;
127
128    /**
129    * GUnixOutputStream:fd:
130    *
131    * The file descriptor that the stream writes to.
132    *
133    * Since: 2.20
134    */
135   g_object_class_install_property (gobject_class,
136                                    PROP_FD,
137                                    g_param_spec_int ("fd",
138                                                      P_("File descriptor"),
139                                                      P_("The file descriptor to write to"),
140                                                      G_MININT, G_MAXINT, -1,
141                                                      G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
142
143   /**
144    * GUnixOutputStream:close-fd:
145    *
146    * Whether to close the file descriptor when the stream is closed.
147    *
148    * Since: 2.20
149    */
150   g_object_class_install_property (gobject_class,
151                                    PROP_CLOSE_FD,
152                                    g_param_spec_boolean ("close-fd",
153                                                          P_("Close file descriptor"),
154                                                          P_("Whether to close the file descriptor when the stream is closed"),
155                                                          TRUE,
156                                                          G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
157 }
158
159 static void
160 g_unix_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface)
161 {
162   iface->can_poll = g_unix_output_stream_pollable_can_poll;
163   iface->is_writable = g_unix_output_stream_pollable_is_writable;
164   iface->create_source = g_unix_output_stream_pollable_create_source;
165 }
166
167 static void
168 g_unix_output_stream_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface)
169 {
170   iface->get_fd = (int (*) (GFileDescriptorBased *))g_unix_output_stream_get_fd;
171 }
172
173 static void
174 g_unix_output_stream_set_property (GObject         *object,
175                                    guint            prop_id,
176                                    const GValue    *value,
177                                    GParamSpec      *pspec)
178 {
179   GUnixOutputStream *unix_stream;
180
181   unix_stream = G_UNIX_OUTPUT_STREAM (object);
182
183   switch (prop_id)
184     {
185     case PROP_FD:
186       unix_stream->priv->fd = g_value_get_int (value);
187       if (lseek (unix_stream->priv->fd, 0, SEEK_CUR) == -1 && errno == ESPIPE)
188         unix_stream->priv->is_pipe_or_socket = TRUE;
189       else
190         unix_stream->priv->is_pipe_or_socket = FALSE;
191       break;
192     case PROP_CLOSE_FD:
193       unix_stream->priv->close_fd = g_value_get_boolean (value);
194       break;
195     default:
196       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
197       break;
198     }
199 }
200
201 static void
202 g_unix_output_stream_get_property (GObject    *object,
203                                    guint       prop_id,
204                                    GValue     *value,
205                                    GParamSpec *pspec)
206 {
207   GUnixOutputStream *unix_stream;
208
209   unix_stream = G_UNIX_OUTPUT_STREAM (object);
210
211   switch (prop_id)
212     {
213     case PROP_FD:
214       g_value_set_int (value, unix_stream->priv->fd);
215       break;
216     case PROP_CLOSE_FD:
217       g_value_set_boolean (value, unix_stream->priv->close_fd);
218       break;
219     default:
220       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
221     }
222 }
223
224 static void
225 g_unix_output_stream_init (GUnixOutputStream *unix_stream)
226 {
227   unix_stream->priv = g_unix_output_stream_get_instance_private (unix_stream);
228   unix_stream->priv->fd = -1;
229   unix_stream->priv->close_fd = TRUE;
230 }
231
232 /**
233  * g_unix_output_stream_new:
234  * @fd: a UNIX file descriptor
235  * @close_fd: %TRUE to close the file descriptor when done
236  * 
237  * Creates a new #GUnixOutputStream for the given @fd. 
238  * 
239  * If @close_fd, is %TRUE, the file descriptor will be closed when 
240  * the output stream is destroyed.
241  * 
242  * Returns: a new #GOutputStream
243  **/
244 GOutputStream *
245 g_unix_output_stream_new (gint     fd,
246                           gboolean close_fd)
247 {
248   GUnixOutputStream *stream;
249
250   g_return_val_if_fail (fd != -1, NULL);
251
252   stream = g_object_new (G_TYPE_UNIX_OUTPUT_STREAM,
253                          "fd", fd,
254                          "close-fd", close_fd,
255                          NULL);
256   
257   return G_OUTPUT_STREAM (stream);
258 }
259
260 /**
261  * g_unix_output_stream_set_close_fd:
262  * @stream: a #GUnixOutputStream
263  * @close_fd: %TRUE to close the file descriptor when done
264  *
265  * Sets whether the file descriptor of @stream shall be closed
266  * when the stream is closed.
267  *
268  * Since: 2.20
269  */
270 void
271 g_unix_output_stream_set_close_fd (GUnixOutputStream *stream,
272                                    gboolean           close_fd)
273 {
274   g_return_if_fail (G_IS_UNIX_OUTPUT_STREAM (stream));
275
276   close_fd = close_fd != FALSE;
277   if (stream->priv->close_fd != close_fd)
278     {
279       stream->priv->close_fd = close_fd;
280       g_object_notify (G_OBJECT (stream), "close-fd");
281     }
282 }
283
284 /**
285  * g_unix_output_stream_get_close_fd:
286  * @stream: a #GUnixOutputStream
287  *
288  * Returns whether the file descriptor of @stream will be
289  * closed when the stream is closed.
290  *
291  * Return value: %TRUE if the file descriptor is closed when done
292  *
293  * Since: 2.20
294  */
295 gboolean
296 g_unix_output_stream_get_close_fd (GUnixOutputStream *stream)
297 {
298   g_return_val_if_fail (G_IS_UNIX_OUTPUT_STREAM (stream), FALSE);
299
300   return stream->priv->close_fd;
301 }
302
303 /**
304  * g_unix_output_stream_get_fd:
305  * @stream: a #GUnixOutputStream
306  *
307  * Return the UNIX file descriptor that the stream writes to.
308  *
309  * Return value: The file descriptor of @stream
310  *
311  * Since: 2.20
312  */
313 gint
314 g_unix_output_stream_get_fd (GUnixOutputStream *stream)
315 {
316   g_return_val_if_fail (G_IS_UNIX_OUTPUT_STREAM (stream), -1);
317
318   return stream->priv->fd;
319 }
320
321 static gssize
322 g_unix_output_stream_write (GOutputStream  *stream,
323                             const void     *buffer,
324                             gsize           count,
325                             GCancellable   *cancellable,
326                             GError        **error)
327 {
328   GUnixOutputStream *unix_stream;
329   gssize res = -1;
330   GPollFD poll_fds[2];
331   int nfds;
332   int poll_ret;
333
334   unix_stream = G_UNIX_OUTPUT_STREAM (stream);
335
336   poll_fds[0].fd = unix_stream->priv->fd;
337   poll_fds[0].events = G_IO_OUT;
338
339   if (unix_stream->priv->is_pipe_or_socket &&
340       g_cancellable_make_pollfd (cancellable, &poll_fds[1]))
341     nfds = 2;
342   else
343     nfds = 1;
344
345   while (1)
346     {
347       poll_fds[0].revents = poll_fds[1].revents = 0;
348       do
349         poll_ret = g_poll (poll_fds, nfds, -1);
350       while (poll_ret == -1 && errno == EINTR);
351
352       if (poll_ret == -1)
353         {
354           int errsv = errno;
355
356           g_set_error (error, G_IO_ERROR,
357                        g_io_error_from_errno (errsv),
358                        _("Error writing to file descriptor: %s"),
359                        g_strerror (errsv));
360           break;
361         }
362
363       if (g_cancellable_set_error_if_cancelled (cancellable, error))
364         break;
365
366       if (!poll_fds[0].revents)
367         continue;
368
369       res = write (unix_stream->priv->fd, buffer, count);
370       if (res == -1)
371         {
372           int errsv = errno;
373
374           if (errsv == EINTR || errsv == EAGAIN)
375             continue;
376
377           g_set_error (error, G_IO_ERROR,
378                        g_io_error_from_errno (errsv),
379                        _("Error writing to file descriptor: %s"),
380                        g_strerror (errsv));
381         }
382
383       break;
384     }
385
386   if (nfds == 2)
387     g_cancellable_release_fd (cancellable);
388   return res;
389 }
390
391 static gboolean
392 g_unix_output_stream_close (GOutputStream  *stream,
393                             GCancellable   *cancellable,
394                             GError        **error)
395 {
396   GUnixOutputStream *unix_stream;
397   int res;
398
399   unix_stream = G_UNIX_OUTPUT_STREAM (stream);
400
401   if (!unix_stream->priv->close_fd)
402     return TRUE;
403   
404   /* This might block during the close. Doesn't seem to be a way to avoid it though. */
405   res = close (unix_stream->priv->fd);
406   if (res == -1)
407     {
408       int errsv = errno;
409
410       g_set_error (error, G_IO_ERROR,
411                    g_io_error_from_errno (errsv),
412                    _("Error closing file descriptor: %s"),
413                    g_strerror (errsv));
414     }
415
416   return res != -1;
417 }
418
419 static void
420 g_unix_output_stream_close_async (GOutputStream       *stream,
421                                   int                  io_priority,
422                                   GCancellable        *cancellable,
423                                   GAsyncReadyCallback  callback,
424                                   gpointer             user_data)
425 {
426   GTask *task;
427   GError *error = NULL;
428
429   task = g_task_new (stream, cancellable, callback, user_data);
430   g_task_set_priority (task, io_priority);
431
432   if (g_unix_output_stream_close (stream, cancellable, &error))
433     g_task_return_boolean (task, TRUE);
434   else
435     g_task_return_error (task, error);
436   g_object_unref (task);
437 }
438
439 static gboolean
440 g_unix_output_stream_close_finish (GOutputStream  *stream,
441                                    GAsyncResult   *result,
442                                    GError        **error)
443 {
444   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
445
446   return g_task_propagate_boolean (G_TASK (result), error);
447 }
448
449 static gboolean
450 g_unix_output_stream_pollable_can_poll (GPollableOutputStream *stream)
451 {
452   return G_UNIX_OUTPUT_STREAM (stream)->priv->is_pipe_or_socket;
453 }
454
455 static gboolean
456 g_unix_output_stream_pollable_is_writable (GPollableOutputStream *stream)
457 {
458   GUnixOutputStream *unix_stream = G_UNIX_OUTPUT_STREAM (stream);
459   GPollFD poll_fd;
460   gint result;
461
462   poll_fd.fd = unix_stream->priv->fd;
463   poll_fd.events = G_IO_OUT;
464   poll_fd.revents = 0;
465
466   do
467     result = g_poll (&poll_fd, 1, 0);
468   while (result == -1 && errno == EINTR);
469
470   return poll_fd.revents != 0;
471 }
472
473 static GSource *
474 g_unix_output_stream_pollable_create_source (GPollableOutputStream *stream,
475                                              GCancellable          *cancellable)
476 {
477   GUnixOutputStream *unix_stream = G_UNIX_OUTPUT_STREAM (stream);
478   GSource *inner_source, *cancellable_source, *pollable_source;
479
480   pollable_source = g_pollable_source_new (G_OBJECT (stream));
481
482   inner_source = g_unix_fd_source_new (unix_stream->priv->fd, G_IO_OUT);
483   g_source_set_dummy_callback (inner_source);
484   g_source_add_child_source (pollable_source, inner_source);
485   g_source_unref (inner_source);
486
487   if (cancellable)
488     {
489       cancellable_source = g_cancellable_source_new (cancellable);
490       g_source_set_dummy_callback (cancellable_source);
491       g_source_add_child_source (pollable_source, cancellable_source);
492       g_source_unref (cancellable_source);
493     }
494
495   return pollable_source;
496 }