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