Fixed building issues after merge
[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 "gasynchelper.h"
28 #include "gnioenumtypes.h"
29
30 #include <string.h>
31 #ifndef G_OS_WIN32
32 # include <netinet/in.h>
33 # include <arpa/inet.h>
34 # include <netdb.h>
35 # include <fcntl.h>
36 # include <unistd.h>
37 # include <sys/types.h>
38 #else
39
40 #endif
41 #include <errno.h>
42
43 #include "ginetaddress.h"
44 #include "ginet4address.h"
45 #include "ginet6address.h"
46 #include "gsocket.h"
47 #include "gnioerror.h"
48 #include "ginetsocketaddress.h"
49
50 G_DEFINE_TYPE (GSocket, g_socket, G_TYPE_OBJECT);
51
52 enum
53 {
54   PROP_0,
55   PROP_DOMAIN,
56   PROP_TYPE,
57   PROP_PROTOCOL,
58   PROP_FD,
59   PROP_BLOCKING,
60   PROP_BACKLOG,
61   PROP_REUSE_ADDRESS,
62   PROP_LOCAL_ADDRESS,
63   PROP_REMOTE_ADDRESS
64 };
65
66 struct _GSocketPrivate
67 {
68   GSocketDomain domain;
69   GSocketType type;
70   gchar *protocol;
71   gint fd;
72   gboolean blocking;
73   gint backlog;
74   gboolean reuse_address;
75   GError *error;
76   GSocketAddress *local_address;
77   GSocketAddress *remote_address;
78 };
79
80 static void
81 g_socket_constructed (GObject *object)
82 {
83   GSocket *sock = G_SOCKET (object);
84   GError *error = NULL;
85   static GStaticMutex getprotobyname_mutex = G_STATIC_MUTEX_INIT;
86   gint fd, native_domain, native_type, native_protocol;
87
88   if (sock->priv->fd >= 0)
89     {
90       // we've been constructed from an existing file descriptor
91       glong arg;
92       gboolean blocking;
93
94       // TODO: set the socket type with getsockopt (SO_TYPE)
95       // TODO: what should we do about domain and protocol?
96
97       if ((arg = fcntl (sock->priv->fd, F_GETFL, NULL)) < 0)
98         g_warning ("Error getting socket status flags: %s", g_strerror (errno));
99
100       blocking = ((arg & O_NONBLOCK) == 0);
101
102       return;
103     }
104
105   switch (sock->priv->domain)
106     {
107       case G_SOCKET_DOMAIN_INET:
108         native_domain = PF_INET;
109         break;
110
111       case G_SOCKET_DOMAIN_INET6:
112         native_domain = PF_INET6;
113         break;
114
115       case G_SOCKET_DOMAIN_UNIX:
116         native_domain = PF_UNIX;
117         break;
118
119       default:
120         g_set_error (&error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "unsupported socket domain");
121         return;
122     }
123
124   switch (sock->priv->type)
125     {
126       case G_SOCKET_TYPE_STREAM:
127         native_type = SOCK_STREAM;
128         break;
129
130       case G_SOCKET_TYPE_DATAGRAM:
131         native_type = SOCK_DGRAM;
132         break;
133
134       case G_SOCKET_TYPE_SEQPACKET:
135         native_type = SOCK_SEQPACKET;
136         break;
137
138       default:
139         g_set_error (&error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "unsupported socket type");
140         return;
141     }
142
143   if (sock->priv->protocol == NULL)
144     native_protocol = 0;
145   else
146     {
147       struct protoent *ent;
148       g_static_mutex_lock (&getprotobyname_mutex);
149       if (!(ent = getprotobyname (sock->priv->protocol)))
150         {
151           g_static_mutex_unlock (&getprotobyname_mutex);
152           g_set_error (&error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "unsupported socket protocol");
153           return;
154         }
155       native_protocol = ent->p_proto;
156       g_static_mutex_unlock (&getprotobyname_mutex);
157     }
158
159   fd = socket (native_domain, native_type, native_protocol);
160
161   if (fd < 0)
162     {
163       g_set_error (&error, G_IO_ERROR, g_io_error_from_errno (errno), "unable to create socket: %s", g_strerror (errno));
164       return;
165     }
166
167   sock->priv->fd = fd;
168 }
169
170 static void
171 g_socket_get_property (GObject    *object,
172                        guint       prop_id,
173                        GValue     *value,
174                        GParamSpec *pspec)
175 {
176   GSocket *socket = G_SOCKET (object);
177
178   switch (prop_id)
179     {
180       case PROP_DOMAIN:
181         g_value_set_enum (value, socket->priv->domain);
182         break;
183
184       case PROP_TYPE:
185         g_value_set_enum (value, socket->priv->type);
186         break;
187
188       case PROP_PROTOCOL:
189         g_value_set_string (value, socket->priv->protocol);
190         break;
191
192       case PROP_FD:
193         g_value_set_int (value, socket->priv->fd);
194         break;
195
196       case PROP_BLOCKING:
197         g_value_set_boolean (value, socket->priv->blocking);
198         break;
199
200       case PROP_BACKLOG:
201         g_value_set_int (value, socket->priv->backlog);
202         break;
203
204       case PROP_REUSE_ADDRESS:
205         g_value_set_boolean (value, socket->priv->reuse_address);
206         break;
207
208       case PROP_LOCAL_ADDRESS:
209         g_value_set_object (value, socket->priv->local_address);
210         break;
211
212       case PROP_REMOTE_ADDRESS:
213         g_value_set_object (value, socket->priv->remote_address);
214         break;
215
216       default:
217         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
218     }
219 }
220
221 static void
222 g_socket_set_property (GObject      *object,
223                        guint         prop_id,
224                        const GValue *value,
225                        GParamSpec   *pspec)
226 {
227   GSocket *socket = G_SOCKET (object);
228
229   switch (prop_id)
230     {
231       case PROP_DOMAIN:
232         socket->priv->domain = g_value_get_enum (value);
233         break;
234
235       case PROP_TYPE:
236         socket->priv->type = g_value_get_enum (value);
237         break;
238
239       case PROP_PROTOCOL:
240         socket->priv->protocol = g_value_dup_string (value);
241         break;
242
243       case PROP_FD:
244         socket->priv->fd = g_value_get_int (value);
245         break;
246
247       case PROP_BLOCKING:
248         g_socket_set_blocking (socket, g_value_get_boolean (value));
249         break;
250
251       case PROP_BACKLOG:
252         socket->priv->backlog = g_value_get_int (value);
253         break;
254
255       case PROP_REUSE_ADDRESS:
256         g_socket_set_reuse_address (socket, g_value_get_boolean (value));
257         break;
258
259       default:
260         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
261     }
262 }
263
264 static void
265 g_socket_finalize (GObject *object)
266 {
267   GSocket *socket = G_SOCKET (object);
268
269   if (socket->priv->local_address)
270     g_object_unref (socket->priv->local_address);
271
272   if (socket->priv->remote_address)
273     g_object_unref (socket->priv->remote_address);
274
275   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
276     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
277 }
278
279 static void
280 g_socket_dispose (GObject *object)
281 {
282   GSocket *socket = G_SOCKET (object);
283
284   g_free (socket->priv->protocol);
285
286   g_clear_error (&socket->priv->error);
287
288   g_socket_close (socket);
289
290   if (G_OBJECT_CLASS (g_socket_parent_class)->dispose)
291     (*G_OBJECT_CLASS (g_socket_parent_class)->dispose) (object);
292 }
293
294 static void
295 g_socket_class_init (GSocketClass *klass)
296 {
297   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
298
299   // TODO: WSAStartup
300
301   g_type_class_add_private (klass, sizeof (GSocketPrivate));
302
303   gobject_class->finalize = g_socket_finalize;
304   gobject_class->dispose = g_socket_dispose;
305   gobject_class->constructed = g_socket_constructed;
306   gobject_class->set_property = g_socket_set_property;
307   gobject_class->get_property = g_socket_get_property;
308
309   g_object_class_install_property (gobject_class, PROP_DOMAIN,
310                                    g_param_spec_enum ("domain",
311                                                       "socket domain",
312                                                       "the socket's domain",
313                                                       G_TYPE_SOCKET_DOMAIN,
314                                                       G_SOCKET_DOMAIN_INET,
315                                                       G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
316
317   g_object_class_install_property (gobject_class, PROP_TYPE,
318                                    g_param_spec_enum ("type",
319                                                       "socket type",
320                                                       "the socket's type",
321                                                       G_TYPE_SOCKET_TYPE,
322                                                       G_SOCKET_TYPE_STREAM,
323                                                       G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
324
325   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
326                                    g_param_spec_string ("protocol",
327                                                         "socket protocol",
328                                                         "the socket's protocol",
329                                                         NULL,
330                                                         G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
331
332   g_object_class_install_property (gobject_class, PROP_FD,
333                                    g_param_spec_int ("fd",
334                                                      "file descriptor",
335                                                      "the socket's file descriptor",
336                                                      G_MININT,
337                                                      G_MAXINT,
338                                                      -1,
339                                                      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
340
341   g_object_class_install_property (gobject_class, PROP_BLOCKING,
342                                    g_param_spec_boolean ("blocking",
343                                                          "blocking",
344                                                          "whether or not this socket is blocking",
345                                                          TRUE,
346                                                          G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
347
348   g_object_class_install_property (gobject_class, PROP_BACKLOG,
349                                    g_param_spec_int ("backlog",
350                                                      "listen backlog",
351                                                      "outstanding connections in the listen queue",
352                                                      0,
353                                                      SOMAXCONN,
354                                                      10,
355                                                      G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
356
357   g_object_class_install_property (gobject_class, PROP_REUSE_ADDRESS,
358                                    g_param_spec_boolean ("reuse-address",
359                                                          "reuse address",
360                                                          "allow reuse of local addresses when binding",
361                                                          FALSE,
362                                                          G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
363
364   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
365                                    g_param_spec_object ("local-address",
366                                                         "local address",
367                                                         "the local address the socket is bound to",
368                                                         G_TYPE_SOCKET_ADDRESS,
369                                                         G_PARAM_READABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
370
371   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
372                                    g_param_spec_object ("remote-address",
373                                                         "remote address",
374                                                         "the remote address the socket is connected to",
375                                                         G_TYPE_SOCKET_ADDRESS,
376                                                         G_PARAM_READABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB | G_PARAM_STATIC_NICK));
377 }
378
379 static void
380 g_socket_init (GSocket *socket)
381 {
382   socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
383
384   socket->priv->fd = -1;
385   socket->priv->blocking = TRUE;
386   socket->priv->backlog = 10;
387   socket->priv->reuse_address = FALSE;
388   socket->priv->error = NULL;
389   socket->priv->remote_address = NULL;
390   socket->priv->local_address = NULL;
391 }
392
393 GSocket *
394 g_socket_new (GSocketDomain domain, GSocketType type, const gchar *protocol)
395 {
396   return G_SOCKET (g_object_new (G_TYPE_SOCKET, "domain", domain, "type", type, "protocol", protocol, NULL));
397 }
398
399 GSocket *
400 g_socket_new_from_fd (gint fd)
401 {
402   return G_SOCKET (g_object_new (G_TYPE_SOCKET, "fd", fd, NULL));
403 }
404
405 void
406 g_socket_set_blocking (GSocket  *socket,
407                        gboolean  blocking)
408 {
409   glong arg;
410
411   g_return_if_fail (G_IS_SOCKET (socket));
412
413   if ((arg = fcntl (socket->priv->fd, F_GETFL, NULL)) < 0)
414     g_warning ("Error getting socket status flags: %s", g_strerror (errno));
415
416   arg = blocking ? arg & ~O_NONBLOCK : arg | O_NONBLOCK;
417
418   if (fcntl (socket->priv->fd, F_SETFL, arg) < 0)
419     g_warning ("Error setting socket status flags: %s", g_strerror (errno));
420
421   socket->priv->blocking = blocking;
422
423   g_object_notify (G_OBJECT (socket), "blocking");
424 }
425
426 gboolean
427 g_socket_get_blocking (GSocket *socket)
428 {
429   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
430
431   return socket->priv->blocking;
432 }
433
434 void
435 g_socket_set_reuse_address (GSocket  *socket,
436                             gboolean  reuse)
437 {
438   gint value = (gint) reuse;
439
440   g_return_if_fail (G_IS_SOCKET (socket));
441
442   if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR, (gpointer) &value, sizeof (value)) < 0)
443     g_warning ("error setting reuse address: %s", g_strerror (errno));
444
445   socket->priv->reuse_address = reuse;
446
447   g_object_notify (G_OBJECT (socket), "reuse-address");
448 }
449
450 gboolean
451 g_socket_get_reuse_address (GSocket *socket)
452 {
453   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
454
455   return socket->priv->reuse_address;
456 }
457
458 gboolean
459 g_socket_has_socket_error (GSocket  *socket,
460                            GError  **error)
461 {
462   gint sockerr;
463   guint32 sockerr_size = sizeof (sockerr);
464
465   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
466
467   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (gpointer) &sockerr, &sockerr_size) < 0)
468     {
469       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get socket error: %s", g_strerror (errno));
470       return TRUE;
471     }
472
473   if (sockerr != 0)
474     {
475       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (sockerr), "error connecting: %s", g_strerror (sockerr));
476       return TRUE;
477     }
478
479   return FALSE;
480 }
481
482 GSocketAddress *
483 g_socket_get_local_address (GSocket  *socket,
484                             GError  **error)
485 {
486   gchar buffer[256];
487   guint32 len = 256;
488
489   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
490
491   if (socket->priv->local_address)
492     return socket->priv->local_address;
493
494   if (getsockname (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
495     {
496       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get local address: %s", g_strerror (errno));
497       return NULL;
498     }
499
500   return (socket->priv->local_address = g_object_ref_sink (g_socket_address_from_native (buffer, len)));
501 }
502
503 GSocketAddress *
504 g_socket_get_remote_address (GSocket  *socket,
505                              GError  **error)
506 {
507   gchar buffer[256];
508   guint32 len = 256;
509
510   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
511
512   if (socket->priv->remote_address)
513     return socket->priv->remote_address;
514
515   if (getpeername (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
516     {
517       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get remote address: %s", g_strerror (errno));
518       return NULL;
519     }
520
521   return (socket->priv->remote_address = g_object_ref_sink (g_socket_address_from_native (buffer, len)));
522 }
523
524 gboolean
525 g_socket_has_error (GSocket  *socket,
526                     GError  **error)
527 {
528   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
529
530   if (!socket->priv->error)
531     return FALSE;
532
533   return TRUE;
534 }
535
536 gboolean
537 g_socket_listen (GSocket  *socket,
538                  GError  **error)
539 {
540   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
541
542   if (g_socket_has_error (socket, error))
543     return FALSE;
544
545   if (listen (socket->priv->fd, socket->priv->backlog) < 0)
546     {
547       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not listen: %s", g_strerror (errno));
548       return FALSE;
549     }
550
551   return TRUE;
552 }
553
554 gboolean
555 g_socket_bind (GSocket         *socket,
556                GSocketAddress  *address,
557                GError         **error)
558 {
559   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
560
561   if (g_socket_has_error (socket, error))
562     return FALSE;
563
564   {
565     gchar addr[256];
566
567     if (!g_socket_address_to_native (address, addr))
568       return FALSE;
569
570     if (bind (socket->priv->fd, (struct sockaddr *) addr, g_socket_address_native_size (address)) < 0)
571       {
572         g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error binding to address: %s", g_strerror (errno));
573         return FALSE;
574       }
575
576     g_object_ref_sink (address);
577
578     socket->priv->local_address = address;
579
580     return TRUE;
581   }
582 }
583
584 GSocket *
585 g_socket_accept (GSocket       *socket,
586                  GError       **error)
587 {
588   gint ret;
589
590   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
591
592   if (g_socket_has_error (socket, error))
593     return NULL;
594
595   if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
596     {
597       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error accepting connection: %s", g_strerror (errno));
598       return NULL;
599     }
600
601   return g_socket_new_from_fd (ret);
602 }
603
604 gboolean
605 g_socket_connect (GSocket         *socket,
606                   GSocketAddress  *address,
607                   GError         **error)
608 {
609   gchar buffer[256];
610
611   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
612
613   if (g_socket_has_error (socket, error))
614     return FALSE;
615
616   g_socket_address_to_native (address, buffer);
617
618   if (connect (socket->priv->fd, (struct sockaddr *) buffer, g_socket_address_native_size (address)) < 0)
619     {
620       if (errno == EINPROGRESS)
621         g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING, "connection in progress");
622       else
623         g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error connecting: %s", g_strerror (errno));
624       return FALSE;
625     }
626
627   socket->priv->remote_address = g_object_ref_sink (address);
628
629   return TRUE;
630 }
631
632 gssize
633 g_socket_receive (GSocket       *socket,
634                   gchar         *buffer,
635                   gsize          size,
636                   GError       **error)
637 {
638   gssize ret;
639
640   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
641
642   if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
643     {
644       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error receiving data: %s", g_strerror (errno));
645       return -1;
646     }
647
648   return ret;
649 }
650
651 gssize
652 g_socket_send (GSocket       *socket,
653                const gchar   *buffer,
654                gsize          size,
655                GError       **error)
656 {
657   gssize ret;
658
659   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
660
661   if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
662     {
663       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error sending data: %s", g_strerror (errno));
664       return -1;
665     }
666
667   return ret;
668 }
669
670 void
671 g_socket_close (GSocket *socket)
672 {
673   g_return_if_fail (G_IS_SOCKET (socket));
674
675 #ifdef G_OS_WIN32
676   closesocket (socket->priv->fd);
677 #else
678   close (socket->priv->fd);
679 #endif
680 }
681
682 GSource *
683 g_socket_create_source (GSocket      *socket,
684                         GIOCondition  condition,
685                         GCancellable *cancellable)
686 {
687   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
688
689   return _g_fd_source_new (socket->priv->fd, condition, cancellable);
690 }