gio: Add private API to create win32 streams from fds
[platform/upstream/glib.git] / gio / gwin32inputstream.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright (C) 2006-2010 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  * Author: Tor Lillqvist <tml@iki.fi>
22  */
23
24 #include "config.h"
25
26 #include <windows.h>
27
28 #include <io.h>
29
30 #include <glib.h>
31 #include "gioerror.h"
32 #include "gsimpleasyncresult.h"
33 #include "gwin32inputstream.h"
34 #include "gcancellable.h"
35 #include "gasynchelper.h"
36 #include "glibintl.h"
37
38
39 /**
40  * SECTION:gwin32inputstream
41  * @short_description: Streaming input operations for Windows file handles
42  * @include: gio/gwin32inputstream.h
43  * @see_also: #GInputStream
44  *
45  * #GWin32InputStream implements #GInputStream for reading from a
46  * Windows file handle.
47  *
48  * Note that <filename>&lt;gio/gwin32inputstream.h&gt;</filename> belongs
49  * to the Windows-specific GIO interfaces, thus you have to use the
50  * <filename>gio-windows-2.0.pc</filename> pkg-config file when using it.
51  */
52
53 enum {
54   PROP_0,
55   PROP_HANDLE,
56   PROP_CLOSE_HANDLE
57 };
58
59 G_DEFINE_TYPE (GWin32InputStream, g_win32_input_stream, G_TYPE_INPUT_STREAM);
60
61 struct _GWin32InputStreamPrivate {
62   HANDLE handle;
63   gboolean close_handle;
64   gint fd;
65 };
66
67 static void     g_win32_input_stream_set_property (GObject              *object,
68                                                    guint                 prop_id,
69                                                    const GValue         *value,
70                                                    GParamSpec           *pspec);
71 static void     g_win32_input_stream_get_property (GObject              *object,
72                                                    guint                 prop_id,
73                                                    GValue               *value,
74                                                    GParamSpec           *pspec);
75 static gssize   g_win32_input_stream_read         (GInputStream         *stream,
76                                                    void                 *buffer,
77                                                    gsize                 count,
78                                                    GCancellable         *cancellable,
79                                                    GError              **error);
80 static gboolean g_win32_input_stream_close        (GInputStream         *stream,
81                                                    GCancellable         *cancellable,
82                                                    GError              **error);
83
84 static void
85 g_win32_input_stream_finalize (GObject *object)
86 {
87   G_OBJECT_CLASS (g_win32_input_stream_parent_class)->finalize (object);
88 }
89
90 static void
91 g_win32_input_stream_class_init (GWin32InputStreamClass *klass)
92 {
93   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
94   GInputStreamClass *stream_class = G_INPUT_STREAM_CLASS (klass);
95
96   g_type_class_add_private (klass, sizeof (GWin32InputStreamPrivate));
97
98   gobject_class->get_property = g_win32_input_stream_get_property;
99   gobject_class->set_property = g_win32_input_stream_set_property;
100   gobject_class->finalize = g_win32_input_stream_finalize;
101
102   stream_class->read_fn = g_win32_input_stream_read;
103   stream_class->close_fn = g_win32_input_stream_close;
104
105   /**
106    * GWin32InputStream:handle:
107    *
108    * The handle that the stream reads from.
109    *
110    * Since: 2.26
111    */
112   g_object_class_install_property (gobject_class,
113                                    PROP_HANDLE,
114                                    g_param_spec_pointer ("handle",
115                                                          P_("File handle"),
116                                                          P_("The file handle to read from"),
117                                                          G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
118
119   /**
120    * GWin32InputStream:close-handle:
121    *
122    * Whether to close the file handle when the stream is closed.
123    *
124    * Since: 2.26
125    */
126   g_object_class_install_property (gobject_class,
127                                    PROP_CLOSE_HANDLE,
128                                    g_param_spec_boolean ("close-handle",
129                                                          P_("Close file handle"),
130                                                          P_("Whether to close the file handle when the stream is closed"),
131                                                          TRUE,
132                                                          G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
133 }
134
135 static void
136 g_win32_input_stream_set_property (GObject         *object,
137                                    guint            prop_id,
138                                    const GValue    *value,
139                                    GParamSpec      *pspec)
140 {
141   GWin32InputStream *win32_stream;
142
143   win32_stream = G_WIN32_INPUT_STREAM (object);
144
145   switch (prop_id)
146     {
147     case PROP_HANDLE:
148       win32_stream->priv->handle = g_value_get_pointer (value);
149       break;
150     case PROP_CLOSE_HANDLE:
151       win32_stream->priv->close_handle = g_value_get_boolean (value);
152       break;
153     default:
154       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
155       break;
156     }
157 }
158
159 static void
160 g_win32_input_stream_get_property (GObject    *object,
161                                    guint       prop_id,
162                                    GValue     *value,
163                                    GParamSpec *pspec)
164 {
165   GWin32InputStream *win32_stream;
166
167   win32_stream = G_WIN32_INPUT_STREAM (object);
168
169   switch (prop_id)
170     {
171     case PROP_HANDLE:
172       g_value_set_pointer (value, win32_stream->priv->handle);
173       break;
174     case PROP_CLOSE_HANDLE:
175       g_value_set_boolean (value, win32_stream->priv->close_handle);
176       break;
177     default:
178       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
179     }
180 }
181
182 static void
183 g_win32_input_stream_init (GWin32InputStream *win32_stream)
184 {
185   win32_stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (win32_stream,
186                                                     G_TYPE_WIN32_INPUT_STREAM,
187                                                     GWin32InputStreamPrivate);
188
189   win32_stream->priv->handle = NULL;
190   win32_stream->priv->close_handle = TRUE;
191   win32_stream->priv->fd = -1;
192 }
193
194 /**
195  * g_win32_input_stream_new:
196  * @handle: a Win32 file handle
197  * @close_handle: %TRUE to close the handle when done
198  *
199  * Creates a new #GWin32InputStream for the given @handle.
200  *
201  * If @close_handle is %TRUE, the handle will be closed
202  * when the stream is closed.
203  *
204  * Note that "handle" here means a Win32 HANDLE, not a "file descriptor"
205  * as used in the Windows C libraries.
206  *
207  * Returns: a new #GWin32InputStream
208  **/
209 GInputStream *
210 g_win32_input_stream_new (void     *handle,
211                           gboolean close_handle)
212 {
213   GWin32InputStream *stream;
214
215   g_return_val_if_fail (handle != NULL, NULL);
216
217   stream = g_object_new (G_TYPE_WIN32_INPUT_STREAM,
218                          "handle", handle,
219                          "close-handle", close_handle,
220                          NULL);
221
222   return G_INPUT_STREAM (stream);
223 }
224
225 /**
226  * g_win32_input_stream_set_close_handle:
227  * @stream: a #GWin32InputStream
228  * @close_handle: %TRUE to close the handle when done
229  *
230  * Sets whether the handle of @stream shall be closed
231  * when the stream is closed.
232  *
233  * Since: 2.26
234  */
235 void
236 g_win32_input_stream_set_close_handle (GWin32InputStream *stream,
237                                        gboolean          close_handle)
238 {
239   g_return_if_fail (G_IS_WIN32_INPUT_STREAM (stream));
240
241   close_handle = close_handle != FALSE;
242   if (stream->priv->close_handle != close_handle)
243     {
244       stream->priv->close_handle = close_handle;
245       g_object_notify (G_OBJECT (stream), "close-handle");
246     }
247 }
248
249 /**
250  * g_win32_input_stream_get_close_handle:
251  * @stream: a #GWin32InputStream
252  *
253  * Returns whether the handle of @stream will be
254  * closed when the stream is closed.
255  *
256  * Return value: %TRUE if the handle is closed when done
257  *
258  * Since: 2.26
259  */
260 gboolean
261 g_win32_input_stream_get_close_handle (GWin32InputStream *stream)
262 {
263   g_return_val_if_fail (G_IS_WIN32_INPUT_STREAM (stream), FALSE);
264
265   return stream->priv->close_handle;
266 }
267
268 /**
269  * g_win32_input_stream_get_handle:
270  * @stream: a #GWin32InputStream
271  *
272  * Return the Windows file handle that the stream reads from.
273  *
274  * Return value: The file handle of @stream
275  *
276  * Since: 2.26
277  */
278 void *
279 g_win32_input_stream_get_handle (GWin32InputStream *stream)
280 {
281   g_return_val_if_fail (G_IS_WIN32_INPUT_STREAM (stream), NULL);
282
283   return stream->priv->handle;
284 }
285
286 static gssize
287 g_win32_input_stream_read (GInputStream  *stream,
288                            void          *buffer,
289                            gsize          count,
290                            GCancellable  *cancellable,
291                            GError       **error)
292 {
293   GWin32InputStream *win32_stream;
294   BOOL res;
295   DWORD nbytes, nread;
296   OVERLAPPED overlap = { 0, };
297   gssize retval = -1;
298
299   win32_stream = G_WIN32_INPUT_STREAM (stream);
300
301   if (g_cancellable_set_error_if_cancelled (cancellable, error))
302     return -1;
303
304   if (count > G_MAXINT)
305     nbytes = G_MAXINT;
306   else
307     nbytes = count;
308
309   overlap.hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
310   g_return_val_if_fail (overlap.hEvent != NULL, -1);
311
312   res = ReadFile (win32_stream->priv->handle, buffer, nbytes, &nread, &overlap);
313   if (res)
314     retval = nread;
315   else
316     {
317       int errsv = GetLastError ();
318
319       if (errsv == ERROR_IO_PENDING &&
320           _g_win32_overlap_wait_result (win32_stream->priv->handle,
321                                         &overlap, &nread, cancellable))
322         {
323           retval = nread;
324           goto end;
325         }
326
327       if (g_cancellable_set_error_if_cancelled (cancellable, error))
328         goto end;
329
330       errsv = GetLastError ();
331       if (errsv == ERROR_MORE_DATA)
332         {
333           /* If a named pipe is being read in message mode and the
334            * next message is longer than the nNumberOfBytesToRead
335            * parameter specifies, ReadFile returns FALSE and
336            * GetLastError returns ERROR_MORE_DATA */
337           retval = nread;
338           goto end;
339         }
340       else if (errsv == ERROR_HANDLE_EOF ||
341                errsv == ERROR_BROKEN_PIPE)
342         {
343           /* TODO: the other end of a pipe may call the WriteFile
344            * function with nNumberOfBytesToWrite set to zero. In this
345            * case, it's not possible for the caller to know if it's
346            * broken pipe or a read of 0. Perhaps we should add a
347            * is_broken flag for this win32 case.. */
348           retval = 0;
349         }
350       else
351         {
352           gchar *emsg;
353
354           emsg = g_win32_error_message (errsv);
355           g_set_error (error, G_IO_ERROR,
356                        g_io_error_from_win32_error (errsv),
357                        _("Error reading from handle: %s"),
358                        emsg);
359           g_free (emsg);
360         }
361     }
362
363 end:
364   CloseHandle (overlap.hEvent);
365   return retval;
366 }
367
368 static gboolean
369 g_win32_input_stream_close (GInputStream  *stream,
370                            GCancellable  *cancellable,
371                            GError       **error)
372 {
373   GWin32InputStream *win32_stream;
374   BOOL res;
375
376   win32_stream = G_WIN32_INPUT_STREAM (stream);
377
378   if (!win32_stream->priv->close_handle)
379     return TRUE;
380
381   if (win32_stream->priv->fd != -1)
382     {
383       int errsv = errno;
384       if (close (win32_stream->priv->fd) < 0)
385         {
386           g_set_error_literal (error, G_IO_ERROR,
387                                g_io_error_from_errno (errsv),
388                                g_strerror (errsv));
389           return FALSE;
390         }
391     }
392   else
393     {
394       res = CloseHandle (win32_stream->priv->handle);
395       if (!res)
396         {
397           int errsv = GetLastError ();
398           gchar *emsg = g_win32_error_message (errsv);
399
400           g_set_error (error, G_IO_ERROR,
401                        g_io_error_from_win32_error (errsv),
402                        _("Error closing handle: %s"),
403                        emsg);
404           g_free (emsg);
405           return FALSE;
406         }
407     }
408
409   return TRUE;
410 }
411
412 GInputStream *
413 g_win32_input_stream_new_from_fd (gint      fd,
414                                   gboolean  close_fd)
415 {
416   GWin32InputStream *win32_stream;
417
418   win32_stream = G_WIN32_INPUT_STREAM (g_win32_input_stream_new ((HANDLE) _get_osfhandle (fd), close_fd));
419   win32_stream->priv->fd = fd;
420
421   return (GInputStream*)win32_stream;
422 }