Fix build on 64-bit systems
[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_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 gboolean
380 g_socket_has_socket_error (GSocket  *socket,
381                            GError  **error)
382 {
383   gint sockerr;
384   guint32 sockerr_size = sizeof (sockerr);
385
386   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
387
388   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (gpointer) &sockerr, &sockerr_size) < 0)
389     {
390       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get socket error: %s", g_strerror (errno));
391       return TRUE;
392     }
393
394   if (sockerr != 0)
395     {
396       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (sockerr), "error connecting: %s", g_strerror (sockerr));
397       return TRUE;
398     }
399
400   return FALSE;
401 }
402
403 GSocketAddress *
404 g_socket_get_local_address (GSocket  *socket,
405                             GError  **error)
406 {
407   gchar buffer[256];
408   guint32 len = 256;
409
410   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
411
412   if (socket->priv->local_address)
413     return socket->priv->local_address;
414
415   if (getsockname (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
416     {
417       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get local address: %s", g_strerror (errno));
418       return NULL;
419     }
420
421   return (socket->priv->local_address = g_object_ref_sink (g_socket_address_from_native (buffer, len)));
422 }
423
424 GSocketAddress *
425 g_socket_get_remote_address (GSocket  *socket,
426                              GError  **error)
427 {
428   gchar buffer[256];
429   guint32 len = 256;
430
431   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
432
433   if (socket->priv->remote_address)
434     return socket->priv->remote_address;
435
436   if (getpeername (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
437     {
438       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not get remote address: %s", g_strerror (errno));
439       return NULL;
440     }
441
442   return (socket->priv->remote_address = g_object_ref_sink (g_socket_address_from_native (buffer, len)));
443 }
444
445 gboolean
446 g_socket_listen (GSocket  *socket,
447                  GError  **error)
448 {
449   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
450
451   if (listen (socket->priv->fd, socket->priv->backlog) < 0)
452     {
453       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "could not listen: %s", g_strerror (errno));
454       return FALSE;
455     }
456
457   return TRUE;
458 }
459
460 gboolean
461 g_socket_bind (GSocket         *socket,
462                GSocketAddress  *address,
463                GError         **error)
464 {
465   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
466
467   {
468     gchar addr[256];
469
470     if (!g_socket_address_to_native (address, addr))
471       return FALSE;
472
473     if (bind (socket->priv->fd, (struct sockaddr *) addr, g_socket_address_native_size (address)) < 0)
474       {
475         g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error binding to address: %s", g_strerror (errno));
476         return FALSE;
477       }
478
479     g_object_ref_sink (address);
480
481     socket->priv->local_address = address;
482
483     return TRUE;
484   }
485 }
486
487 GSocket *
488 g_socket_accept (GSocket       *socket,
489                  GError       **error)
490 {
491   gint ret;
492
493   if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
494     {
495       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error accepting connection: %s", g_strerror (errno));
496       return NULL;
497     }
498
499   return g_socket_new_from_fd (ret);
500 }
501
502 gboolean
503 g_socket_connect (GSocket         *socket,
504                   GSocketAddress  *address,
505                   GError         **error)
506 {
507   gchar buffer[256];
508
509   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
510
511   g_socket_address_to_native (address, buffer);
512
513   if (connect (socket->priv->fd, (struct sockaddr *) buffer, g_socket_address_native_size (address)) < 0)
514     {
515       if (errno == EINPROGRESS)
516         g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING, "connection in progress");
517       else
518         g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error connecting: %s", g_strerror (errno));
519       return FALSE;
520     }
521
522   socket->priv->remote_address = g_object_ref_sink (address);
523
524   return TRUE;
525 }
526
527 gssize
528 g_socket_receive (GSocket       *socket,
529                   gchar         *buffer,
530                   gsize          size,
531                   GError       **error)
532 {
533   gssize ret;
534
535   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
536
537   if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
538     {
539       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error receiving data: %s", g_strerror (errno));
540       return -1;
541     }
542
543   return ret;
544 }
545
546 gssize
547 g_socket_send (GSocket       *socket,
548                const gchar   *buffer,
549                gsize          size,
550                GError       **error)
551 {
552   gssize ret;
553
554   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
555
556   if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
557     {
558       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "error sending data: %s", g_strerror (errno));
559       return -1;
560     }
561
562   return ret;
563 }
564
565 void
566 g_socket_close (GSocket *socket)
567 {
568   g_return_if_fail (G_IS_SOCKET (socket));
569
570 #ifdef G_OS_WIN32
571   closesocket (socket->priv->fd);
572 #else
573   close (socket->priv->fd);
574 #endif
575 }
576
577 GSource *
578 g_socket_create_source (GSocket      *socket,
579                         GIOCondition  condition,
580                         GCancellable *cancellable)
581 {
582   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
583
584   return _g_fd_source_new (socket->priv->fd, condition, cancellable);
585 }