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