Close socket on dispose
[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_SOCKET (object);
130
131   if (socket->priv->local_address)
132     g_object_unref (socket->priv->local_address);
133
134   if (socket->priv->remote_address)
135     g_object_unref (socket->priv->remote_address);
136
137   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
138     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
139 }
140
141 static void
142 g_socket_dispose (GObject *object)
143 {
144   GSocket *socket = G_SOCKET (object);
145
146   g_socket_close (socket);
147
148   if (G_OBJECT_CLASS (g_socket_parent_class)->dispose)
149     (*G_OBJECT_CLASS (g_socket_parent_class)->dispose) (object);
150 }
151
152 static void
153 g_socket_class_init (GSocketClass *klass)
154 {
155   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
156
157   // TODO: WSAStartup
158
159   g_type_class_add_private (klass, sizeof (GSocketPrivate));
160
161   gobject_class->finalize = g_socket_finalize;
162   gobject_class->dispose = g_socket_dispose;
163   gobject_class->set_property = g_socket_set_property;
164   gobject_class->get_property = g_socket_get_property;
165
166   g_object_class_install_property (gobject_class, PROP_FD,
167                                    g_param_spec_int ("fd",
168                                                      "file descriptor",
169                                                      "the socket's file descriptor",
170                                                      G_MININT,
171                                                      G_MAXINT,
172                                                      -1,
173                                                      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
174
175   g_object_class_install_property (gobject_class, PROP_BLOCKING,
176                                    g_param_spec_boolean ("blocking",
177                                                          "blocking",
178                                                          "whether or not this socket is blocking",
179                                                          TRUE,
180                                                          G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
181
182   g_object_class_install_property (gobject_class, PROP_BACKLOG,
183                                    g_param_spec_int ("backlog",
184                                                      "listen backlog",
185                                                      "outstanding connections in the listen queue",
186                                                      0,
187                                                      SOMAXCONN,
188                                                      10,
189                                                      G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
190
191   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
192                                    g_param_spec_object ("local-address",
193                                                         "local address",
194                                                         "the local address the socket is bound to",
195                                                         G_TYPE_SOCKET_ADDRESS,
196                                                         G_PARAM_READABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
197
198   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
199                                    g_param_spec_object ("remote-address",
200                                                         "remote address",
201                                                         "the remote address the socket is connected to",
202                                                         G_TYPE_SOCKET_ADDRESS,
203                                                         G_PARAM_READABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
204 }
205
206 static void
207 g_socket_init (GSocket *socket)
208 {
209   socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
210
211   socket->priv->fd = -1;
212   socket->priv->blocking = TRUE;
213   socket->priv->backlog = 10;
214   socket->priv->remote_address = NULL;
215   socket->priv->local_address = NULL;
216 }
217
218 GSocket *
219 g_socket_new (GSocketDomain domain, GSocketType type, const gchar *protocol, GError **error)
220 {
221   static GStaticMutex getprotobyname_mutex = G_STATIC_MUTEX_INIT;
222   gint fd, native_domain, native_type, native_protocol;
223
224   switch (domain)
225     {
226       case G_SOCKET_DOMAIN_INET:
227         native_domain = PF_INET;
228         break;
229
230       case G_SOCKET_DOMAIN_INET6:
231         native_domain = PF_INET6;
232         break;
233
234       case G_SOCKET_DOMAIN_UNIX:
235         native_domain = PF_UNIX;
236         break;
237
238       default:
239         g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "unsupported socket domain");
240         return NULL;
241     }
242
243   switch (type)
244     {
245       case G_SOCKET_TYPE_STREAM:
246         native_type = SOCK_STREAM;
247         break;
248
249       case G_SOCKET_TYPE_DATAGRAM:
250         native_type = SOCK_DGRAM;
251         break;
252
253       case G_SOCKET_TYPE_SEQPACKET:
254         native_type = SOCK_SEQPACKET;
255         break;
256
257       default:
258         g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "unsupported socket type");
259         return NULL;
260     }
261
262   if (protocol == NULL)
263     native_protocol = 0;
264   else
265     {
266       struct protoent *ent;
267       g_static_mutex_lock (&getprotobyname_mutex);
268       if (!(ent = getprotobyname (protocol)))
269         {
270           g_static_mutex_unlock (&getprotobyname_mutex);
271           g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "unsupported socket protocol");
272           return NULL;
273         }
274       native_protocol = ent->p_proto;
275       g_static_mutex_unlock (&getprotobyname_mutex);
276     }
277
278   fd = socket(native_domain, native_type, native_protocol);
279
280   if (fd < 0)
281     {
282       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "unable to create socket: %s", g_strerror (errno));
283       return NULL;
284     }
285
286   return G_SOCKET (g_object_new (G_TYPE_SOCKET, "fd", fd, "blocking", TRUE, NULL));
287 }
288
289 GSocket *
290 g_socket_new_from_fd (gint fd)
291 {
292   glong arg;
293   gboolean blocking;
294
295   if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
296     g_warning ("Error getting socket status flags: %s", g_strerror (errno));
297
298   blocking = ((arg & O_NONBLOCK) == 0);
299
300   return G_SOCKET (g_object_new (G_TYPE_SOCKET, "fd", fd, "blocking", blocking, NULL));
301 }
302
303 void
304 g_socket_set_blocking (GSocket  *socket,
305                        gboolean  blocking)
306 {
307   glong arg;
308
309   g_return_if_fail (G_IS_SOCKET (socket));
310
311   if ((arg = fcntl (socket->priv->fd, F_GETFL, NULL)) < 0)
312     g_warning ("Error getting socket status flags: %s", g_strerror (errno));
313
314   arg = blocking ? arg & ~O_NONBLOCK : arg | O_NONBLOCK;
315
316   if (fcntl (socket->priv->fd, F_SETFL, arg) < 0)
317     g_warning ("Error setting socket status flags: %s", g_strerror (errno));
318
319   socket->priv->blocking = blocking;
320 }
321
322 gboolean
323 g_socket_get_blocking (GSocket *socket)
324 {
325   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
326
327   return socket->priv->blocking;
328 }
329
330 GSocketAddress *
331 g_socket_get_local_address (GSocket  *socket,
332                             GError  **error)
333 {
334   gchar buffer[256];
335   gsize len = 256;
336
337   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
338
339   if (socket->priv->local_address)
340     return socket->priv->local_address;
341
342   if (getsockname (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
343     {
344       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get local address: %s", g_strerror (errno));
345       return NULL;
346     }
347
348   return (socket->priv->local_address = g_object_ref_sink (g_socket_address_from_native (buffer, len)));
349 }
350
351 GSocketAddress *
352 g_socket_get_remote_address (GSocket  *socket,
353                              GError  **error)
354 {
355   gchar buffer[256];
356   gsize len = 256;
357
358   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
359
360   if (socket->priv->remote_address)
361     return socket->priv->remote_address;
362
363   if (getpeername (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
364     {
365       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get remote address: %s", g_strerror (errno));
366       return NULL;
367     }
368
369   return (socket->priv->remote_address = g_object_ref_sink (g_socket_address_from_native (buffer, len)));
370 }
371
372 void
373 g_socket_listen (GSocket *socket)
374 {
375   g_return_if_fail (G_IS_SOCKET (socket));
376
377   listen (socket->priv->fd, socket->priv->backlog);
378 }
379
380 gboolean
381 g_socket_bind (GSocket         *socket,
382                GSocketAddress  *address,
383                GError         **error)
384 {
385   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
386
387   {
388     gchar addr[256];
389
390     if (!g_socket_address_to_native (address, addr))
391       return FALSE;
392
393     if (bind (socket->priv->fd, (struct sockaddr *) addr, g_socket_address_native_size (address)) < 0)
394       {
395         g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error binding to address: %s", g_strerror (errno));
396         return FALSE;
397       }
398
399     g_object_ref_sink (address);
400
401     socket->priv->local_address = address;
402
403     return TRUE;
404   }
405 }
406
407 GSocket *
408 g_socket_accept (GSocket       *socket,
409                  GError       **error)
410 {
411   gint ret;
412
413   if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
414     {
415       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error accepting connection: %s", g_strerror (errno));
416       return NULL;
417     }
418
419   return g_socket_new_from_fd (ret);
420 }
421
422 gboolean
423 g_socket_connect (GSocket         *socket,
424                   GSocketAddress  *address,
425                   GError         **error)
426 {
427   gchar buffer[256];
428
429   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
430
431   g_socket_address_to_native (address, buffer);
432
433   if (connect (socket->priv->fd, (struct sockaddr *) buffer, g_socket_address_native_size (address)) < 0)
434     {
435       if (errno == EINPROGRESS)
436         g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING, "connection in progress");
437       else
438         g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error connecting: %s", g_strerror (errno));
439       return FALSE;
440     }
441
442   socket->priv->remote_address = g_object_ref_sink (address);
443
444   return TRUE;
445 }
446
447 gssize
448 g_socket_receive (GSocket       *socket,
449                   gchar         *buffer,
450                   gsize          size,
451                   GError       **error)
452 {
453   gssize ret;
454
455   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
456
457   if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
458     {
459       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error receiving data: %s", g_strerror (errno));
460       return -1;
461     }
462
463   return ret;
464 }
465
466 gssize
467 g_socket_send (GSocket       *socket,
468                gchar         *buffer,
469                gsize          size,
470                GError       **error)
471 {
472   gssize ret;
473
474   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
475
476   if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
477     {
478       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error sending data: %s", g_strerror (errno));
479       return -1;
480     }
481
482   return ret;
483 }
484
485 void
486 g_socket_close (GSocket *socket)
487 {
488   g_return_if_fail (G_IS_SOCKET (socket));
489
490 #ifdef G_OS_WIN32
491   closesocket (socket->priv->fd);
492 #else
493   close (socket->priv->fd);
494 #endif
495 }
496
497 GSource *
498 g_socket_create_source (GSocket      *socket,
499                         GIOCondition  condition,
500                         GCancellable *cancellable)
501 {
502   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
503
504   return _g_fd_source_new (socket->priv->fd, G_IO_IN | G_IO_HUP | G_IO_ERR, cancellable);
505 }