Save errno before calling other funcs that potentially alter it. Bug
[platform/upstream/glib.git] / gio / gunixinputstream.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 #include <poll.h>
32
33 #include <glib.h>
34 #include <glib/gstdio.h>
35 #include "gioerror.h"
36 #include "gsimpleasyncresult.h"
37 #include "gunixinputstream.h"
38 #include "gcancellable.h"
39 #include "gasynchelper.h"
40 #include "glibintl.h"
41
42 #include "gioalias.h"
43
44 /**
45  * SECTION:gunixinputstream
46  * @short_description: Streaming input operations for Unix file descriptors
47  * @include: gio/gunixinputstream.h
48  * @see_also: #GInputStream
49  *
50  * #GUnixInputStream implements #GInputStream for reading from a
51  * unix file descriptor, including asynchronous operations. The file
52  * descriptor much be selectable, so it doesn't work with opened files.
53  **/
54
55 G_DEFINE_TYPE (GUnixInputStream, g_unix_input_stream, G_TYPE_INPUT_STREAM);
56
57 struct _GUnixInputStreamPrivate {
58   int fd;
59   gboolean close_fd_at_close;
60 };
61
62 static gssize   g_unix_input_stream_read         (GInputStream         *stream,
63                                                   void                 *buffer,
64                                                   gsize                 count,
65                                                   GCancellable         *cancellable,
66                                                   GError              **error);
67 static gboolean g_unix_input_stream_close        (GInputStream         *stream,
68                                                   GCancellable         *cancellable,
69                                                   GError              **error);
70 static void     g_unix_input_stream_read_async   (GInputStream         *stream,
71                                                   void                 *buffer,
72                                                   gsize                 count,
73                                                   int                   io_priority,
74                                                   GCancellable         *cancellable,
75                                                   GAsyncReadyCallback   callback,
76                                                   gpointer              data);
77 static gssize   g_unix_input_stream_read_finish  (GInputStream         *stream,
78                                                   GAsyncResult         *result,
79                                                   GError              **error);
80 static void     g_unix_input_stream_skip_async   (GInputStream         *stream,
81                                                   gsize                 count,
82                                                   int                   io_priority,
83                                                   GCancellable         *cancellable,
84                                                   GAsyncReadyCallback   callback,
85                                                   gpointer              data);
86 static gssize   g_unix_input_stream_skip_finish  (GInputStream         *stream,
87                                                   GAsyncResult         *result,
88                                                   GError              **error);
89 static void     g_unix_input_stream_close_async  (GInputStream         *stream,
90                                                   int                   io_priority,
91                                                   GCancellable         *cancellable,
92                                                   GAsyncReadyCallback   callback,
93                                                   gpointer              data);
94 static gboolean g_unix_input_stream_close_finish (GInputStream         *stream,
95                                                   GAsyncResult         *result,
96                                                   GError              **error);
97
98
99 static void
100 g_unix_input_stream_finalize (GObject *object)
101 {
102   GUnixInputStream *stream;
103   
104   stream = G_UNIX_INPUT_STREAM (object);
105
106   if (G_OBJECT_CLASS (g_unix_input_stream_parent_class)->finalize)
107     (*G_OBJECT_CLASS (g_unix_input_stream_parent_class)->finalize) (object);
108 }
109
110 static void
111 g_unix_input_stream_class_init (GUnixInputStreamClass *klass)
112 {
113   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
114   GInputStreamClass *stream_class = G_INPUT_STREAM_CLASS (klass);
115   
116   g_type_class_add_private (klass, sizeof (GUnixInputStreamPrivate));
117   
118   gobject_class->finalize = g_unix_input_stream_finalize;
119
120   stream_class->read_fn = g_unix_input_stream_read;
121   stream_class->close_fn = g_unix_input_stream_close;
122   stream_class->read_async = g_unix_input_stream_read_async;
123   stream_class->read_finish = g_unix_input_stream_read_finish;
124   if (0)
125     {
126       /* TODO: Implement instead of using fallbacks */
127       stream_class->skip_async = g_unix_input_stream_skip_async;
128       stream_class->skip_finish = g_unix_input_stream_skip_finish;
129     }
130   stream_class->close_async = g_unix_input_stream_close_async;
131   stream_class->close_finish = g_unix_input_stream_close_finish;
132 }
133
134 static void
135 g_unix_input_stream_init (GUnixInputStream *unix_stream)
136 {
137   unix_stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (unix_stream,
138                                                    G_TYPE_UNIX_INPUT_STREAM,
139                                                    GUnixInputStreamPrivate);
140 }
141
142 /**
143  * g_unix_input_stream_new:
144  * @fd: unix file descriptor.
145  * @close_fd_at_close: a #gboolean.
146  * 
147  * Creates a new #GUnixInputStream for the given @fd. If @close_fd_at_close
148  * is %TRUE, the file descriptor will be closed when the stream is closed.
149  * 
150  * Returns: a #GUnixInputStream. 
151  **/
152 GInputStream *
153 g_unix_input_stream_new (int      fd,
154                          gboolean close_fd_at_close)
155 {
156   GUnixInputStream *stream;
157
158   g_return_val_if_fail (fd != -1, NULL);
159
160   stream = g_object_new (G_TYPE_UNIX_INPUT_STREAM, NULL);
161
162   stream->priv->fd = fd;
163   stream->priv->close_fd_at_close = close_fd_at_close;
164   
165   return G_INPUT_STREAM (stream);
166 }
167
168 static gssize
169 g_unix_input_stream_read (GInputStream  *stream,
170                           void          *buffer,
171                           gsize          count,
172                           GCancellable  *cancellable,
173                           GError       **error)
174 {
175   GUnixInputStream *unix_stream;
176   gssize res;
177   struct pollfd poll_fds[2];
178   int poll_ret;
179   int cancel_fd;
180
181   unix_stream = G_UNIX_INPUT_STREAM (stream);
182
183   cancel_fd = g_cancellable_get_fd (cancellable);
184   if (cancel_fd != -1)
185     {
186       do
187         {
188           poll_fds[0].events = POLLIN;
189           poll_fds[0].fd = unix_stream->priv->fd;
190           poll_fds[1].events = POLLIN;
191           poll_fds[1].fd = cancel_fd;
192           poll_ret = poll (poll_fds, 2, -1);
193         }
194       while (poll_ret == -1 && errno == EINTR);
195       
196       if (poll_ret == -1)
197         {
198           int errsv = errno;
199
200           g_set_error (error, G_IO_ERROR,
201                        g_io_error_from_errno (errsv),
202                        _("Error reading from unix: %s"),
203                        g_strerror (errsv));
204           return -1;
205         }
206     }
207
208   while (1)
209     {
210       if (g_cancellable_set_error_if_cancelled (cancellable, error))
211         break;
212       res = read (unix_stream->priv->fd, buffer, count);
213       if (res == -1)
214         {
215           int errsv = errno;
216
217           if (errsv == EINTR)
218             continue;
219           
220           g_set_error (error, G_IO_ERROR,
221                        g_io_error_from_errno (errsv),
222                        _("Error reading from unix: %s"),
223                        g_strerror (errsv));
224         }
225       
226       break;
227     }
228
229   return res;
230 }
231
232 static gboolean
233 g_unix_input_stream_close (GInputStream  *stream,
234                            GCancellable  *cancellable,
235                            GError       **error)
236 {
237   GUnixInputStream *unix_stream;
238   int res;
239
240   unix_stream = G_UNIX_INPUT_STREAM (stream);
241
242   if (!unix_stream->priv->close_fd_at_close)
243     return TRUE;
244   
245   while (1)
246     {
247       /* This might block during the close. Doesn't seem to be a way to avoid it though. */
248       res = close (unix_stream->priv->fd);
249       if (res == -1)
250         {
251           int errsv = errno;
252
253           g_set_error (error, G_IO_ERROR,
254                        g_io_error_from_errno (errsv),
255                        _("Error closing unix: %s"),
256                        g_strerror (errsv));
257         }
258       break;
259     }
260   
261   return res != -1;
262 }
263
264 typedef struct {
265   gsize count;
266   void *buffer;
267   GAsyncReadyCallback callback;
268   gpointer user_data;
269   GCancellable *cancellable;
270   GUnixInputStream *stream;
271 } ReadAsyncData;
272
273 static gboolean
274 read_async_cb (ReadAsyncData *data,
275                GIOCondition   condition,
276                int            fd)
277 {
278   GSimpleAsyncResult *simple;
279   GError *error = NULL;
280   gssize count_read;
281
282   /* We know that we can read from fd once without blocking */
283   while (1)
284     {
285       if (g_cancellable_set_error_if_cancelled (data->cancellable, &error))
286         {
287           count_read = -1;
288           break;
289         }
290       count_read = read (data->stream->priv->fd, data->buffer, data->count);
291       if (count_read == -1)
292         {
293           int errsv = errno;
294
295           if (errsv == EINTR)
296             continue;
297           
298           g_set_error (&error, G_IO_ERROR,
299                        g_io_error_from_errno (errsv),
300                        _("Error reading from unix: %s"),
301                        g_strerror (errsv));
302         }
303       break;
304     }
305
306   simple = g_simple_async_result_new (G_OBJECT (data->stream),
307                                       data->callback,
308                                       data->user_data,
309                                       g_unix_input_stream_read_async);
310
311   g_simple_async_result_set_op_res_gssize (simple, count_read);
312
313   if (count_read == -1)
314     {
315       g_simple_async_result_set_from_error (simple, error);
316       g_error_free (error);
317     }
318
319   /* Complete immediately, not in idle, since we're already in a mainloop callout */
320   g_simple_async_result_complete (simple);
321   g_object_unref (simple);
322
323   return FALSE;
324 }
325
326 static void
327 g_unix_input_stream_read_async (GInputStream        *stream,
328                                 void                *buffer,
329                                 gsize                count,
330                                 int                  io_priority,
331                                 GCancellable        *cancellable,
332                                 GAsyncReadyCallback  callback,
333                                 gpointer             user_data)
334 {
335   GSource *source;
336   GUnixInputStream *unix_stream;
337   ReadAsyncData *data;
338
339   unix_stream = G_UNIX_INPUT_STREAM (stream);
340
341   data = g_new0 (ReadAsyncData, 1);
342   data->count = count;
343   data->buffer = buffer;
344   data->callback = callback;
345   data->user_data = user_data;
346   data->cancellable = cancellable;
347   data->stream = unix_stream;
348
349   source = _g_fd_source_new (unix_stream->priv->fd,
350                              POLLIN,
351                              cancellable);
352   
353   g_source_set_callback (source, (GSourceFunc)read_async_cb, data, g_free);
354   g_source_attach (source, NULL);
355  
356   g_source_unref (source);
357 }
358
359 static gssize
360 g_unix_input_stream_read_finish (GInputStream  *stream,
361                                  GAsyncResult  *result,
362                                  GError       **error)
363 {
364   GSimpleAsyncResult *simple;
365   gssize nread;
366
367   simple = G_SIMPLE_ASYNC_RESULT (result);
368   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_unix_input_stream_read_async);
369   
370   nread = g_simple_async_result_get_op_res_gssize (simple);
371   return nread;
372 }
373
374 static void
375 g_unix_input_stream_skip_async (GInputStream        *stream,
376                                 gsize                count,
377                                 int                  io_priority,
378                                 GCancellable        *cancellable,
379                                 GAsyncReadyCallback  callback,
380                                 gpointer             data)
381 {
382   g_warn_if_reached ();
383   /* TODO: Not implemented */
384 }
385
386 static gssize
387 g_unix_input_stream_skip_finish  (GInputStream  *stream,
388                                   GAsyncResult  *result,
389                                   GError       **error)
390 {
391   g_warn_if_reached ();
392   return 0;
393   /* TODO: Not implemented */
394 }
395
396
397 typedef struct {
398   GInputStream *stream;
399   GAsyncReadyCallback callback;
400   gpointer user_data;
401 } CloseAsyncData;
402
403 static void
404 close_async_data_free (gpointer _data)
405 {
406   CloseAsyncData *data = _data;
407
408   g_free (data);
409 }
410
411 static gboolean
412 close_async_cb (CloseAsyncData *data)
413 {
414   GUnixInputStream *unix_stream;
415   GSimpleAsyncResult *simple;
416   GError *error = NULL;
417   gboolean result;
418   int res;
419
420   unix_stream = G_UNIX_INPUT_STREAM (data->stream);
421
422   if (!unix_stream->priv->close_fd_at_close)
423     {
424       result = TRUE;
425       goto out;
426     }
427   
428   while (1)
429     {
430       res = close (unix_stream->priv->fd);
431       if (res == -1)
432         {
433           int errsv = errno;
434
435           g_set_error (&error, G_IO_ERROR,
436                        g_io_error_from_errno (errsv),
437                        _("Error closing unix: %s"),
438                        g_strerror (errsv));
439         }
440       break;
441     }
442   
443   result = res != -1;
444
445  out:
446   simple = g_simple_async_result_new (G_OBJECT (data->stream),
447                                       data->callback,
448                                       data->user_data,
449                                       g_unix_input_stream_close_async);
450
451   if (!result)
452     {
453       g_simple_async_result_set_from_error (simple, error);
454       g_error_free (error);
455     }
456
457   /* Complete immediately, not in idle, since we're already in a mainloop callout */
458   g_simple_async_result_complete (simple);
459   g_object_unref (simple);
460   
461   return FALSE;
462 }
463
464 static void
465 g_unix_input_stream_close_async (GInputStream        *stream,
466                                  int                  io_priority,
467                                  GCancellable        *cancellable,
468                                  GAsyncReadyCallback  callback,
469                                  gpointer             user_data)
470 {
471   GSource *idle;
472   CloseAsyncData *data;
473
474   data = g_new0 (CloseAsyncData, 1);
475
476   data->stream = stream;
477   data->callback = callback;
478   data->user_data = user_data;
479   
480   idle = g_idle_source_new ();
481   g_source_set_callback (idle, (GSourceFunc)close_async_cb, data, close_async_data_free);
482   g_source_attach (idle, NULL);
483   g_source_unref (idle);
484 }
485
486 static gboolean
487 g_unix_input_stream_close_finish (GInputStream  *stream,
488                                   GAsyncResult  *result,
489                                   GError       **error)
490 {
491   /* Failures handled in generic close_finish code */
492   return TRUE;
493 }
494
495 #define __G_UNIX_INPUT_STREAM_C__
496 #include "gioaliasdef.c"