GUnix{Input,Output}Stream: Only release cancelable poll-fd if we allocated it
[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 "gioerror.h"
35 #include "gsimpleasyncresult.h"
36 #include "gunixinputstream.h"
37 #include "gcancellable.h"
38 #include "gasynchelper.h"
39 #include "gfiledescriptorbased.h"
40 #include "glibintl.h"
41
42
43 /**
44  * SECTION:gunixinputstream
45  * @short_description: Streaming input operations for UNIX file descriptors
46  * @include: gio/gunixinputstream.h
47  * @see_also: #GInputStream
48  *
49  * #GUnixInputStream implements #GInputStream for reading from 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/gunixinputstream.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_input_stream_pollable_iface_init (GPollableInputStreamInterface *iface);
67 static void g_unix_input_stream_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface);
68
69 G_DEFINE_TYPE_WITH_CODE (GUnixInputStream, g_unix_input_stream, G_TYPE_INPUT_STREAM,
70                          G_IMPLEMENT_INTERFACE (G_TYPE_POLLABLE_INPUT_STREAM,
71                                                 g_unix_input_stream_pollable_iface_init)
72                          G_IMPLEMENT_INTERFACE (G_TYPE_FILE_DESCRIPTOR_BASED,
73                                                 g_unix_input_stream_file_descriptor_based_iface_init)
74                          )
75
76 struct _GUnixInputStreamPrivate {
77   int fd;
78   guint close_fd : 1;
79   guint is_pipe_or_socket : 1;
80 };
81
82 static void     g_unix_input_stream_set_property (GObject              *object,
83                                                   guint                 prop_id,
84                                                   const GValue         *value,
85                                                   GParamSpec           *pspec);
86 static void     g_unix_input_stream_get_property (GObject              *object,
87                                                   guint                 prop_id,
88                                                   GValue               *value,
89                                                   GParamSpec           *pspec);
90 static gssize   g_unix_input_stream_read         (GInputStream         *stream,
91                                                   void                 *buffer,
92                                                   gsize                 count,
93                                                   GCancellable         *cancellable,
94                                                   GError              **error);
95 static gboolean g_unix_input_stream_close        (GInputStream         *stream,
96                                                   GCancellable         *cancellable,
97                                                   GError              **error);
98 static void     g_unix_input_stream_read_async   (GInputStream         *stream,
99                                                   void                 *buffer,
100                                                   gsize                 count,
101                                                   int                   io_priority,
102                                                   GCancellable         *cancellable,
103                                                   GAsyncReadyCallback   callback,
104                                                   gpointer              data);
105 static gssize   g_unix_input_stream_read_finish  (GInputStream         *stream,
106                                                   GAsyncResult         *result,
107                                                   GError              **error);
108 static void     g_unix_input_stream_skip_async   (GInputStream         *stream,
109                                                   gsize                 count,
110                                                   int                   io_priority,
111                                                   GCancellable         *cancellable,
112                                                   GAsyncReadyCallback   callback,
113                                                   gpointer              data);
114 static gssize   g_unix_input_stream_skip_finish  (GInputStream         *stream,
115                                                   GAsyncResult         *result,
116                                                   GError              **error);
117 static void     g_unix_input_stream_close_async  (GInputStream         *stream,
118                                                   int                   io_priority,
119                                                   GCancellable         *cancellable,
120                                                   GAsyncReadyCallback   callback,
121                                                   gpointer              data);
122 static gboolean g_unix_input_stream_close_finish (GInputStream         *stream,
123                                                   GAsyncResult         *result,
124                                                   GError              **error);
125
126 static gboolean g_unix_input_stream_pollable_is_readable   (GPollableInputStream *stream);
127 static GSource *g_unix_input_stream_pollable_create_source (GPollableInputStream *stream,
128                                                             GCancellable         *cancellable);
129
130 static void
131 g_unix_input_stream_finalize (GObject *object)
132 {
133   G_OBJECT_CLASS (g_unix_input_stream_parent_class)->finalize (object);
134 }
135
136 static void
137 g_unix_input_stream_class_init (GUnixInputStreamClass *klass)
138 {
139   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
140   GInputStreamClass *stream_class = G_INPUT_STREAM_CLASS (klass);
141   
142   g_type_class_add_private (klass, sizeof (GUnixInputStreamPrivate));
143
144   gobject_class->get_property = g_unix_input_stream_get_property;
145   gobject_class->set_property = g_unix_input_stream_set_property;
146   gobject_class->finalize = g_unix_input_stream_finalize;
147
148   stream_class->read_fn = g_unix_input_stream_read;
149   stream_class->close_fn = g_unix_input_stream_close;
150   stream_class->read_async = g_unix_input_stream_read_async;
151   stream_class->read_finish = g_unix_input_stream_read_finish;
152   if (0)
153     {
154       /* TODO: Implement instead of using fallbacks */
155       stream_class->skip_async = g_unix_input_stream_skip_async;
156       stream_class->skip_finish = g_unix_input_stream_skip_finish;
157     }
158   stream_class->close_async = g_unix_input_stream_close_async;
159   stream_class->close_finish = g_unix_input_stream_close_finish;
160
161   /**
162    * GUnixInputStream:fd:
163    *
164    * The file descriptor that the stream reads from.
165    *
166    * Since: 2.20
167    */
168   g_object_class_install_property (gobject_class,
169                                    PROP_FD,
170                                    g_param_spec_int ("fd",
171                                                      P_("File descriptor"),
172                                                      P_("The file descriptor to read from"),
173                                                      G_MININT, G_MAXINT, -1,
174                                                      G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
175
176   /**
177    * GUnixInputStream:close-fd:
178    *
179    * Whether to close the file descriptor when the stream is closed.
180    *
181    * Since: 2.20
182    */
183   g_object_class_install_property (gobject_class,
184                                    PROP_CLOSE_FD,
185                                    g_param_spec_boolean ("close-fd",
186                                                          P_("Close file descriptor"),
187                                                          P_("Whether to close the file descriptor when the stream is closed"),
188                                                          TRUE,
189                                                          G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
190 }
191
192 static void
193 g_unix_input_stream_pollable_iface_init (GPollableInputStreamInterface *iface)
194 {
195   iface->is_readable = g_unix_input_stream_pollable_is_readable;
196   iface->create_source = g_unix_input_stream_pollable_create_source;
197 }
198
199 static void
200 g_unix_input_stream_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface)
201 {
202   iface->get_fd = (int (*) (GFileDescriptorBased *))g_unix_input_stream_get_fd;
203 }
204
205 static void
206 g_unix_input_stream_set_property (GObject         *object,
207                                   guint            prop_id,
208                                   const GValue    *value,
209                                   GParamSpec      *pspec)
210 {
211   GUnixInputStream *unix_stream;
212   
213   unix_stream = G_UNIX_INPUT_STREAM (object);
214
215   switch (prop_id)
216     {
217     case PROP_FD:
218       unix_stream->priv->fd = g_value_get_int (value);
219       if (lseek (unix_stream->priv->fd, 0, SEEK_CUR) == -1 && errno == ESPIPE)
220         unix_stream->priv->is_pipe_or_socket = TRUE;
221       else
222         unix_stream->priv->is_pipe_or_socket = FALSE;
223       break;
224     case PROP_CLOSE_FD:
225       unix_stream->priv->close_fd = g_value_get_boolean (value);
226       break;
227     default:
228       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
229       break;
230     }
231 }
232
233 static void
234 g_unix_input_stream_get_property (GObject    *object,
235                                   guint       prop_id,
236                                   GValue     *value,
237                                   GParamSpec *pspec)
238 {
239   GUnixInputStream *unix_stream;
240
241   unix_stream = G_UNIX_INPUT_STREAM (object);
242
243   switch (prop_id)
244     {
245     case PROP_FD:
246       g_value_set_int (value, unix_stream->priv->fd);
247       break;
248     case PROP_CLOSE_FD:
249       g_value_set_boolean (value, unix_stream->priv->close_fd);
250       break;
251     default:
252       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
253     }
254 }
255
256 static void
257 g_unix_input_stream_init (GUnixInputStream *unix_stream)
258 {
259   unix_stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (unix_stream,
260                                                    G_TYPE_UNIX_INPUT_STREAM,
261                                                    GUnixInputStreamPrivate);
262
263   unix_stream->priv->fd = -1;
264   unix_stream->priv->close_fd = TRUE;
265 }
266
267 /**
268  * g_unix_input_stream_new:
269  * @fd: a UNIX file descriptor
270  * @close_fd: %TRUE to close the file descriptor when done
271  * 
272  * Creates a new #GUnixInputStream for the given @fd. 
273  *
274  * If @close_fd is %TRUE, the file descriptor will be closed 
275  * when the stream is closed.
276  * 
277  * Returns: a new #GUnixInputStream
278  **/
279 GInputStream *
280 g_unix_input_stream_new (gint     fd,
281                          gboolean close_fd)
282 {
283   GUnixInputStream *stream;
284
285   g_return_val_if_fail (fd != -1, NULL);
286
287   stream = g_object_new (G_TYPE_UNIX_INPUT_STREAM,
288                          "fd", fd,
289                          "close-fd", close_fd,
290                          NULL);
291
292   return G_INPUT_STREAM (stream);
293 }
294
295 /**
296  * g_unix_input_stream_set_close_fd:
297  * @stream: a #GUnixInputStream
298  * @close_fd: %TRUE to close the file descriptor when done
299  *
300  * Sets whether the file descriptor of @stream shall be closed
301  * when the stream is closed.
302  *
303  * Since: 2.20
304  */
305 void
306 g_unix_input_stream_set_close_fd (GUnixInputStream *stream,
307                                   gboolean          close_fd)
308 {
309   g_return_if_fail (G_IS_UNIX_INPUT_STREAM (stream));
310
311   close_fd = close_fd != FALSE;
312   if (stream->priv->close_fd != close_fd)
313     {
314       stream->priv->close_fd = close_fd;
315       g_object_notify (G_OBJECT (stream), "close-fd");
316     }
317 }
318
319 /**
320  * g_unix_input_stream_get_close_fd:
321  * @stream: a #GUnixInputStream
322  *
323  * Returns whether the file descriptor of @stream will be
324  * closed when the stream is closed.
325  *
326  * Return value: %TRUE if the file descriptor is closed when done
327  *
328  * Since: 2.20
329  */
330 gboolean
331 g_unix_input_stream_get_close_fd (GUnixInputStream *stream)
332 {
333   g_return_val_if_fail (G_IS_UNIX_INPUT_STREAM (stream), FALSE);
334
335   return stream->priv->close_fd;
336 }
337
338 /**
339  * g_unix_input_stream_get_fd:
340  * @stream: a #GUnixInputStream
341  *
342  * Return the UNIX file descriptor that the stream reads from.
343  *
344  * Return value: The file descriptor of @stream
345  *
346  * Since: 2.20
347  */
348 gint
349 g_unix_input_stream_get_fd (GUnixInputStream *stream)
350 {
351   g_return_val_if_fail (G_IS_UNIX_INPUT_STREAM (stream), -1);
352   
353   return stream->priv->fd;
354 }
355
356 static gssize
357 g_unix_input_stream_read (GInputStream  *stream,
358                           void          *buffer,
359                           gsize          count,
360                           GCancellable  *cancellable,
361                           GError       **error)
362 {
363   GUnixInputStream *unix_stream;
364   gssize res = -1;
365   GPollFD poll_fds[2];
366   int nfds;
367   int poll_ret;
368
369   unix_stream = G_UNIX_INPUT_STREAM (stream);
370
371   poll_fds[0].fd = unix_stream->priv->fd;
372   poll_fds[0].events = G_IO_IN;
373   if (unix_stream->priv->is_pipe_or_socket &&
374       g_cancellable_make_pollfd (cancellable, &poll_fds[1]))
375     nfds = 2;
376   else
377     nfds = 1;
378
379   while (1)
380     {
381       poll_fds[0].revents = poll_fds[1].revents = 0;
382       do
383         poll_ret = g_poll (poll_fds, nfds, -1);
384       while (poll_ret == -1 && errno == EINTR);
385
386       if (poll_ret == -1)
387         {
388           int errsv = errno;
389
390           g_set_error (error, G_IO_ERROR,
391                        g_io_error_from_errno (errsv),
392                        _("Error reading from file descriptor: %s"),
393                        g_strerror (errsv));
394           break;
395         }
396
397       if (g_cancellable_set_error_if_cancelled (cancellable, error))
398         break;
399
400       if (!poll_fds[0].revents)
401         continue;
402
403       res = read (unix_stream->priv->fd, buffer, count);
404       if (res == -1)
405         {
406           int errsv = errno;
407
408           if (errsv == EINTR || errsv == EAGAIN)
409             continue;
410
411           g_set_error (error, G_IO_ERROR,
412                        g_io_error_from_errno (errsv),
413                        _("Error reading from file descriptor: %s"),
414                        g_strerror (errsv));
415         }
416
417       break;
418     }
419
420   if (nfds == 2)
421     g_cancellable_release_fd (cancellable);
422   return res;
423 }
424
425 static gboolean
426 g_unix_input_stream_close (GInputStream  *stream,
427                            GCancellable  *cancellable,
428                            GError       **error)
429 {
430   GUnixInputStream *unix_stream;
431   int res;
432
433   unix_stream = G_UNIX_INPUT_STREAM (stream);
434
435   if (!unix_stream->priv->close_fd)
436     return TRUE;
437   
438   while (1)
439     {
440       /* This might block during the close. Doesn't seem to be a way to avoid it though. */
441       res = close (unix_stream->priv->fd);
442       if (res == -1)
443         {
444           int errsv = errno;
445
446           g_set_error (error, G_IO_ERROR,
447                        g_io_error_from_errno (errsv),
448                        _("Error closing file descriptor: %s"),
449                        g_strerror (errsv));
450         }
451       break;
452     }
453   
454   return res != -1;
455 }
456
457 typedef struct {
458   gsize count;
459   void *buffer;
460   GAsyncReadyCallback callback;
461   gpointer user_data;
462   GCancellable *cancellable;
463   GUnixInputStream *stream;
464 } ReadAsyncData;
465
466 static gboolean
467 read_async_cb (int            fd,
468                GIOCondition   condition,
469                ReadAsyncData *data)
470 {
471   GSimpleAsyncResult *simple;
472   GError *error = NULL;
473   gssize count_read;
474
475   /* We know that we can read from fd once without blocking */
476   while (1)
477     {
478       if (g_cancellable_set_error_if_cancelled (data->cancellable, &error))
479         {
480           count_read = -1;
481           break;
482         }
483       count_read = read (data->stream->priv->fd, data->buffer, data->count);
484       if (count_read == -1)
485         {
486           int errsv = errno;
487
488           if (errsv == EINTR || errsv == EAGAIN)
489             return TRUE;
490           
491           g_set_error (&error, G_IO_ERROR,
492                        g_io_error_from_errno (errsv),
493                        _("Error reading from file descriptor: %s"),
494                        g_strerror (errsv));
495         }
496       break;
497     }
498
499   simple = g_simple_async_result_new (G_OBJECT (data->stream),
500                                       data->callback,
501                                       data->user_data,
502                                       g_unix_input_stream_read_async);
503
504   g_simple_async_result_set_op_res_gssize (simple, count_read);
505
506   if (count_read == -1)
507     g_simple_async_result_take_error (simple, error);
508
509   /* Complete immediately, not in idle, since we're already in a mainloop callout */
510   g_simple_async_result_complete (simple);
511   g_object_unref (simple);
512
513   return FALSE;
514 }
515
516 static void
517 g_unix_input_stream_read_async (GInputStream        *stream,
518                                 void                *buffer,
519                                 gsize                count,
520                                 int                  io_priority,
521                                 GCancellable        *cancellable,
522                                 GAsyncReadyCallback  callback,
523                                 gpointer             user_data)
524 {
525   GSource *source;
526   GUnixInputStream *unix_stream;
527   ReadAsyncData *data;
528
529   unix_stream = G_UNIX_INPUT_STREAM (stream);
530
531   if (!unix_stream->priv->is_pipe_or_socket)
532     {
533       G_INPUT_STREAM_CLASS (g_unix_input_stream_parent_class)->
534         read_async (stream, buffer, count, io_priority,
535                     cancellable, callback, user_data);
536       return;
537     }
538
539   data = g_new0 (ReadAsyncData, 1);
540   data->count = count;
541   data->buffer = buffer;
542   data->callback = callback;
543   data->user_data = user_data;
544   data->cancellable = cancellable;
545   data->stream = unix_stream;
546
547   source = _g_fd_source_new (unix_stream->priv->fd,
548                              G_IO_IN,
549                              cancellable);
550   g_source_set_name (source, "GUnixInputStream");
551   
552   g_source_set_callback (source, (GSourceFunc)read_async_cb, data, g_free);
553   g_source_attach (source, g_main_context_get_thread_default ());
554  
555   g_source_unref (source);
556 }
557
558 static gssize
559 g_unix_input_stream_read_finish (GInputStream  *stream,
560                                  GAsyncResult  *result,
561                                  GError       **error)
562 {
563   GUnixInputStream *unix_stream = G_UNIX_INPUT_STREAM (stream);
564   GSimpleAsyncResult *simple;
565   gssize nread;
566
567   if (!unix_stream->priv->is_pipe_or_socket)
568     {
569       return G_INPUT_STREAM_CLASS (g_unix_input_stream_parent_class)->
570         read_finish (stream, result, error);
571     }
572
573   simple = G_SIMPLE_ASYNC_RESULT (result);
574   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_unix_input_stream_read_async);
575   
576   nread = g_simple_async_result_get_op_res_gssize (simple);
577   return nread;
578 }
579
580 static void
581 g_unix_input_stream_skip_async (GInputStream        *stream,
582                                 gsize                count,
583                                 int                  io_priority,
584                                 GCancellable        *cancellable,
585                                 GAsyncReadyCallback  callback,
586                                 gpointer             data)
587 {
588   g_warn_if_reached ();
589   /* TODO: Not implemented */
590 }
591
592 static gssize
593 g_unix_input_stream_skip_finish  (GInputStream  *stream,
594                                   GAsyncResult  *result,
595                                   GError       **error)
596 {
597   g_warn_if_reached ();
598   return 0;
599   /* TODO: Not implemented */
600 }
601
602
603 typedef struct {
604   GInputStream *stream;
605   GAsyncReadyCallback callback;
606   gpointer user_data;
607 } CloseAsyncData;
608
609 static void
610 close_async_data_free (gpointer _data)
611 {
612   CloseAsyncData *data = _data;
613
614   g_free (data);
615 }
616
617 static gboolean
618 close_async_cb (CloseAsyncData *data)
619 {
620   GUnixInputStream *unix_stream;
621   GSimpleAsyncResult *simple;
622   GError *error = NULL;
623   gboolean result;
624   int res;
625
626   unix_stream = G_UNIX_INPUT_STREAM (data->stream);
627
628   if (!unix_stream->priv->close_fd)
629     {
630       result = TRUE;
631       goto out;
632     }
633   
634   while (1)
635     {
636       res = close (unix_stream->priv->fd);
637       if (res == -1)
638         {
639           int errsv = errno;
640
641           g_set_error (&error, G_IO_ERROR,
642                        g_io_error_from_errno (errsv),
643                        _("Error closing file descriptor: %s"),
644                        g_strerror (errsv));
645         }
646       break;
647     }
648   
649   result = res != -1;
650
651  out:
652   simple = g_simple_async_result_new (G_OBJECT (data->stream),
653                                       data->callback,
654                                       data->user_data,
655                                       g_unix_input_stream_close_async);
656
657   if (!result)
658     g_simple_async_result_take_error (simple, error);
659
660   /* Complete immediately, not in idle, since we're already in a mainloop callout */
661   g_simple_async_result_complete (simple);
662   g_object_unref (simple);
663   
664   return FALSE;
665 }
666
667 static void
668 g_unix_input_stream_close_async (GInputStream        *stream,
669                                  int                  io_priority,
670                                  GCancellable        *cancellable,
671                                  GAsyncReadyCallback  callback,
672                                  gpointer             user_data)
673 {
674   GSource *idle;
675   CloseAsyncData *data;
676
677   data = g_new0 (CloseAsyncData, 1);
678
679   data->stream = stream;
680   data->callback = callback;
681   data->user_data = user_data;
682   
683   idle = g_idle_source_new ();
684   g_source_set_callback (idle, (GSourceFunc)close_async_cb, data, close_async_data_free);
685   g_source_attach (idle, g_main_context_get_thread_default ());
686   g_source_unref (idle);
687 }
688
689 static gboolean
690 g_unix_input_stream_close_finish (GInputStream  *stream,
691                                   GAsyncResult  *result,
692                                   GError       **error)
693 {
694   /* Failures handled in generic close_finish code */
695   return TRUE;
696 }
697
698 static gboolean
699 g_unix_input_stream_pollable_is_readable (GPollableInputStream *stream)
700 {
701   GUnixInputStream *unix_stream = G_UNIX_INPUT_STREAM (stream);
702   GPollFD poll_fd;
703   gint result;
704
705   poll_fd.fd = unix_stream->priv->fd;
706   poll_fd.events = G_IO_IN;
707
708   do
709     result = g_poll (&poll_fd, 1, 0);
710   while (result == -1 && errno == EINTR);
711
712   return poll_fd.revents != 0;
713 }
714
715 static GSource *
716 g_unix_input_stream_pollable_create_source (GPollableInputStream *stream,
717                                             GCancellable         *cancellable)
718 {
719   GUnixInputStream *unix_stream = G_UNIX_INPUT_STREAM (stream);
720   GSource *inner_source, *pollable_source;
721
722   pollable_source = g_pollable_source_new (G_OBJECT (stream));
723
724   inner_source = _g_fd_source_new (unix_stream->priv->fd, G_IO_IN, cancellable);
725   g_source_set_dummy_callback (inner_source);
726   g_source_add_child_source (pollable_source, inner_source);
727   g_source_unref (inner_source);
728
729   return pollable_source;
730 }