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