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 struct _GWin32InputStreamPrivate {
60   HANDLE handle;
61   gboolean close_handle;
62   gint fd;
63 };
64
65 G_DEFINE_TYPE_WITH_PRIVATE (GWin32InputStream, g_win32_input_stream, G_TYPE_INPUT_STREAM)
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_class_init (GWin32InputStreamClass *klass)
86 {
87   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
88   GInputStreamClass *stream_class = G_INPUT_STREAM_CLASS (klass);
89
90   gobject_class->get_property = g_win32_input_stream_get_property;
91   gobject_class->set_property = g_win32_input_stream_set_property;
92
93   stream_class->read_fn = g_win32_input_stream_read;
94   stream_class->close_fn = g_win32_input_stream_close;
95
96   /**
97    * GWin32InputStream:handle:
98    *
99    * The handle that the stream reads from.
100    *
101    * Since: 2.26
102    */
103   g_object_class_install_property (gobject_class,
104                                    PROP_HANDLE,
105                                    g_param_spec_pointer ("handle",
106                                                          P_("File handle"),
107                                                          P_("The file handle to read from"),
108                                                          G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
109
110   /**
111    * GWin32InputStream:close-handle:
112    *
113    * Whether to close the file handle when the stream is closed.
114    *
115    * Since: 2.26
116    */
117   g_object_class_install_property (gobject_class,
118                                    PROP_CLOSE_HANDLE,
119                                    g_param_spec_boolean ("close-handle",
120                                                          P_("Close file handle"),
121                                                          P_("Whether to close the file handle when the stream is closed"),
122                                                          TRUE,
123                                                          G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
124 }
125
126 static void
127 g_win32_input_stream_set_property (GObject         *object,
128                                    guint            prop_id,
129                                    const GValue    *value,
130                                    GParamSpec      *pspec)
131 {
132   GWin32InputStream *win32_stream;
133
134   win32_stream = G_WIN32_INPUT_STREAM (object);
135
136   switch (prop_id)
137     {
138     case PROP_HANDLE:
139       win32_stream->priv->handle = g_value_get_pointer (value);
140       break;
141     case PROP_CLOSE_HANDLE:
142       win32_stream->priv->close_handle = g_value_get_boolean (value);
143       break;
144     default:
145       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
146       break;
147     }
148 }
149
150 static void
151 g_win32_input_stream_get_property (GObject    *object,
152                                    guint       prop_id,
153                                    GValue     *value,
154                                    GParamSpec *pspec)
155 {
156   GWin32InputStream *win32_stream;
157
158   win32_stream = G_WIN32_INPUT_STREAM (object);
159
160   switch (prop_id)
161     {
162     case PROP_HANDLE:
163       g_value_set_pointer (value, win32_stream->priv->handle);
164       break;
165     case PROP_CLOSE_HANDLE:
166       g_value_set_boolean (value, win32_stream->priv->close_handle);
167       break;
168     default:
169       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
170     }
171 }
172
173 static void
174 g_win32_input_stream_init (GWin32InputStream *win32_stream)
175 {
176   win32_stream->priv = g_win32_input_stream_get_instance_private (win32_stream);
177   win32_stream->priv->handle = NULL;
178   win32_stream->priv->close_handle = TRUE;
179   win32_stream->priv->fd = -1;
180 }
181
182 /**
183  * g_win32_input_stream_new:
184  * @handle: a Win32 file handle
185  * @close_handle: %TRUE to close the handle when done
186  *
187  * Creates a new #GWin32InputStream for the given @handle.
188  *
189  * If @close_handle is %TRUE, the handle will be closed
190  * when the stream is closed.
191  *
192  * Note that "handle" here means a Win32 HANDLE, not a "file descriptor"
193  * as used in the Windows C libraries.
194  *
195  * Returns: a new #GWin32InputStream
196  **/
197 GInputStream *
198 g_win32_input_stream_new (void     *handle,
199                           gboolean close_handle)
200 {
201   GWin32InputStream *stream;
202
203   g_return_val_if_fail (handle != NULL, NULL);
204
205   stream = g_object_new (G_TYPE_WIN32_INPUT_STREAM,
206                          "handle", handle,
207                          "close-handle", close_handle,
208                          NULL);
209
210   return G_INPUT_STREAM (stream);
211 }
212
213 /**
214  * g_win32_input_stream_set_close_handle:
215  * @stream: a #GWin32InputStream
216  * @close_handle: %TRUE to close the handle when done
217  *
218  * Sets whether the handle of @stream shall be closed
219  * when the stream is closed.
220  *
221  * Since: 2.26
222  */
223 void
224 g_win32_input_stream_set_close_handle (GWin32InputStream *stream,
225                                        gboolean          close_handle)
226 {
227   g_return_if_fail (G_IS_WIN32_INPUT_STREAM (stream));
228
229   close_handle = close_handle != FALSE;
230   if (stream->priv->close_handle != close_handle)
231     {
232       stream->priv->close_handle = close_handle;
233       g_object_notify (G_OBJECT (stream), "close-handle");
234     }
235 }
236
237 /**
238  * g_win32_input_stream_get_close_handle:
239  * @stream: a #GWin32InputStream
240  *
241  * Returns whether the handle of @stream will be
242  * closed when the stream is closed.
243  *
244  * Return value: %TRUE if the handle is closed when done
245  *
246  * Since: 2.26
247  */
248 gboolean
249 g_win32_input_stream_get_close_handle (GWin32InputStream *stream)
250 {
251   g_return_val_if_fail (G_IS_WIN32_INPUT_STREAM (stream), FALSE);
252
253   return stream->priv->close_handle;
254 }
255
256 /**
257  * g_win32_input_stream_get_handle:
258  * @stream: a #GWin32InputStream
259  *
260  * Return the Windows file handle that the stream reads from.
261  *
262  * Return value: The file handle of @stream
263  *
264  * Since: 2.26
265  */
266 void *
267 g_win32_input_stream_get_handle (GWin32InputStream *stream)
268 {
269   g_return_val_if_fail (G_IS_WIN32_INPUT_STREAM (stream), NULL);
270
271   return stream->priv->handle;
272 }
273
274 static gssize
275 g_win32_input_stream_read (GInputStream  *stream,
276                            void          *buffer,
277                            gsize          count,
278                            GCancellable  *cancellable,
279                            GError       **error)
280 {
281   GWin32InputStream *win32_stream;
282   BOOL res;
283   DWORD nbytes, nread;
284   OVERLAPPED overlap = { 0, };
285   gssize retval = -1;
286
287   win32_stream = G_WIN32_INPUT_STREAM (stream);
288
289   if (g_cancellable_set_error_if_cancelled (cancellable, error))
290     return -1;
291
292   if (count > G_MAXINT)
293     nbytes = G_MAXINT;
294   else
295     nbytes = count;
296
297   overlap.hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
298   g_return_val_if_fail (overlap.hEvent != NULL, -1);
299
300   res = ReadFile (win32_stream->priv->handle, buffer, nbytes, &nread, &overlap);
301   if (res)
302     retval = nread;
303   else
304     {
305       int errsv = GetLastError ();
306
307       if (errsv == ERROR_IO_PENDING &&
308           _g_win32_overlap_wait_result (win32_stream->priv->handle,
309                                         &overlap, &nread, cancellable))
310         {
311           retval = nread;
312           goto end;
313         }
314
315       if (g_cancellable_set_error_if_cancelled (cancellable, error))
316         goto end;
317
318       errsv = GetLastError ();
319       if (errsv == ERROR_MORE_DATA)
320         {
321           /* If a named pipe is being read in message mode and the
322            * next message is longer than the nNumberOfBytesToRead
323            * parameter specifies, ReadFile returns FALSE and
324            * GetLastError returns ERROR_MORE_DATA */
325           retval = nread;
326           goto end;
327         }
328       else if (errsv == ERROR_HANDLE_EOF ||
329                errsv == ERROR_BROKEN_PIPE)
330         {
331           /* TODO: the other end of a pipe may call the WriteFile
332            * function with nNumberOfBytesToWrite set to zero. In this
333            * case, it's not possible for the caller to know if it's
334            * broken pipe or a read of 0. Perhaps we should add a
335            * is_broken flag for this win32 case.. */
336           retval = 0;
337         }
338       else
339         {
340           gchar *emsg;
341
342           emsg = g_win32_error_message (errsv);
343           g_set_error (error, G_IO_ERROR,
344                        g_io_error_from_win32_error (errsv),
345                        _("Error reading from handle: %s"),
346                        emsg);
347           g_free (emsg);
348         }
349     }
350
351 end:
352   CloseHandle (overlap.hEvent);
353   return retval;
354 }
355
356 static gboolean
357 g_win32_input_stream_close (GInputStream  *stream,
358                            GCancellable  *cancellable,
359                            GError       **error)
360 {
361   GWin32InputStream *win32_stream;
362   BOOL res;
363
364   win32_stream = G_WIN32_INPUT_STREAM (stream);
365
366   if (!win32_stream->priv->close_handle)
367     return TRUE;
368
369   if (win32_stream->priv->fd != -1)
370     {
371       if (close (win32_stream->priv->fd) < 0)
372         {
373           g_set_error_literal (error, G_IO_ERROR,
374                                g_io_error_from_errno (errno),
375                                g_strerror (errno));
376           return FALSE;
377         }
378     }
379   else
380     {
381       res = CloseHandle (win32_stream->priv->handle);
382       if (!res)
383         {
384           int errsv = GetLastError ();
385           gchar *emsg = g_win32_error_message (errsv);
386
387           g_set_error (error, G_IO_ERROR,
388                        g_io_error_from_win32_error (errsv),
389                        _("Error closing handle: %s"),
390                        emsg);
391           g_free (emsg);
392           return FALSE;
393         }
394     }
395
396   return TRUE;
397 }
398
399 GInputStream *
400 g_win32_input_stream_new_from_fd (gint      fd,
401                                   gboolean  close_fd)
402 {
403   GWin32InputStream *win32_stream;
404
405   win32_stream = G_WIN32_INPUT_STREAM (g_win32_input_stream_new ((HANDLE) _get_osfhandle (fd), close_fd));
406   win32_stream->priv->fd = fd;
407
408   return (GInputStream*)win32_stream;
409 }