Starting on TcpClient, some formatting fixes
[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
345 gboolean
346 g_socket_get_blocking (GSocket *socket)
347 {
348   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
349
350   return socket->priv->blocking;
351 }
352
353 void
354 g_socket_set_reuse_address (GSocket  *socket,
355                             gboolean  reuse)
356 {
357   gint value = (gint) reuse;
358
359   g_return_if_fail (G_IS_SOCKET (socket));
360
361   if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR, (gpointer) &value, sizeof (value)) < 0)
362     g_warning ("error setting reuse address: %s", g_strerror (errno));
363
364   socket->priv->reuse_address = reuse;
365 }
366
367 gboolean
368 g_socket_get_reuse_address (GSocket *socket)
369 {
370   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
371
372   return socket->priv->reuse_address;
373 }
374
375 GSocketAddress *
376 g_socket_get_local_address (GSocket  *socket,
377                             GError  **error)
378 {
379   gchar buffer[256];
380   gsize len = 256;
381
382   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
383
384   if (socket->priv->local_address)
385     return socket->priv->local_address;
386
387   if (getsockname (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
388     {
389       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get local address: %s", g_strerror (errno));
390       return NULL;
391     }
392
393   return (socket->priv->local_address = g_object_ref_sink (g_socket_address_from_native (buffer, len)));
394 }
395
396 GSocketAddress *
397 g_socket_get_remote_address (GSocket  *socket,
398                              GError  **error)
399 {
400   gchar buffer[256];
401   gsize len = 256;
402
403   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
404
405   if (socket->priv->remote_address)
406     return socket->priv->remote_address;
407
408   if (getpeername (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
409     {
410       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get remote address: %s", g_strerror (errno));
411       return NULL;
412     }
413
414   return (socket->priv->remote_address = g_object_ref_sink (g_socket_address_from_native (buffer, len)));
415 }
416
417 gboolean
418 g_socket_listen (GSocket  *socket,
419                  GError  **error)
420 {
421   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
422
423   if (listen (socket->priv->fd, socket->priv->backlog) < 0)
424     {
425       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not listen: %s", g_strerror (errno));
426       return FALSE;
427     }
428
429   return TRUE;
430 }
431
432 gboolean
433 g_socket_bind (GSocket         *socket,
434                GSocketAddress  *address,
435                GError         **error)
436 {
437   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
438
439   {
440     gchar addr[256];
441
442     if (!g_socket_address_to_native (address, addr))
443       return FALSE;
444
445     if (bind (socket->priv->fd, (struct sockaddr *) addr, g_socket_address_native_size (address)) < 0)
446       {
447         g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error binding to address: %s", g_strerror (errno));
448         return FALSE;
449       }
450
451     g_object_ref_sink (address);
452
453     socket->priv->local_address = address;
454
455     return TRUE;
456   }
457 }
458
459 GSocket *
460 g_socket_accept (GSocket       *socket,
461                  GError       **error)
462 {
463   gint ret;
464
465   if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
466     {
467       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error accepting connection: %s", g_strerror (errno));
468       return NULL;
469     }
470
471   return g_socket_new_from_fd (ret);
472 }
473
474 gboolean
475 g_socket_connect (GSocket         *socket,
476                   GSocketAddress  *address,
477                   GError         **error)
478 {
479   gchar buffer[256];
480
481   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
482
483   g_socket_address_to_native (address, buffer);
484
485   if (connect (socket->priv->fd, (struct sockaddr *) buffer, g_socket_address_native_size (address)) < 0)
486     {
487       if (errno == EINPROGRESS)
488         g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING, "connection in progress");
489       else
490         g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error connecting: %s", g_strerror (errno));
491       return FALSE;
492     }
493
494   socket->priv->remote_address = g_object_ref_sink (address);
495
496   return TRUE;
497 }
498
499 gssize
500 g_socket_receive (GSocket       *socket,
501                   gchar         *buffer,
502                   gsize          size,
503                   GError       **error)
504 {
505   gssize ret;
506
507   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
508
509   if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
510     {
511       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error receiving data: %s", g_strerror (errno));
512       return -1;
513     }
514
515   return ret;
516 }
517
518 gssize
519 g_socket_send (GSocket       *socket,
520                gchar         *buffer,
521                gsize          size,
522                GError       **error)
523 {
524   gssize ret;
525
526   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
527
528   if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
529     {
530       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error sending data: %s", g_strerror (errno));
531       return -1;
532     }
533
534   return ret;
535 }
536
537 void
538 g_socket_close (GSocket *socket)
539 {
540   g_return_if_fail (G_IS_SOCKET (socket));
541
542 #ifdef G_OS_WIN32
543   closesocket (socket->priv->fd);
544 #else
545   close (socket->priv->fd);
546 #endif
547 }
548
549 GSource *
550 g_socket_create_source (GSocket      *socket,
551                         GIOCondition  condition,
552                         GCancellable *cancellable)
553 {
554   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
555
556   return _g_fd_source_new (socket->priv->fd, G_IO_IN | G_IO_HUP | G_IO_ERR, cancellable);
557 }