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