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