gio: Use the new private instance data declaration
[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 "gfiledescriptorbased.h"
40 #include "glibintl.h"
41
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 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/gunixoutputstream.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 struct _GUnixOutputStreamPrivate {
67   int fd;
68   guint close_fd : 1;
69   guint is_pipe_or_socket : 1;
70 };
71
72 static void g_unix_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface);
73 static void g_unix_output_stream_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface);
74
75 G_DEFINE_TYPE_WITH_CODE (GUnixOutputStream, g_unix_output_stream, G_TYPE_OUTPUT_STREAM,
76                          G_ADD_PRIVATE (GUnixOutputStream)
77                          G_IMPLEMENT_INTERFACE (G_TYPE_POLLABLE_OUTPUT_STREAM,
78                                                 g_unix_output_stream_pollable_iface_init)
79                          G_IMPLEMENT_INTERFACE (G_TYPE_FILE_DESCRIPTOR_BASED,
80                                                 g_unix_output_stream_file_descriptor_based_iface_init)
81                          )
82
83 static void     g_unix_output_stream_set_property (GObject              *object,
84                                                    guint                 prop_id,
85                                                    const GValue         *value,
86                                                    GParamSpec           *pspec);
87 static void     g_unix_output_stream_get_property (GObject              *object,
88                                                    guint                 prop_id,
89                                                    GValue               *value,
90                                                    GParamSpec           *pspec);
91 static gssize   g_unix_output_stream_write        (GOutputStream        *stream,
92                                                    const void           *buffer,
93                                                    gsize                 count,
94                                                    GCancellable         *cancellable,
95                                                    GError              **error);
96 static gboolean g_unix_output_stream_close        (GOutputStream        *stream,
97                                                    GCancellable         *cancellable,
98                                                    GError              **error);
99 static void     g_unix_output_stream_close_async  (GOutputStream        *stream,
100                                                    int                   io_priority,
101                                                    GCancellable         *cancellable,
102                                                    GAsyncReadyCallback   callback,
103                                                    gpointer              data);
104 static gboolean g_unix_output_stream_close_finish (GOutputStream        *stream,
105                                                    GAsyncResult         *result,
106                                                    GError              **error);
107
108 static gboolean g_unix_output_stream_pollable_can_poll      (GPollableOutputStream *stream);
109 static gboolean g_unix_output_stream_pollable_is_writable   (GPollableOutputStream *stream);
110 static GSource *g_unix_output_stream_pollable_create_source (GPollableOutputStream *stream,
111                                                              GCancellable         *cancellable);
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   gobject_class->get_property = g_unix_output_stream_get_property;
120   gobject_class->set_property = g_unix_output_stream_set_property;
121
122   stream_class->write_fn = g_unix_output_stream_write;
123   stream_class->close_fn = g_unix_output_stream_close;
124   stream_class->close_async = g_unix_output_stream_close_async;
125   stream_class->close_finish = g_unix_output_stream_close_finish;
126
127    /**
128    * GUnixOutputStream:fd:
129    *
130    * The file descriptor that the stream writes to.
131    *
132    * Since: 2.20
133    */
134   g_object_class_install_property (gobject_class,
135                                    PROP_FD,
136                                    g_param_spec_int ("fd",
137                                                      P_("File descriptor"),
138                                                      P_("The file descriptor to write to"),
139                                                      G_MININT, G_MAXINT, -1,
140                                                      G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
141
142   /**
143    * GUnixOutputStream:close-fd:
144    *
145    * Whether to close the file descriptor when the stream is closed.
146    *
147    * Since: 2.20
148    */
149   g_object_class_install_property (gobject_class,
150                                    PROP_CLOSE_FD,
151                                    g_param_spec_boolean ("close-fd",
152                                                          P_("Close file descriptor"),
153                                                          P_("Whether to close the file descriptor when the stream is closed"),
154                                                          TRUE,
155                                                          G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
156 }
157
158 static void
159 g_unix_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface)
160 {
161   iface->can_poll = g_unix_output_stream_pollable_can_poll;
162   iface->is_writable = g_unix_output_stream_pollable_is_writable;
163   iface->create_source = g_unix_output_stream_pollable_create_source;
164 }
165
166 static void
167 g_unix_output_stream_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface)
168 {
169   iface->get_fd = (int (*) (GFileDescriptorBased *))g_unix_output_stream_get_fd;
170 }
171
172 static void
173 g_unix_output_stream_set_property (GObject         *object,
174                                    guint            prop_id,
175                                    const GValue    *value,
176                                    GParamSpec      *pspec)
177 {
178   GUnixOutputStream *unix_stream;
179
180   unix_stream = G_UNIX_OUTPUT_STREAM (object);
181
182   switch (prop_id)
183     {
184     case PROP_FD:
185       unix_stream->priv->fd = g_value_get_int (value);
186       if (lseek (unix_stream->priv->fd, 0, SEEK_CUR) == -1 && errno == ESPIPE)
187         unix_stream->priv->is_pipe_or_socket = TRUE;
188       else
189         unix_stream->priv->is_pipe_or_socket = FALSE;
190       break;
191     case PROP_CLOSE_FD:
192       unix_stream->priv->close_fd = g_value_get_boolean (value);
193       break;
194     default:
195       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
196       break;
197     }
198 }
199
200 static void
201 g_unix_output_stream_get_property (GObject    *object,
202                                    guint       prop_id,
203                                    GValue     *value,
204                                    GParamSpec *pspec)
205 {
206   GUnixOutputStream *unix_stream;
207
208   unix_stream = G_UNIX_OUTPUT_STREAM (object);
209
210   switch (prop_id)
211     {
212     case PROP_FD:
213       g_value_set_int (value, unix_stream->priv->fd);
214       break;
215     case PROP_CLOSE_FD:
216       g_value_set_boolean (value, unix_stream->priv->close_fd);
217       break;
218     default:
219       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
220     }
221 }
222
223 static void
224 g_unix_output_stream_init (GUnixOutputStream *unix_stream)
225 {
226   unix_stream->priv = g_unix_output_stream_get_private (unix_stream);
227   unix_stream->priv->fd = -1;
228   unix_stream->priv->close_fd = TRUE;
229 }
230
231 /**
232  * g_unix_output_stream_new:
233  * @fd: a UNIX file descriptor
234  * @close_fd: %TRUE to close the file descriptor when done
235  * 
236  * Creates a new #GUnixOutputStream for the given @fd. 
237  * 
238  * If @close_fd, is %TRUE, the file descriptor will be closed when 
239  * the output stream is destroyed.
240  * 
241  * Returns: a new #GOutputStream
242  **/
243 GOutputStream *
244 g_unix_output_stream_new (gint     fd,
245                           gboolean close_fd)
246 {
247   GUnixOutputStream *stream;
248
249   g_return_val_if_fail (fd != -1, NULL);
250
251   stream = g_object_new (G_TYPE_UNIX_OUTPUT_STREAM,
252                          "fd", fd,
253                          "close-fd", close_fd,
254                          NULL);
255   
256   return G_OUTPUT_STREAM (stream);
257 }
258
259 /**
260  * g_unix_output_stream_set_close_fd:
261  * @stream: a #GUnixOutputStream
262  * @close_fd: %TRUE to close the file descriptor when done
263  *
264  * Sets whether the file descriptor of @stream shall be closed
265  * when the stream is closed.
266  *
267  * Since: 2.20
268  */
269 void
270 g_unix_output_stream_set_close_fd (GUnixOutputStream *stream,
271                                    gboolean           close_fd)
272 {
273   g_return_if_fail (G_IS_UNIX_OUTPUT_STREAM (stream));
274
275   close_fd = close_fd != FALSE;
276   if (stream->priv->close_fd != close_fd)
277     {
278       stream->priv->close_fd = close_fd;
279       g_object_notify (G_OBJECT (stream), "close-fd");
280     }
281 }
282
283 /**
284  * g_unix_output_stream_get_close_fd:
285  * @stream: a #GUnixOutputStream
286  *
287  * Returns whether the file descriptor of @stream will be
288  * closed when the stream is closed.
289  *
290  * Return value: %TRUE if the file descriptor is closed when done
291  *
292  * Since: 2.20
293  */
294 gboolean
295 g_unix_output_stream_get_close_fd (GUnixOutputStream *stream)
296 {
297   g_return_val_if_fail (G_IS_UNIX_OUTPUT_STREAM (stream), FALSE);
298
299   return stream->priv->close_fd;
300 }
301
302 /**
303  * g_unix_output_stream_get_fd:
304  * @stream: a #GUnixOutputStream
305  *
306  * Return the UNIX file descriptor that the stream writes to.
307  *
308  * Return value: The file descriptor of @stream
309  *
310  * Since: 2.20
311  */
312 gint
313 g_unix_output_stream_get_fd (GUnixOutputStream *stream)
314 {
315   g_return_val_if_fail (G_IS_UNIX_OUTPUT_STREAM (stream), -1);
316
317   return stream->priv->fd;
318 }
319
320 static gssize
321 g_unix_output_stream_write (GOutputStream  *stream,
322                             const void     *buffer,
323                             gsize           count,
324                             GCancellable   *cancellable,
325                             GError        **error)
326 {
327   GUnixOutputStream *unix_stream;
328   gssize res = -1;
329   GPollFD poll_fds[2];
330   int nfds;
331   int poll_ret;
332
333   unix_stream = G_UNIX_OUTPUT_STREAM (stream);
334
335   poll_fds[0].fd = unix_stream->priv->fd;
336   poll_fds[0].events = G_IO_OUT;
337
338   if (unix_stream->priv->is_pipe_or_socket &&
339       g_cancellable_make_pollfd (cancellable, &poll_fds[1]))
340     nfds = 2;
341   else
342     nfds = 1;
343
344   while (1)
345     {
346       poll_fds[0].revents = poll_fds[1].revents = 0;
347       do
348         poll_ret = g_poll (poll_fds, nfds, -1);
349       while (poll_ret == -1 && errno == EINTR);
350
351       if (poll_ret == -1)
352         {
353           int errsv = errno;
354
355           g_set_error (error, G_IO_ERROR,
356                        g_io_error_from_errno (errsv),
357                        _("Error writing to file descriptor: %s"),
358                        g_strerror (errsv));
359           break;
360         }
361
362       if (g_cancellable_set_error_if_cancelled (cancellable, error))
363         break;
364
365       if (!poll_fds[0].revents)
366         continue;
367
368       res = write (unix_stream->priv->fd, buffer, count);
369       if (res == -1)
370         {
371           int errsv = errno;
372
373           if (errsv == EINTR || errsv == EAGAIN)
374             continue;
375
376           g_set_error (error, G_IO_ERROR,
377                        g_io_error_from_errno (errsv),
378                        _("Error writing to file descriptor: %s"),
379                        g_strerror (errsv));
380         }
381
382       break;
383     }
384
385   if (nfds == 2)
386     g_cancellable_release_fd (cancellable);
387   return res;
388 }
389
390 static gboolean
391 g_unix_output_stream_close (GOutputStream  *stream,
392                             GCancellable   *cancellable,
393                             GError        **error)
394 {
395   GUnixOutputStream *unix_stream;
396   int res;
397
398   unix_stream = G_UNIX_OUTPUT_STREAM (stream);
399
400   if (!unix_stream->priv->close_fd)
401     return TRUE;
402   
403   /* This might block during the close. Doesn't seem to be a way to avoid it though. */
404   res = close (unix_stream->priv->fd);
405   if (res == -1)
406     {
407       int errsv = errno;
408
409       g_set_error (error, G_IO_ERROR,
410                    g_io_error_from_errno (errsv),
411                    _("Error closing file descriptor: %s"),
412                    g_strerror (errsv));
413     }
414
415   return res != -1;
416 }
417
418 static void
419 g_unix_output_stream_close_async (GOutputStream       *stream,
420                                   int                  io_priority,
421                                   GCancellable        *cancellable,
422                                   GAsyncReadyCallback  callback,
423                                   gpointer             user_data)
424 {
425   GTask *task;
426   GError *error = NULL;
427
428   task = g_task_new (stream, cancellable, callback, user_data);
429   g_task_set_priority (task, io_priority);
430
431   if (g_unix_output_stream_close (stream, cancellable, &error))
432     g_task_return_boolean (task, TRUE);
433   else
434     g_task_return_error (task, error);
435   g_object_unref (task);
436 }
437
438 static gboolean
439 g_unix_output_stream_close_finish (GOutputStream  *stream,
440                                    GAsyncResult   *result,
441                                    GError        **error)
442 {
443   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
444
445   return g_task_propagate_boolean (G_TASK (result), error);
446 }
447
448 static gboolean
449 g_unix_output_stream_pollable_can_poll (GPollableOutputStream *stream)
450 {
451   return G_UNIX_OUTPUT_STREAM (stream)->priv->is_pipe_or_socket;
452 }
453
454 static gboolean
455 g_unix_output_stream_pollable_is_writable (GPollableOutputStream *stream)
456 {
457   GUnixOutputStream *unix_stream = G_UNIX_OUTPUT_STREAM (stream);
458   GPollFD poll_fd;
459   gint result;
460
461   poll_fd.fd = unix_stream->priv->fd;
462   poll_fd.events = G_IO_OUT;
463   poll_fd.revents = 0;
464
465   do
466     result = g_poll (&poll_fd, 1, 0);
467   while (result == -1 && errno == EINTR);
468
469   return poll_fd.revents != 0;
470 }
471
472 static GSource *
473 g_unix_output_stream_pollable_create_source (GPollableOutputStream *stream,
474                                              GCancellable          *cancellable)
475 {
476   GUnixOutputStream *unix_stream = G_UNIX_OUTPUT_STREAM (stream);
477   GSource *inner_source, *pollable_source;
478
479   pollable_source = g_pollable_source_new (G_OBJECT (stream));
480
481   inner_source = _g_fd_source_new (unix_stream->priv->fd, G_IO_OUT, cancellable);
482   g_source_set_dummy_callback (inner_source);
483   g_source_add_child_source (pollable_source, inner_source);
484   g_source_unref (inner_source);
485
486   return pollable_source;
487 }