4678e46593ae3329f811c44f4520ac038da08994
[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 # include <sys/types.h>
37 #else
38
39 #endif
40 #include <errno.h>
41
42 #include "ginetaddress.h"
43 #include "ginet4address.h"
44 #include "ginet6address.h"
45 #include "gsocket.h"
46 #include "gnioerror.h"
47 #include "ginetsocketaddress.h"
48
49 G_DEFINE_TYPE (GSocket, g_socket, G_TYPE_OBJECT);
50
51 enum
52 {
53   PROP_0,
54   PROP_FD,
55   PROP_BLOCKING,
56   PROP_BACKLOG,
57   PROP_LOCAL_ADDRESS,
58   PROP_REMOTE_ADDRESS
59 };
60
61 struct _GSocketPrivate
62 {
63   gint fd;
64   gboolean blocking;
65   gint backlog;
66   GSocketAddress *local_address;
67   GSocketAddress *remote_address;
68 };
69
70 static void
71 g_socket_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
72 {
73   GSocket *socket = G_SOCKET (object);
74
75   switch (prop_id)
76     {
77       case PROP_FD:
78         g_value_set_int (value, socket->priv->fd);
79         break;
80
81       case PROP_BLOCKING:
82         g_value_set_boolean (value, socket->priv->blocking);
83         break;
84
85       case PROP_BACKLOG:
86         g_value_set_int (value, socket->priv->backlog);
87         break;
88
89       case PROP_LOCAL_ADDRESS:
90         g_value_set_object (value, socket->priv->local_address);
91         break;
92
93       case PROP_REMOTE_ADDRESS:
94         g_value_set_object (value, socket->priv->remote_address);
95         break;
96
97       default:
98         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
99     }
100 }
101
102 static void
103 g_socket_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
104 {
105   GSocket *socket = G_SOCKET (object);
106
107   switch (prop_id)
108     {
109       case PROP_FD:
110         socket->priv->fd = g_value_get_int (value);
111         break;
112
113       case PROP_BLOCKING:
114         g_socket_set_blocking (socket, g_value_get_boolean (value));
115         break;
116
117       case PROP_BACKLOG:
118         socket->priv->backlog = g_value_get_int (value);
119         break;
120
121       default:
122         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
123     }
124 }
125
126 static void
127 g_socket_finalize (GObject *object)
128 {
129   GSocket *socket G_GNUC_UNUSED = G_SOCKET (object);
130
131   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
132     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
133 }
134
135 static void
136 g_socket_dispose (GObject *object)
137 {
138   GSocket *socket G_GNUC_UNUSED = G_SOCKET (object);;
139
140   if (G_OBJECT_CLASS (g_socket_parent_class)->dispose)
141     (*G_OBJECT_CLASS (g_socket_parent_class)->dispose) (object);
142 }
143
144 static void
145 g_socket_class_init (GSocketClass *klass)
146 {
147   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
148
149   // TODO: WSAStartup
150
151   g_type_class_add_private (klass, sizeof (GSocketPrivate));
152
153   gobject_class->finalize = g_socket_finalize;
154   gobject_class->dispose = g_socket_dispose;
155   gobject_class->set_property = g_socket_set_property;
156   gobject_class->get_property = g_socket_get_property;
157
158   g_object_class_install_property (gobject_class, PROP_FD,
159                                    g_param_spec_int ("fd",
160                                                      "file descriptor",
161                                                      "the socket's file descriptor",
162                                                      G_MININT,
163                                                      G_MAXINT,
164                                                      -1,
165                                                      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
166
167   g_object_class_install_property (gobject_class, PROP_BLOCKING,
168                                    g_param_spec_boolean ("blocking",
169                                                          "blocking",
170                                                          "whether or not this socket is blocking",
171                                                          TRUE,
172                                                          G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
173
174   g_object_class_install_property (gobject_class, PROP_BACKLOG,
175                                    g_param_spec_int ("backlog",
176                                                      "listen backlog",
177                                                      "outstanding connections in the listen queue",
178                                                      0,
179                                                      SOMAXCONN,
180                                                      10,
181                                                      G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
182
183   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
184                                    g_param_spec_object ("local-address",
185                                                         "local address",
186                                                         "the local address the socket is bound to",
187                                                         G_TYPE_SOCKET_ADDRESS,
188                                                         G_PARAM_READABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
189
190   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
191                                    g_param_spec_object ("remote-address",
192                                                         "remote address",
193                                                         "the remote address the socket is connected to",
194                                                         G_TYPE_SOCKET_ADDRESS,
195                                                         G_PARAM_READABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
196 }
197
198 static void
199 g_socket_init (GSocket *socket)
200 {
201   socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
202
203   socket->priv->fd = -1;
204   socket->priv->blocking = TRUE;
205   socket->priv->backlog = 10;
206   socket->priv->remote_address = NULL;
207   socket->priv->local_address = NULL;
208 }
209
210 GSocket *
211 g_socket_new (GSocketDomain domain, GSocketType type, const gchar *protocol, GError **error)
212 {
213   static GStaticMutex getprotobyname_mutex = G_STATIC_MUTEX_INIT;
214   gint fd, native_domain, native_type, native_protocol;
215
216   switch (domain)
217     {
218       case G_SOCKET_DOMAIN_INET:
219         native_domain = PF_INET;
220         break;
221
222       case G_SOCKET_DOMAIN_INET6:
223         native_domain = PF_INET6;
224         break;
225
226       case G_SOCKET_DOMAIN_UNIX:
227         native_domain = PF_UNIX;
228         break;
229
230       default:
231         g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "unsupported socket domain");
232         return NULL;
233     }
234
235   switch (type)
236     {
237       case G_SOCKET_TYPE_STREAM:
238         native_type = SOCK_STREAM;
239         break;
240
241       case G_SOCKET_TYPE_DATAGRAM:
242         native_type = SOCK_DGRAM;
243         break;
244
245       case G_SOCKET_TYPE_SEQPACKET:
246         native_type = SOCK_SEQPACKET;
247         break;
248
249       default:
250         g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "unsupported socket type");
251         return NULL;
252     }
253
254   if (protocol == NULL)
255     native_protocol = 0;
256   else
257     {
258       struct protoent *ent;
259       g_static_mutex_lock (&getprotobyname_mutex);
260       if (!(ent = getprotobyname (protocol)))
261         {
262           g_static_mutex_unlock (&getprotobyname_mutex);
263           g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "unsupported socket protocol");
264           return NULL;
265         }
266       native_protocol = ent->p_proto;
267       g_static_mutex_unlock (&getprotobyname_mutex);
268     }
269
270   fd = socket(native_domain, native_type, native_protocol);
271
272   if (fd < 0)
273     {
274       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "unable to create socket: %s", g_strerror (errno));
275       return NULL;
276     }
277
278   return G_SOCKET (g_object_new (G_TYPE_SOCKET, "fd", fd, "blocking", TRUE, NULL));
279 }
280
281 GSocket *
282 g_socket_new_from_fd (gint fd)
283 {
284   glong arg;
285   gboolean blocking;
286
287   if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
288     g_warning ("Error getting socket status flags: %s", g_strerror (errno));
289
290   blocking = ((arg & O_NONBLOCK) == 0);
291
292   return G_SOCKET (g_object_new (G_TYPE_SOCKET, "fd", fd, "blocking", blocking, NULL));
293 }
294
295 void
296 g_socket_set_blocking (GSocket  *socket,
297                        gboolean  blocking)
298 {
299   glong arg;
300
301   g_return_if_fail (G_IS_SOCKET (socket));
302
303   if ((arg = fcntl (socket->priv->fd, F_GETFL, NULL)) < 0)
304     g_warning ("Error getting socket status flags: %s", g_strerror (errno));
305
306   arg = blocking ? arg & ~O_NONBLOCK : arg | O_NONBLOCK;
307
308   if (fcntl (socket->priv->fd, F_SETFL, arg) < 0)
309     g_warning ("Error setting socket status flags: %s", g_strerror (errno));
310
311   socket->priv->blocking = blocking;
312 }
313
314 gboolean
315 g_socket_get_blocking (GSocket *socket)
316 {
317   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
318
319   return socket->priv->blocking;
320 }
321
322 GSocketAddress *
323 g_socket_get_local_address (GSocket  *socket,
324                             GError  **error)
325 {
326   gchar buffer[256];
327   gsize len = 256;
328
329   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
330
331   if (socket->priv->local_address)
332     return socket->priv->local_address;
333
334   if (getsockname (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
335     {
336       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get local address: %s", g_strerror (errno));
337       return NULL;
338     }
339
340   return (socket->priv->local_address = g_object_ref_sink (g_socket_address_from_native (buffer, len)));
341 }
342
343 GSocketAddress *
344 g_socket_get_remote_address (GSocket  *socket,
345                              GError  **error)
346 {
347   gchar buffer[256];
348   gsize len = 256;
349
350   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
351
352   if (socket->priv->remote_address)
353     return socket->priv->remote_address;
354
355   if (getpeername (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
356     {
357       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get remote address: %s", g_strerror (errno));
358       return NULL;
359     }
360
361   return (socket->priv->remote_address = g_object_ref_sink (g_socket_address_from_native (buffer, len)));
362 }
363
364 void
365 g_socket_listen (GSocket *socket)
366 {
367   g_return_if_fail (G_IS_SOCKET (socket));
368
369   listen (socket->priv->fd, socket->priv->backlog);
370 }
371
372 gboolean
373 g_socket_bind (GSocket         *socket,
374                GSocketAddress  *address,
375                GError         **error)
376 {
377   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
378
379   {
380     gchar addr[256];
381
382     if (!g_socket_address_to_native (address, addr))
383       return FALSE;
384
385     if (bind (socket->priv->fd, (struct sockaddr *) addr, g_socket_address_native_size (address)) < 0)
386       {
387         g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error binding to address: %s", g_strerror (errno));
388         return FALSE;
389       }
390
391     g_object_ref_sink (address);
392
393     socket->priv->local_address = address;
394
395     return TRUE;
396   }
397 }
398
399 GSocket *
400 g_socket_accept (GSocket       *socket,
401                  GError       **error)
402 {
403   gint ret;
404
405   if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
406     {
407       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error accepting connection");
408       return NULL;
409     }
410
411   return g_socket_new_from_fd (ret);
412 }
413
414 gboolean
415 g_socket_connect (GSocket         *socket,
416                   GSocketAddress  *address,
417                   GError         **error)
418 {
419   gchar buffer[256];
420
421   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
422
423   g_socket_address_to_native (address, buffer);
424
425   if (connect (socket->priv->fd, (struct sockaddr *) buffer, g_socket_address_native_size (address)) < 0)
426     {
427       if (errno == EINPROGRESS)
428         g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING, "connection in progress");
429       else
430         g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error connecting: %s", g_strerror (errno));
431       return FALSE;
432     }
433
434   socket->priv->remote_address = g_object_ref_sink (address);
435
436   return TRUE;
437 }
438
439 gssize
440 g_socket_receive (GSocket       *socket,
441                   gchar         *buffer,
442                   gsize          size,
443                   GError       **error)
444 {
445   gssize ret;
446
447   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
448
449   if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
450     {
451       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error receiving data: %s", g_strerror (errno));
452       return -1;
453     }
454
455   return ret;
456 }
457
458 gssize
459 g_socket_send (GSocket       *socket,
460                gchar         *buffer,
461                gsize          size,
462                GError       **error)
463 {
464   gssize ret;
465
466   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
467
468   if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
469     {
470       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error receiving data: %s", g_strerror (errno));
471       return -1;
472     }
473
474   return ret;
475 }
476
477 void
478 g_socket_close (GSocket *socket)
479 {
480   g_return_if_fail (G_IS_SOCKET (socket));
481
482 #ifdef G_OS_WIN32
483   closesocket (socket->priv->fd);
484 #else
485   close (socket->priv->fd);
486 #endif
487 }