pull in gasynchelper (won't need this once gnio is merged into gio)
[cascardo/gnio.git] / gnio / gsocket.c
1 /* GNIO - GLib Network Layer of GIO
2  *
3  * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
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  * Authors: Christian Kellner <gicmo@gnome.org>
21  *          Samuel Cormier-Iijima <sciyoshi@gmail.com>
22  */
23
24 #include <config.h>
25 #include <glib.h>
26 #include <gio/gio.h>
27 #include <gio/gasynchelper.h>
28
29 #include <string.h>
30 #ifndef G_OS_WIN32
31 # include <netinet/in.h>
32 # include <arpa/inet.h>
33 # include <netdb.h>
34 # include <fcntl.h>
35 # include <unistd.h>
36 #else
37
38 #endif
39 #include <errno.h>
40
41 #include "ginetaddress.h"
42 #include "ginet4address.h"
43 #include "ginet6address.h"
44 #include "gsocket.h"
45 #include "gnioerror.h"
46 #include "ginetsocketaddress.h"
47
48 G_DEFINE_TYPE (GSocket, g_socket, G_TYPE_OBJECT);
49
50 enum
51 {
52   PROP_0,
53   PROP_FD,
54   PROP_BLOCKING
55 };
56
57 struct _GSocketPrivate
58 {
59   gint fd;
60   gboolean blocking;
61 };
62
63 static void
64 g_socket_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
65 {
66   GSocket *socket = G_SOCKET (object);
67
68   switch (prop_id)
69     {
70       case PROP_FD:
71         g_value_set_int (value, socket->priv->fd);
72         break;
73
74       case PROP_BLOCKING:
75         g_value_set_boolean (value, socket->priv->blocking);
76         break;
77
78       default:
79         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
80     }
81 }
82
83 static void
84 g_socket_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
85 {
86   GSocket *socket = G_SOCKET (object);
87
88   switch (prop_id)
89     {
90       case PROP_FD:
91         socket->priv->fd = g_value_get_int (value);
92         break;
93
94       case PROP_BLOCKING:
95         g_socket_set_blocking (socket, g_value_get_boolean (value));
96         break;
97
98       default:
99         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
100     }
101 }
102
103 static void
104 g_socket_finalize (GObject *object)
105 {
106   GSocket *socket G_GNUC_UNUSED = G_SOCKET (object);
107
108   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
109     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
110 }
111
112 static void
113 g_socket_dispose (GObject *object)
114 {
115   GSocket *socket G_GNUC_UNUSED = G_SOCKET (object);;
116
117   if (G_OBJECT_CLASS (g_socket_parent_class)->dispose)
118     (*G_OBJECT_CLASS (g_socket_parent_class)->dispose) (object);
119 }
120
121 static void
122 g_socket_class_init (GSocketClass *klass)
123 {
124   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
125
126   g_type_class_add_private (klass, sizeof (GSocketPrivate));
127
128   gobject_class->finalize = g_socket_finalize;
129   gobject_class->dispose = g_socket_dispose;
130   gobject_class->set_property = g_socket_set_property;
131   gobject_class->get_property = g_socket_get_property;
132
133   g_object_class_install_property (gobject_class, PROP_FD,
134                                    g_param_spec_int ("fd",
135                                                      "file descriptor",
136                                                      "the socket's file descriptor",
137                                                      G_MININT,
138                                                      G_MAXINT,
139                                                      -1,
140                                                      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
141
142   g_object_class_install_property (gobject_class, PROP_BLOCKING,
143                                    g_param_spec_boolean ("blocking",
144                                                          "blocking",
145                                                          "whether or not this socket is blocking",
146                                                          TRUE,
147                                                          G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
148 }
149
150 static void
151 g_socket_init (GSocket *socket)
152 {
153   socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
154
155   socket->priv->fd = -1;
156   socket->priv->blocking = TRUE;
157 }
158
159 GSocket *
160 g_socket_new (gint domain, gint type, gint protocol)
161 {
162   gint sock;
163
164   sock = socket(domain, type, protocol);
165
166   if (sock < 0)
167     return NULL;
168
169   return G_SOCKET (g_object_new (G_TYPE_SOCKET, "fd", sock, NULL));
170 }
171
172 GSocket *
173 g_socket_new_from_fd (gint fd)
174 {
175   glong arg;
176   gboolean blocking;
177
178   if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
179     g_warning ("Error getting socket status flags: %s", g_strerror (errno));
180
181   blocking = ((arg & O_NONBLOCK) != 0);
182
183   return G_SOCKET (g_object_new (G_TYPE_SOCKET, "blocking", blocking, "fd", fd, NULL));
184 }
185
186 void
187 g_socket_set_blocking (GSocket  *socket,
188                        gboolean  blocking)
189 {
190   glong arg;
191
192   g_return_if_fail (G_IS_SOCKET (socket));
193
194   if ((arg = fcntl (socket->priv->fd, F_GETFL, NULL)) < 0)
195     g_warning ("Error getting socket status flags: %s", g_strerror (errno));
196
197   arg = blocking ? arg | O_NONBLOCK : arg & ~O_NONBLOCK;
198
199   if (fcntl (socket->priv->fd, F_SETFL, arg) < 0)
200     g_warning ("Error setting socket status flags: %s", g_strerror (errno));
201
202   socket->priv->blocking = blocking;
203 }
204
205 gboolean
206 g_socket_get_blocking (GSocket *socket)
207 {
208   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
209
210   return socket->priv->blocking;
211 }
212
213 GSocketAddress *
214 g_socket_get_peer_address (GSocket  *socket,
215                            GError  **error)
216 {
217   gchar buffer[128];
218   gsize len;
219
220   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
221
222   if (getpeername (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
223     {
224       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get peer address");
225       return NULL;
226     }
227
228   return g_socket_address_from_native (buffer, len);
229 }
230
231 void
232 g_socket_listen (GSocket *socket,
233                  gint     backlog)
234 {
235   g_return_if_fail (G_IS_SOCKET (socket));
236
237   listen (socket->priv->fd, backlog);
238 }
239
240 gboolean
241 g_socket_bind (GSocket         *socket,
242                GSocketAddress  *address,
243                GError         **error)
244 {
245   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
246
247   {
248     gchar addr[g_socket_address_native_size (address)];
249
250     if (!g_socket_address_to_native (address, addr))
251       return FALSE;
252
253     if (bind (socket->priv->fd, (struct sockaddr *) addr, g_socket_address_native_size (address)) < 0)
254       {
255         // TODO: set error
256         return FALSE;
257       }
258
259     g_object_unref (address);
260
261     return TRUE;
262   }
263 }
264
265 GSocket *
266 g_socket_accept (GSocket       *socket,
267                  GCancellable  *cancellable,
268                  GError       **error)
269 {
270   gint ret;
271
272   if (g_cancellable_set_error_if_cancelled (cancellable, error))
273     return NULL;
274
275   if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
276     {
277       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error accepting connection");
278       return NULL;
279     }
280
281   if (g_cancellable_set_error_if_cancelled (cancellable, error))
282     {
283       close (ret);
284       return NULL;
285     }
286
287   return g_socket_new_from_fd (ret);
288 }
289
290 typedef struct {
291   GAsyncReadyCallback callback;
292   GCancellable *cancellable;
293   gpointer user_data;
294   GSocket *socket;
295 } AcceptData;
296
297 static gboolean
298 accept_callback (AcceptData *data,
299                  GIOCondition condition,
300                  gint fd)
301 {
302   if (condition & G_IO_IN)
303     {
304       g_print ("WE COULD ACCEPT HERE\n");
305     }
306
307   return FALSE;
308 }
309
310 void
311 g_socket_accept_async (GSocket             *socket,
312                        GCancellable        *cancellable,
313                        GAsyncReadyCallback  callback,
314                        gpointer             user_data)
315 {
316   GSource *source;
317   GSimpleAsyncResult *result;
318   AcceptData *data;
319   gint ret;
320
321   g_return_if_fail (G_IS_SOCKET (socket));
322
323   if (g_socket_get_blocking (socket))
324     g_socket_set_blocking (socket, FALSE);
325
326   if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
327     {
328       if (errno == EAGAIN)
329         {
330           source = _g_fd_source_new (socket->priv->fd, G_IO_IN | G_IO_HUP | G_IO_ERR, cancellable);
331
332           data = g_new (AcceptData, 1);
333
334           data->socket = socket;
335           data->callback = callback;
336           data->cancellable = cancellable;
337           data->user_data = user_data;
338
339           g_source_set_callback (source, (GSourceFunc) accept_callback, data, g_free);
340
341           g_source_attach (source, NULL);
342         }
343       else
344         {
345           g_simple_async_report_error_in_idle (G_OBJECT (socket), callback, user_data, G_IO_ERROR, g_io_error_from_errno (errno), "error accepting connection");
346         }
347     }
348   else
349     {
350       result = g_simple_async_result_new (G_OBJECT (socket), callback, user_data, g_socket_accept_async);
351
352       g_simple_async_result_complete_in_idle (result);
353
354       g_object_unref (result);
355     }
356 }
357
358 GSocket *
359 g_socket_accept_finish (GSocket       *socket,
360                         GAsyncResult  *result,
361                         GError       **error)
362 {
363   return NULL;
364 }
365
366 gboolean
367 g_socket_connect (GSocket         *socket,
368                   GSocketAddress  *address,
369                   GCancellable    *cancellable,
370                   GError         **error)
371 {
372   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
373 /*
374   if (connect () < 0)
375     {
376       if (errno == EINPROGRESS)
377         g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING, "connection in progress");
378       else
379         g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error connecting: %s", g_strerror (errno));
380       return FALSE;
381     }
382 */
383   return TRUE;
384 }
385
386 void
387 g_socket_connect_async (GSocket             *socket,
388                         GSocketAddress      *address,
389                         GCancellable        *cancellable,
390                         GAsyncReadyCallback *callback,
391                         gpointer             user_data)
392 {
393
394 }
395
396 gboolean
397 g_socket_connect_finish (GSocket       *socket,
398                          GAsyncResult  *result,
399                          GError       **error)
400 {
401   return FALSE;
402 }