gio: port unix streams to GUnixFDSource
[platform/upstream/glib.git] / gio / gunixinputstream.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 "gsimpleasyncresult.h"
37 #include "gunixinputstream.h"
38 #include "gcancellable.h"
39 #include "gasynchelper.h"
40 #include "gfiledescriptorbased.h"
41 #include "glibintl.h"
42
43
44 /**
45  * SECTION:gunixinputstream
46  * @short_description: Streaming input operations for UNIX file descriptors
47  * @include: gio/gunixinputstream.h
48  * @see_also: #GInputStream
49  *
50  * #GUnixInputStream implements #GInputStream for reading from 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/gunixinputstream.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 _GUnixInputStreamPrivate {
68   int fd;
69   guint close_fd : 1;
70   guint is_pipe_or_socket : 1;
71 };
72
73 static void g_unix_input_stream_pollable_iface_init (GPollableInputStreamInterface *iface);
74 static void g_unix_input_stream_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface);
75
76 G_DEFINE_TYPE_WITH_CODE (GUnixInputStream, g_unix_input_stream, G_TYPE_INPUT_STREAM,
77                          G_ADD_PRIVATE (GUnixInputStream)
78                          G_IMPLEMENT_INTERFACE (G_TYPE_POLLABLE_INPUT_STREAM,
79                                                 g_unix_input_stream_pollable_iface_init)
80                          G_IMPLEMENT_INTERFACE (G_TYPE_FILE_DESCRIPTOR_BASED,
81                                                 g_unix_input_stream_file_descriptor_based_iface_init)
82                          )
83
84 static void     g_unix_input_stream_set_property (GObject              *object,
85                                                   guint                 prop_id,
86                                                   const GValue         *value,
87                                                   GParamSpec           *pspec);
88 static void     g_unix_input_stream_get_property (GObject              *object,
89                                                   guint                 prop_id,
90                                                   GValue               *value,
91                                                   GParamSpec           *pspec);
92 static gssize   g_unix_input_stream_read         (GInputStream         *stream,
93                                                   void                 *buffer,
94                                                   gsize                 count,
95                                                   GCancellable         *cancellable,
96                                                   GError              **error);
97 static gboolean g_unix_input_stream_close        (GInputStream         *stream,
98                                                   GCancellable         *cancellable,
99                                                   GError              **error);
100 static void     g_unix_input_stream_skip_async   (GInputStream         *stream,
101                                                   gsize                 count,
102                                                   int                   io_priority,
103                                                   GCancellable         *cancellable,
104                                                   GAsyncReadyCallback   callback,
105                                                   gpointer              data);
106 static gssize   g_unix_input_stream_skip_finish  (GInputStream         *stream,
107                                                   GAsyncResult         *result,
108                                                   GError              **error);
109 static void     g_unix_input_stream_close_async  (GInputStream         *stream,
110                                                   int                   io_priority,
111                                                   GCancellable         *cancellable,
112                                                   GAsyncReadyCallback   callback,
113                                                   gpointer              data);
114 static gboolean g_unix_input_stream_close_finish (GInputStream         *stream,
115                                                   GAsyncResult         *result,
116                                                   GError              **error);
117
118 static gboolean g_unix_input_stream_pollable_can_poll      (GPollableInputStream *stream);
119 static gboolean g_unix_input_stream_pollable_is_readable   (GPollableInputStream *stream);
120 static GSource *g_unix_input_stream_pollable_create_source (GPollableInputStream *stream,
121                                                             GCancellable         *cancellable);
122
123 static void
124 g_unix_input_stream_class_init (GUnixInputStreamClass *klass)
125 {
126   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
127   GInputStreamClass *stream_class = G_INPUT_STREAM_CLASS (klass);
128
129   gobject_class->get_property = g_unix_input_stream_get_property;
130   gobject_class->set_property = g_unix_input_stream_set_property;
131
132   stream_class->read_fn = g_unix_input_stream_read;
133   stream_class->close_fn = g_unix_input_stream_close;
134   if (0)
135     {
136       /* TODO: Implement instead of using fallbacks */
137       stream_class->skip_async = g_unix_input_stream_skip_async;
138       stream_class->skip_finish = g_unix_input_stream_skip_finish;
139     }
140   stream_class->close_async = g_unix_input_stream_close_async;
141   stream_class->close_finish = g_unix_input_stream_close_finish;
142
143   /**
144    * GUnixInputStream:fd:
145    *
146    * The file descriptor that the stream reads from.
147    *
148    * Since: 2.20
149    */
150   g_object_class_install_property (gobject_class,
151                                    PROP_FD,
152                                    g_param_spec_int ("fd",
153                                                      P_("File descriptor"),
154                                                      P_("The file descriptor to read from"),
155                                                      G_MININT, G_MAXINT, -1,
156                                                      G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
157
158   /**
159    * GUnixInputStream:close-fd:
160    *
161    * Whether to close the file descriptor when the stream is closed.
162    *
163    * Since: 2.20
164    */
165   g_object_class_install_property (gobject_class,
166                                    PROP_CLOSE_FD,
167                                    g_param_spec_boolean ("close-fd",
168                                                          P_("Close file descriptor"),
169                                                          P_("Whether to close the file descriptor when the stream is closed"),
170                                                          TRUE,
171                                                          G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
172 }
173
174 static void
175 g_unix_input_stream_pollable_iface_init (GPollableInputStreamInterface *iface)
176 {
177   iface->can_poll = g_unix_input_stream_pollable_can_poll;
178   iface->is_readable = g_unix_input_stream_pollable_is_readable;
179   iface->create_source = g_unix_input_stream_pollable_create_source;
180 }
181
182 static void
183 g_unix_input_stream_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface)
184 {
185   iface->get_fd = (int (*) (GFileDescriptorBased *))g_unix_input_stream_get_fd;
186 }
187
188 static void
189 g_unix_input_stream_set_property (GObject         *object,
190                                   guint            prop_id,
191                                   const GValue    *value,
192                                   GParamSpec      *pspec)
193 {
194   GUnixInputStream *unix_stream;
195   
196   unix_stream = G_UNIX_INPUT_STREAM (object);
197
198   switch (prop_id)
199     {
200     case PROP_FD:
201       unix_stream->priv->fd = g_value_get_int (value);
202       if (lseek (unix_stream->priv->fd, 0, SEEK_CUR) == -1 && errno == ESPIPE)
203         unix_stream->priv->is_pipe_or_socket = TRUE;
204       else
205         unix_stream->priv->is_pipe_or_socket = FALSE;
206       break;
207     case PROP_CLOSE_FD:
208       unix_stream->priv->close_fd = g_value_get_boolean (value);
209       break;
210     default:
211       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
212       break;
213     }
214 }
215
216 static void
217 g_unix_input_stream_get_property (GObject    *object,
218                                   guint       prop_id,
219                                   GValue     *value,
220                                   GParamSpec *pspec)
221 {
222   GUnixInputStream *unix_stream;
223
224   unix_stream = G_UNIX_INPUT_STREAM (object);
225
226   switch (prop_id)
227     {
228     case PROP_FD:
229       g_value_set_int (value, unix_stream->priv->fd);
230       break;
231     case PROP_CLOSE_FD:
232       g_value_set_boolean (value, unix_stream->priv->close_fd);
233       break;
234     default:
235       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
236     }
237 }
238
239 static void
240 g_unix_input_stream_init (GUnixInputStream *unix_stream)
241 {
242   unix_stream->priv = g_unix_input_stream_get_instance_private (unix_stream);
243   unix_stream->priv->fd = -1;
244   unix_stream->priv->close_fd = TRUE;
245 }
246
247 /**
248  * g_unix_input_stream_new:
249  * @fd: a UNIX file descriptor
250  * @close_fd: %TRUE to close the file descriptor when done
251  * 
252  * Creates a new #GUnixInputStream for the given @fd. 
253  *
254  * If @close_fd is %TRUE, the file descriptor will be closed 
255  * when the stream is closed.
256  * 
257  * Returns: a new #GUnixInputStream
258  **/
259 GInputStream *
260 g_unix_input_stream_new (gint     fd,
261                          gboolean close_fd)
262 {
263   GUnixInputStream *stream;
264
265   g_return_val_if_fail (fd != -1, NULL);
266
267   stream = g_object_new (G_TYPE_UNIX_INPUT_STREAM,
268                          "fd", fd,
269                          "close-fd", close_fd,
270                          NULL);
271
272   return G_INPUT_STREAM (stream);
273 }
274
275 /**
276  * g_unix_input_stream_set_close_fd:
277  * @stream: a #GUnixInputStream
278  * @close_fd: %TRUE to close the file descriptor when done
279  *
280  * Sets whether the file descriptor of @stream shall be closed
281  * when the stream is closed.
282  *
283  * Since: 2.20
284  */
285 void
286 g_unix_input_stream_set_close_fd (GUnixInputStream *stream,
287                                   gboolean          close_fd)
288 {
289   g_return_if_fail (G_IS_UNIX_INPUT_STREAM (stream));
290
291   close_fd = close_fd != FALSE;
292   if (stream->priv->close_fd != close_fd)
293     {
294       stream->priv->close_fd = close_fd;
295       g_object_notify (G_OBJECT (stream), "close-fd");
296     }
297 }
298
299 /**
300  * g_unix_input_stream_get_close_fd:
301  * @stream: a #GUnixInputStream
302  *
303  * Returns whether the file descriptor of @stream will be
304  * closed when the stream is closed.
305  *
306  * Return value: %TRUE if the file descriptor is closed when done
307  *
308  * Since: 2.20
309  */
310 gboolean
311 g_unix_input_stream_get_close_fd (GUnixInputStream *stream)
312 {
313   g_return_val_if_fail (G_IS_UNIX_INPUT_STREAM (stream), FALSE);
314
315   return stream->priv->close_fd;
316 }
317
318 /**
319  * g_unix_input_stream_get_fd:
320  * @stream: a #GUnixInputStream
321  *
322  * Return the UNIX file descriptor that the stream reads from.
323  *
324  * Return value: The file descriptor of @stream
325  *
326  * Since: 2.20
327  */
328 gint
329 g_unix_input_stream_get_fd (GUnixInputStream *stream)
330 {
331   g_return_val_if_fail (G_IS_UNIX_INPUT_STREAM (stream), -1);
332   
333   return stream->priv->fd;
334 }
335
336 static gssize
337 g_unix_input_stream_read (GInputStream  *stream,
338                           void          *buffer,
339                           gsize          count,
340                           GCancellable  *cancellable,
341                           GError       **error)
342 {
343   GUnixInputStream *unix_stream;
344   gssize res = -1;
345   GPollFD poll_fds[2];
346   int nfds;
347   int poll_ret;
348
349   unix_stream = G_UNIX_INPUT_STREAM (stream);
350
351   poll_fds[0].fd = unix_stream->priv->fd;
352   poll_fds[0].events = G_IO_IN;
353   if (unix_stream->priv->is_pipe_or_socket &&
354       g_cancellable_make_pollfd (cancellable, &poll_fds[1]))
355     nfds = 2;
356   else
357     nfds = 1;
358
359   while (1)
360     {
361       poll_fds[0].revents = poll_fds[1].revents = 0;
362       do
363         poll_ret = g_poll (poll_fds, nfds, -1);
364       while (poll_ret == -1 && errno == EINTR);
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 reading from file descriptor: %s"),
373                        g_strerror (errsv));
374           break;
375         }
376
377       if (g_cancellable_set_error_if_cancelled (cancellable, error))
378         break;
379
380       if (!poll_fds[0].revents)
381         continue;
382
383       res = read (unix_stream->priv->fd, buffer, count);
384       if (res == -1)
385         {
386           int errsv = errno;
387
388           if (errsv == EINTR || errsv == EAGAIN)
389             continue;
390
391           g_set_error (error, G_IO_ERROR,
392                        g_io_error_from_errno (errsv),
393                        _("Error reading from file descriptor: %s"),
394                        g_strerror (errsv));
395         }
396
397       break;
398     }
399
400   if (nfds == 2)
401     g_cancellable_release_fd (cancellable);
402   return res;
403 }
404
405 static gboolean
406 g_unix_input_stream_close (GInputStream  *stream,
407                            GCancellable  *cancellable,
408                            GError       **error)
409 {
410   GUnixInputStream *unix_stream;
411   int res;
412
413   unix_stream = G_UNIX_INPUT_STREAM (stream);
414
415   if (!unix_stream->priv->close_fd)
416     return TRUE;
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 file descriptor: %s"),
427                    g_strerror (errsv));
428     }
429   
430   return res != -1;
431 }
432
433 static void
434 g_unix_input_stream_skip_async (GInputStream        *stream,
435                                 gsize                count,
436                                 int                  io_priority,
437                                 GCancellable        *cancellable,
438                                 GAsyncReadyCallback  callback,
439                                 gpointer             data)
440 {
441   g_warn_if_reached ();
442   /* TODO: Not implemented */
443 }
444
445 static gssize
446 g_unix_input_stream_skip_finish  (GInputStream  *stream,
447                                   GAsyncResult  *result,
448                                   GError       **error)
449 {
450   g_warn_if_reached ();
451   return 0;
452   /* TODO: Not implemented */
453 }
454
455 static void
456 g_unix_input_stream_close_async (GInputStream        *stream,
457                                  int                  io_priority,
458                                  GCancellable        *cancellable,
459                                  GAsyncReadyCallback  callback,
460                                  gpointer             user_data)
461 {
462   GTask *task;
463   GError *error = NULL;
464
465   task = g_task_new (stream, cancellable, callback, user_data);
466   g_task_set_priority (task, io_priority);
467
468   if (g_unix_input_stream_close (stream, cancellable, &error))
469     g_task_return_boolean (task, TRUE);
470   else
471     g_task_return_error (task, error);
472   g_object_unref (task);
473 }
474
475 static gboolean
476 g_unix_input_stream_close_finish (GInputStream  *stream,
477                                   GAsyncResult  *result,
478                                   GError       **error)
479 {
480   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
481
482   return g_task_propagate_boolean (G_TASK (result), error);
483 }
484
485 static gboolean
486 g_unix_input_stream_pollable_can_poll (GPollableInputStream *stream)
487 {
488   return G_UNIX_INPUT_STREAM (stream)->priv->is_pipe_or_socket;
489 }
490
491 static gboolean
492 g_unix_input_stream_pollable_is_readable (GPollableInputStream *stream)
493 {
494   GUnixInputStream *unix_stream = G_UNIX_INPUT_STREAM (stream);
495   GPollFD poll_fd;
496   gint result;
497
498   poll_fd.fd = unix_stream->priv->fd;
499   poll_fd.events = G_IO_IN;
500   poll_fd.revents = 0;
501
502   do
503     result = g_poll (&poll_fd, 1, 0);
504   while (result == -1 && errno == EINTR);
505
506   return poll_fd.revents != 0;
507 }
508
509 static GSource *
510 g_unix_input_stream_pollable_create_source (GPollableInputStream *stream,
511                                             GCancellable         *cancellable)
512 {
513   GUnixInputStream *unix_stream = G_UNIX_INPUT_STREAM (stream);
514   GSource *inner_source, *cancellable_source, *pollable_source;
515
516   pollable_source = g_pollable_source_new (G_OBJECT (stream));
517
518   inner_source = g_unix_fd_source_new (unix_stream->priv->fd, G_IO_IN);
519   g_source_set_dummy_callback (inner_source);
520   g_source_add_child_source (pollable_source, inner_source);
521   g_source_unref (inner_source);
522
523   if (cancellable)
524     {
525       cancellable_source = g_cancellable_source_new (cancellable);
526       g_source_set_dummy_callback (cancellable_source);
527       g_source_add_child_source (pollable_source, cancellable_source);
528       g_source_unref (cancellable_source);
529     }
530
531   return pollable_source;
532 }