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