Import GInitable, GSocket and dependencies from gnio
[platform/upstream/glib.git] / gio / gsocket.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4  * Copyright © 2009 Codethink Limited
5  * Copyright © 2009 Red Hat, Inc
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA 02111-1307, USA.
21  *
22  * Authors: Christian Kellner <gicmo@gnome.org>
23  *          Samuel Cormier-Iijima <sciyoshi@gmail.com>
24  *          Ryan Lortie <desrt@desrt.ca>
25  *          Alexander Larsson <alexl@redhat.com>
26  */
27
28 #include "config.h"
29
30 #include <errno.h>
31
32 #ifndef G_OS_WIN32
33 # include <netinet/in.h>
34 # include <arpa/inet.h>
35 # include <netdb.h>
36 # include <fcntl.h>
37 # include <unistd.h>
38 # include <sys/types.h>
39 #else
40 # include <winsock2.h>
41 # include <mswsock.h>
42 #endif
43
44 #include "gsocket.h"
45 #include "gcancellable.h"
46 #include "gioenumtypes.h"
47 #include "ginitable.h"
48 #include "gasynchelper.h"
49 #include "gioerror.h"
50 #include "gioenums.h"
51 #include "gioerror.h"
52 #include "glibintl.h"
53
54 #include "gioalias.h"
55
56 /**
57  * SECTION:gsocket
58  * @short_description: Low-level network socket handling
59  * @include: gio/gio.h
60  * @see_also: #GInitable
61  *
62  * A #GSocket is a low-level networking primitive. It is a more or less
63  * direct mapping of the BSD socket API in a portable GObject based API.
64  * It supports both the unix socket implementations and winsock2 on Windows.
65  *
66  * #GSocket is the platform independent base upon which the higher level
67  * network primitives are based. Applications are not typically meant to
68  * use it directly, but rather through classes like #GSocketClient, etc.
69  * However there may be cases where direct use of #GSocket is useful.
70  *
71  * TODO: Add more references to the highlevel API once that is more
72  * finalized.
73  *
74  * #GSocket implements the #GInitable interface, so if it is manually constructed
75  * by e.g. g_object_new() you must call g_initable_init() and check the
76  * results before using the object. This is done automatically in
77  * g_socket_new() and g_socket_new_from_fd(), so these functions can return
78  * %NULL.
79  *
80  * Sockets operate in two general modes, blocking or non-blocking. When
81  * in blocking mode all operations block until the requested operation
82  * is finished or there is an error. In non-blocking mode all calls that
83  * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
84  * To know when a call would successfully run you can call g_socket_condition_check(),
85  * or g_socket_condition_wait(). You can also use g_socket_create_source() and
86  * attach it to a #GMainContext to get callbacks when I/O is possible.
87  * Note that all sockets are always set to non blocking mode in the system, and
88  * blocking mode is emulated in GSocket.
89  *
90  * When working in non-blocking mode applications should always be able to
91  * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
92  * function said that I/O was possible. This can easily happen in case
93  * of a race condition in the application, but it can also happen for other
94  * reasons. For instance, on Windows a socket is always seen as writable
95  * until a write returns %G_IO_ERROR_WOULD_BLOCK.
96  *
97  * #GSocket<!-- -->s can be either connection oriented or datagram based.
98  * For connection oriented types you must first establish a connection by
99  * either connecting to an address or accepting a connection from another
100  * address. For connectionless socket types the target/source address is
101  * specified or received in each I/O operation.
102  *
103  * All socket file descriptors are set to be close-on-exec.
104  *
105  * Since: 2.22
106  **/
107
108 static void     g_socket_initable_iface_init (GInitableIface  *iface);
109 static gboolean g_socket_initable_init       (GInitable       *initable,
110                                               GCancellable    *cancellable,
111                                               GError         **error);
112
113 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
114                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
115                                                 g_socket_initable_iface_init));
116
117 enum
118 {
119   PROP_0,
120   PROP_FAMILY,
121   PROP_TYPE,
122   PROP_PROTOCOL,
123   PROP_FD,
124   PROP_BLOCKING,
125   PROP_LISTEN_BACKLOG,
126   PROP_KEEPALIVE,
127   PROP_LOCAL_ADDRESS,
128   PROP_REMOTE_ADDRESS
129 };
130
131 struct _GSocketPrivate
132 {
133   GSocketFamily   family;
134   GSocketType     type;
135   char           *protocol;
136   gint            fd;
137   gint            listen_backlog;
138   GError         *construct_error;
139   GSocketAddress *local_address;
140   GSocketAddress *remote_address;
141   guint           inited : 1;
142   guint           blocking : 1;
143   guint           keepalive : 1;
144   guint           closed : 1;
145 #ifdef G_OS_WIN32
146   WSAEVENT        event;
147   int             current_events;
148   int             current_errors;
149   int             selected_events;
150   GList          *requested_conditions; /* list of requested GIOCondition * */
151 #endif
152 };
153
154 static int
155 get_socket_errno (void)
156 {
157 #ifndef G_OS_WIN32
158   return errno;
159 #else
160   return WSAGetLastError ();
161 #endif
162 }
163
164 static GIOErrorEnum
165 socket_io_error_from_errno (int err)
166 {
167 #ifndef G_OS_WIN32
168   return g_io_error_from_errno (err);
169 #else
170   switch (err)
171     {
172     case WSAEADDRINUSE:
173       return G_IO_ERROR_ADDRESS_IN_USE;
174     case WSAEWOULDBLOCK:
175       return G_IO_ERROR_WOULD_BLOCK;
176     case WSAEACCES:
177       return G_IO_ERROR_PERMISSION_DENIED;
178     case WSA_INVALID_HANDLE:
179     case WSA_INVALID_PARAMETER:
180     case WSAEBADF:
181     case WSAENOTSOCK:
182       return G_IO_ERROR_INVALID_ARGUMENT;
183     case WSAEPROTONOSUPPORT:
184       return G_IO_ERROR_NOT_SUPPORTED;
185     case WSAECANCELLED:
186       return G_IO_ERROR_CANCELLED;
187     case WSAESOCKTNOSUPPORT:
188     case WSAEOPNOTSUPP:
189     case WSAEPFNOSUPPORT:
190     case WSAEAFNOSUPPORT:
191       return G_IO_ERROR_NOT_SUPPORTED;
192     default:
193       return G_IO_ERROR_FAILED;
194     }
195 #endif
196 }
197
198 static const char *
199 socket_strerror (int err)
200 {
201 #ifndef G_OS_WIN32
202   return g_strerror (err);
203 #else
204   static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
205   char *buf, *msg;
206
207   buf = g_static_private_get (&msg_private);
208   if (!buf)
209     {
210       buf = g_new (gchar, 128);
211       g_static_private_set (&msg_private, buf, g_free);
212     }
213
214   msg = g_win32_error_message (err);
215   strncpy (buf, msg, 128);
216   g_free (msg);
217   return buf;
218 #endif
219 }
220
221 #ifdef G_OS_WIN32
222 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
223 static void
224 _win32_unset_event_mask (GSocket *socket, int mask)
225 {
226   socket->priv->current_events &= ~mask;
227   socket->priv->current_errors &= ~mask;
228 }
229 #else
230 #define win32_unset_event_mask(_socket, _mask)
231 #endif
232
233 static void
234 set_fd_nonblocking (int fd)
235 {
236 #ifndef G_OS_WIN32
237   glong arg;
238 #else
239   gulong arg;
240 #endif
241
242 #ifndef G_OS_WIN32
243   if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
244     {
245       g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
246       arg = 0;
247     }
248
249   arg = arg | O_NONBLOCK;
250
251   if (fcntl (fd, F_SETFL, arg) < 0)
252       g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
253 #else
254   arg = TRUE;
255
256   if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
257     {
258       int errsv = get_socket_errno ();
259       g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
260     }
261 #endif
262 }
263
264 static gboolean
265 check_socket (GSocket *socket,
266               GError **error)
267 {
268   if (!socket->priv->inited)
269     {
270       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
271                    _("Invalid socket, not initialized"));
272       return FALSE;
273     }
274
275   if (socket->priv->construct_error)
276     {
277       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
278                    _("Invalid socket, initialization failed due to: %s"),
279                    socket->priv->construct_error->message);
280       return FALSE;
281     }
282
283   if (socket->priv->closed)
284     {
285       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
286                            _("Socket is already closed"));
287       return FALSE;
288     }
289   return TRUE;
290 }
291
292 static void
293 g_socket_details_from_fd (GSocket *socket)
294 {
295   struct sockaddr_storage address;
296   gint fd;
297   guint addrlen;
298   guint optlen;
299   int value;
300   int errsv;
301 #ifdef G_OS_WIN32
302   BOOL bool_val;
303 #else
304   int bool_val;
305 #endif
306
307   fd = socket->priv->fd;
308   optlen = sizeof value;
309   if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
310     {
311       errsv = get_socket_errno ();
312
313       switch (errsv)
314         {
315 #ifdef ENOTSOCK
316          case ENOTSOCK:
317 #endif
318 #ifdef WSAENOTSOCK
319          case WSAENOTSOCK:
320 #endif
321          case EBADF:
322           /* programmer error */
323           g_error ("creating GSocket from fd %d: %s\n",
324                    fd, socket_strerror (errsv));
325          default:
326            break;
327         }
328
329       goto err;
330     }
331
332   g_assert (optlen == sizeof value);
333   switch (value)
334     {
335      case SOCK_STREAM:
336       socket->priv->type = G_SOCKET_TYPE_STREAM;
337       break;
338
339      case SOCK_DGRAM:
340       socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
341       break;
342
343      case SOCK_SEQPACKET:
344       socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
345       break;
346
347      default:
348       socket->priv->type = G_SOCKET_TYPE_INVALID;
349       break;
350     }
351
352   addrlen = sizeof address;
353   if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
354     {
355       errsv = get_socket_errno ();
356       goto err;
357     }
358
359   g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
360             sizeof address.ss_family <= addrlen);
361   switch (address.ss_family)
362     {
363      case G_SOCKET_FAMILY_IPV4:
364      case G_SOCKET_FAMILY_IPV6:
365      case G_SOCKET_FAMILY_UNIX:
366       socket->priv->family = address.ss_family;
367       break;
368
369      default:
370       socket->priv->family = G_SOCKET_FAMILY_INVALID;
371       break;
372     }
373
374   if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
375     {
376       socket->priv->local_address =
377         g_socket_address_new_from_native (&address, addrlen);
378
379       addrlen = sizeof address;
380       if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
381         socket->priv->remote_address =
382           g_socket_address_new_from_native (&address, addrlen);
383     }
384
385   optlen = sizeof bool_val;
386   if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
387                   (void *)&bool_val, &optlen) == 0)
388     {
389       g_assert (optlen == sizeof bool_val);
390       socket->priv->keepalive = !!bool_val;
391     }
392   else
393     {
394       /* Can't read, maybe not supported, assume FALSE */
395       socket->priv->keepalive = FALSE;
396     }
397
398   return;
399
400  err:
401   g_set_error (&socket->priv->construct_error, G_IO_ERROR,
402                socket_io_error_from_errno (errsv),
403                _("creating GSocket from fd: %s"),
404                socket_strerror (errsv));
405 }
406
407 static gint
408 g_socket_create_socket (GSocketFamily   family,
409                         GSocketType     type,
410                         const char     *protocol_name,
411                         GError        **error)
412 {
413   gint native_type;
414   gint fd;
415   gint protocol;
416   struct protoent *protoent;
417
418   switch (type)
419     {
420      case G_SOCKET_TYPE_STREAM:
421       native_type = SOCK_STREAM;
422       break;
423
424      case G_SOCKET_TYPE_DATAGRAM:
425       native_type = SOCK_DGRAM;
426       break;
427
428      case G_SOCKET_TYPE_SEQPACKET:
429       native_type = SOCK_SEQPACKET;
430       break;
431
432      default:
433       g_assert_not_reached ();
434     }
435
436   protocol = 0;
437   if (protocol_name)
438     {
439 #ifdef HAVE_GETPROTOBYNAME_R
440       char buffer[1024];
441       struct protoent my_protoent;
442
443       protoent = NULL;
444       getprotobyname_r (protocol_name,
445                         &my_protoent, buffer, sizeof (buffer),
446                         &protoent);
447 #else
448       protoent = getprotobyname (protocol_name);
449 #endif
450       if (protoent == NULL)
451         {
452           g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
453                        _("unable to create socket: Protocol %s not supported"),
454                        protocol_name);
455           return -1;
456         }
457       protocol = protoent->p_proto;
458     }
459
460 #ifdef SOCK_CLOEXEC
461   native_type |= SOCK_CLOEXEC;
462 #endif
463   fd = socket (family, native_type, protocol);
464
465   if (fd < 0)
466     {
467       int errsv = get_socket_errno ();
468
469       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
470                    _("unable to create socket: %s"), socket_strerror (errsv));
471     }
472
473 #ifndef G_OS_WIN32
474   {
475     int flags;
476
477     /* We always want to set close-on-exec to protect users. If you
478        need to so some weird inheritance to exec you can re-enable this
479        using lower level hacks with g_socket_get_fd(). */
480     flags = fcntl (fd, F_GETFD, 0);
481     if (flags != -1 &&
482         (flags & FD_CLOEXEC) == 0)
483       {
484         flags |= FD_CLOEXEC;
485         fcntl (fd, F_SETFD, flags);
486       }
487   }
488 #endif
489
490   return fd;
491 }
492
493 static void
494 g_socket_constructed (GObject *object)
495 {
496   GSocket *socket = G_SOCKET (object);
497
498   if (socket->priv->fd >= 0)
499     /* create socket->priv info from the fd */
500     g_socket_details_from_fd (socket);
501
502   else
503     /* create the fd from socket->priv info */
504     socket->priv->fd = g_socket_create_socket (socket->priv->family,
505                                                socket->priv->type,
506                                                socket->priv->protocol,
507                                                &socket->priv->construct_error);
508
509   /* Always use native nonblocking sockets, as
510      windows sets sockets to nonblocking automatically
511      in certain operations. This way we make things work
512      the same on all platforms */
513   if (socket->priv->fd != -1)
514     set_fd_nonblocking (socket->priv->fd);
515 }
516
517 static void
518 g_socket_get_property (GObject    *object,
519                        guint       prop_id,
520                        GValue     *value,
521                        GParamSpec *pspec)
522 {
523   GSocket *socket = G_SOCKET (object);
524
525   switch (prop_id)
526     {
527       case PROP_FAMILY:
528         g_value_set_enum (value, socket->priv->family);
529         break;
530
531       case PROP_TYPE:
532         g_value_set_enum (value, socket->priv->type);
533         break;
534
535       case PROP_PROTOCOL:
536         g_value_set_string (value, socket->priv->protocol);
537         break;
538
539       case PROP_FD:
540         g_value_set_int (value, socket->priv->fd);
541         break;
542
543       case PROP_BLOCKING:
544         g_value_set_boolean (value, socket->priv->blocking);
545         break;
546
547       case PROP_LISTEN_BACKLOG:
548         g_value_set_int (value, socket->priv->listen_backlog);
549         break;
550
551       case PROP_KEEPALIVE:
552         g_value_set_boolean (value, socket->priv->keepalive);
553         break;
554
555       case PROP_LOCAL_ADDRESS:
556         g_value_set_object (value, socket->priv->local_address);
557         break;
558
559       case PROP_REMOTE_ADDRESS:
560         g_value_set_object (value, socket->priv->remote_address);
561         break;
562
563       default:
564         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
565     }
566 }
567
568 static void
569 g_socket_set_property (GObject      *object,
570                        guint         prop_id,
571                        const GValue *value,
572                        GParamSpec   *pspec)
573 {
574   GSocket *socket = G_SOCKET (object);
575
576   switch (prop_id)
577     {
578       case PROP_FAMILY:
579         socket->priv->family = g_value_get_enum (value);
580         break;
581
582       case PROP_TYPE:
583         socket->priv->type = g_value_get_enum (value);
584         break;
585
586       case PROP_PROTOCOL:
587         socket->priv->protocol = g_value_dup_string (value);
588         break;
589
590       case PROP_FD:
591         socket->priv->fd = g_value_get_int (value);
592         break;
593
594       case PROP_BLOCKING:
595         g_socket_set_blocking (socket, g_value_get_boolean (value));
596         break;
597
598       case PROP_LISTEN_BACKLOG:
599         g_socket_set_listen_backlog (socket, g_value_get_int (value));
600         break;
601
602       case PROP_KEEPALIVE:
603         g_socket_set_keepalive (socket, g_value_get_boolean (value));
604         break;
605
606       default:
607         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
608     }
609 }
610
611 static void
612 g_socket_finalize (GObject *object)
613 {
614   GSocket *socket = G_SOCKET (object);
615
616   g_clear_error (&socket->priv->construct_error);
617
618   if (socket->priv->fd != -1 &&
619       !socket->priv->closed)
620     g_socket_close (socket, NULL);
621
622   g_free (socket->priv->protocol);
623
624 #ifdef G_OS_WIN32
625   g_assert (socket->priv->requested_conditions == NULL);
626 #endif
627
628   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
629     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
630 }
631
632 static void
633 g_socket_dispose (GObject *object)
634 {
635   GSocket *socket = G_SOCKET (object);
636
637   if (socket->priv->local_address)
638     {
639       g_object_unref (socket->priv->local_address);
640       socket->priv->local_address = NULL;
641     }
642
643   if (socket->priv->remote_address)
644     {
645       g_object_unref (socket->priv->remote_address);
646       socket->priv->remote_address = NULL;
647     }
648
649   if (G_OBJECT_CLASS (g_socket_parent_class)->dispose)
650     (*G_OBJECT_CLASS (g_socket_parent_class)->dispose) (object);
651 }
652
653 static void
654 g_socket_class_init (GSocketClass *klass)
655 {
656   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
657   volatile GType type;
658
659   /* Make sure winsock has been initialized */
660   type = g_inet_address_get_type ();
661
662   g_type_class_add_private (klass, sizeof (GSocketPrivate));
663
664   gobject_class->finalize = g_socket_finalize;
665   gobject_class->dispose = g_socket_dispose;
666   gobject_class->constructed = g_socket_constructed;
667   gobject_class->set_property = g_socket_set_property;
668   gobject_class->get_property = g_socket_get_property;
669
670   g_object_class_install_property (gobject_class, PROP_FAMILY,
671                                    g_param_spec_enum ("family",
672                                                       P_("Socket family"),
673                                                       P_("The sockets address family"),
674                                                       G_TYPE_SOCKET_FAMILY,
675                                                       G_SOCKET_FAMILY_INVALID,
676                                                       G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
677
678   g_object_class_install_property (gobject_class, PROP_TYPE,
679                                    g_param_spec_enum ("type",
680                                                       P_("Socket type"),
681                                                       P_("The sockets type"),
682                                                       G_TYPE_SOCKET_TYPE,
683                                                       G_SOCKET_TYPE_STREAM,
684                                                       G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
685
686   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
687                                    g_param_spec_string ("protocol",
688                                                         P_("Socket protocol"),
689                                                         P_("The name of the protocol to use, or NULL"),
690                                                         NULL,
691                                                         G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
692
693   g_object_class_install_property (gobject_class, PROP_FD,
694                                    g_param_spec_int ("fd",
695                                                      P_("File descriptor"),
696                                                      P_("The sockets file descriptor"),
697                                                      G_MININT,
698                                                      G_MAXINT,
699                                                      -1,
700                                                      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
701
702   g_object_class_install_property (gobject_class, PROP_BLOCKING,
703                                    g_param_spec_boolean ("blocking",
704                                                          P_("blocking"),
705                                                          P_("Whether or not I/O on this socket is blocking"),
706                                                          TRUE,
707                                                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
708
709   g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
710                                    g_param_spec_int ("listen-backlog",
711                                                      P_("Listen backlog"),
712                                                      P_("outstanding connections in the listen queue"),
713                                                      0,
714                                                      SOMAXCONN,
715                                                      10,
716                                                      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
717
718   g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
719                                    g_param_spec_boolean ("keepalive",
720                                                          P_("Keep connection alive"),
721                                                          P_("Keep connection alive by sending periodic pings"),
722                                                          FALSE,
723                                                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
724
725   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
726                                    g_param_spec_object ("local-address",
727                                                         P_("Local address"),
728                                                         P_("The local address the socket is bound to"),
729                                                         G_TYPE_SOCKET_ADDRESS,
730                                                         G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
731
732   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
733                                    g_param_spec_object ("remote-address",
734                                                         P_("Remote address"),
735                                                         P_("The remote address the socket is connected to"),
736                                                         G_TYPE_SOCKET_ADDRESS,
737                                                         G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
738 }
739
740 static void
741 g_socket_initable_iface_init (GInitableIface *iface)
742 {
743   iface->init = g_socket_initable_init;
744 }
745
746 static void
747 g_socket_init (GSocket *socket)
748 {
749   socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
750
751   socket->priv->fd = -1;
752   socket->priv->blocking = TRUE;
753   socket->priv->listen_backlog = 10;
754   socket->priv->construct_error = NULL;
755   socket->priv->remote_address = NULL;
756   socket->priv->local_address = NULL;
757 #ifdef G_OS_WIN32
758   socket->priv->event = WSA_INVALID_EVENT;
759 #endif
760 }
761
762 static gboolean
763 g_socket_initable_init (GInitable *initable,
764                         GCancellable *cancellable,
765                         GError  **error)
766 {
767   GSocket  *socket;
768
769   g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
770
771   socket = G_SOCKET (initable);
772
773   if (cancellable != NULL)
774     {
775       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
776                    _("Cancellable initialization not supported"));
777       return FALSE;
778     }
779
780   socket->priv->inited = TRUE;
781
782   if (socket->priv->construct_error)
783     {
784       if (error)
785         *error = g_error_copy (socket->priv->construct_error);
786       return FALSE;
787     }
788
789
790   return TRUE;
791 }
792
793 /**
794  * g_socket_new:
795  * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
796  * @type: the socket type to use.
797  * @protocol: the name of the protocol to use, or %NULL.
798  * @error: #GError for error reporting, or %NULL to ignore.
799  *
800  * Creates a new #GSocket with the defined family, type and protocol.
801  * If @protocol is %NULL the default protocol type for the family and
802  * type is used.
803  *
804  * Returns: a #GSocket or %NULL on error.
805  *     Free the returned object with g_object_unref().
806  *
807  * Since: 2.22
808  **/
809 GSocket *
810 g_socket_new (GSocketFamily family,
811               GSocketType type,
812               const char *protocol,
813               GError **error)
814 {
815   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
816                                    NULL, error,
817                                    "family", family,
818                                    "type", type,
819                                    "protocol", protocol,
820                                    NULL));
821 }
822
823 /**
824  * g_socket_new_from_fd:
825  * @fd: a native socket file descriptor.
826  * @error: #GError for error reporting, or %NULL to ignore.
827  *
828  * Creates a new #GSocket from a native file descriptor
829  * or winsock SOCKET handle.
830  *
831  * This reads all the settings from the file descriptor so that
832  * all properties should work. Note that the file descriptor
833  * will be set to non-blocking mode, independent on the blocking
834  * mode of the #GSocket.
835  *
836  * Returns: a #GSocket or %NULL on error.
837  *     Free the returned object with g_object_unref().
838  *
839  * Since: 2.22
840  **/
841 GSocket *
842 g_socket_new_from_fd (gint fd,
843                       GError **error)
844 {
845   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
846                                    NULL, error,
847                                    "fd", fd,
848                                    NULL));
849 }
850
851 /**
852  * g_socket_set_blocking:
853  * @socket: a #GSocket.
854  * @blocking: Whether to use blocking I/O or not.
855  *
856  * Sets the blocking mode of the socket. In blocking mode
857  * all operations block until they succeed or there is an error. In
858  * non-blocking mode all functions return results immediately or
859  * with a %G_IO_ERROR_WOULD_BLOCK error.
860  *
861  * All sockets are created in blocking mode. However, note that the
862  * platform level socket is always non-blocking, and blocking mode
863  * is a GSocket level feature.
864  *
865  * Since: 2.22
866  **/
867 void
868 g_socket_set_blocking (GSocket  *socket,
869                        gboolean  blocking)
870 {
871   g_return_if_fail (G_IS_SOCKET (socket));
872
873   blocking = !!blocking;
874
875   if (socket->priv->blocking == blocking)
876     return;
877
878   socket->priv->blocking = blocking;
879   g_object_notify (G_OBJECT (socket), "blocking");
880 }
881
882 /**
883  * g_socket_get_blocking:
884  * @socket: a #GSocket.
885  *
886  * Gets the blocking mode of the socket. For details on blocking I/O,
887  * see g_socket_set_blocking().
888  *
889  * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
890  *
891  * Since: 2.22
892  **/
893 gboolean
894 g_socket_get_blocking (GSocket *socket)
895 {
896   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
897
898   return socket->priv->blocking;
899 }
900
901 /**
902  * g_socket_set_keepalive:
903  * @socket: a #GSocket.
904  * @keepalive: Whether to use try to keep the connection alive or not.
905  *
906  * Setting @keepalive to %TRUE enables the sending of periodic ping requests
907  * on idle connections in order to keep the connection alive. This is only
908  * useful for connection oriented sockets. The exact period used between
909  * each ping is system and protocol dependent.
910  *
911  * Sending keepalive requests like this has a few disadvantages. For instance,
912  * it uses more network bandwidth, and it makes your application more sensitive
913  * to temporary outages in the network (i.e. if a cable is pulled your otherwise
914  * idle connection could be terminated, whereas otherwise it would survive unless
915  * actually used before the cable was reinserted). However, it is sometimes
916  * useful to ensure that connections are eventually terminated if e.g. the
917  * remote side is disconnected, so as to avoid leaking resources forever.
918  *
919  * Since: 2.22
920  **/
921 void
922 g_socket_set_keepalive (GSocket *socket,
923                         gboolean keepalive)
924 {
925   int value;
926
927   g_return_if_fail (G_IS_SOCKET (socket));
928
929   keepalive = !!keepalive;
930   if (socket->priv->keepalive == keepalive)
931     return;
932
933   value = (gint) keepalive;
934   if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
935                   (gpointer) &value, sizeof (value)) < 0)
936     {
937       int errsv = get_socket_errno ();
938       g_warning ("error setting keepalive: %s", socket_strerror (errsv));
939       return;
940     }
941
942   socket->priv->keepalive = keepalive;
943   g_object_notify (G_OBJECT (socket), "keepalive");
944 }
945
946 /**
947  * g_socket_get_keepalive:
948  * @socket: a #GSocket.
949  *
950  * Gets the keepalive mode of the socket. For details on this,
951  * see g_socket_set_keepalive().
952  *
953  * Returns: %TRUE if keepalive is active, %FALSE otherwise.
954  *
955  * Since: 2.22
956  **/
957 gboolean
958 g_socket_get_keepalive (GSocket *socket)
959 {
960   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
961
962   return socket->priv->keepalive;
963 }
964
965 /**
966  * g_socket_get_listen_backlog:
967  * @socket: a #GSocket.
968  *
969  * Gets the listen backlog setting of the socket. For details on this,
970  * see g_socket_set_listen_backlog().
971  *
972  * Returns: the maximum number of pending connections.
973  *
974  * Since: 2.22
975  **/
976 gint
977 g_socket_get_listen_backlog  (GSocket                 *socket)
978 {
979   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
980
981   return socket->priv->listen_backlog;
982 }
983
984 /**
985  * g_socket_set_listen_backlog:
986  * @socket: a #GSocket.
987  * @backlog: the maximum number of pending connections.
988  *
989  * Sets the maximum number of outstanding connections allowed
990  * when listening on this socket. If more clients than this are
991  * connecting to the socket and the application is not handling them
992  * on time then the new connections will be refused.
993  *
994  * Since: 2.22
995  **/
996 void
997 g_socket_set_listen_backlog (GSocket *socket,
998                              gint backlog)
999 {
1000   g_return_if_fail (G_IS_SOCKET (socket));
1001
1002   if (backlog != socket->priv->listen_backlog)
1003     {
1004       socket->priv->listen_backlog = backlog;
1005       g_object_notify (G_OBJECT (socket), "listen-backlog");
1006     }
1007 }
1008
1009 /**
1010  * g_socket_get_family:
1011  * @socket: a #GSocket.
1012  *
1013  * Gets the socket family of the socket.
1014  *
1015  * Returns: a #GSocketFamily
1016  *
1017  * Since: 2.22
1018  **/
1019 GSocketFamily
1020 g_socket_get_family (GSocket *socket)
1021 {
1022   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1023
1024   return socket->priv->family;
1025 }
1026
1027 /**
1028  * g_socket_get_socket_type:
1029  * @socket: a #GSocket.
1030  *
1031  * Gets the socket type of the socket.
1032  *
1033  * Returns: a #GSocketType
1034  *
1035  * Since: 2.22
1036  **/
1037 GSocketType
1038 g_socket_get_socket_type (GSocket *socket)
1039 {
1040   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1041
1042   return socket->priv->type;
1043 }
1044
1045 /**
1046  * g_socket_get_protocol:
1047  * @socket: a #GSocket.
1048  *
1049  * Gets the socket protocol type name the socket was created with.
1050  * This can be %NULL if the socket was created with a NULL protocol.
1051  *
1052  * Returns: a string or %NULL, do not free
1053  *
1054  * Since: 2.22
1055  **/
1056 const char *
1057 g_socket_get_protocol (GSocket *socket)
1058 {
1059   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1060
1061   return socket->priv->protocol;
1062 }
1063
1064 /**
1065  * g_socket_get_fd:
1066  * @socket: a #GSocket.
1067  *
1068  * Returns the underlying OS socket object. On unix this
1069  * is a socket file descriptor, and on windows this is
1070  * a Winsock2 SOCKET handle. This may be useful for
1071  * doing platform specific or otherwise unusual operations
1072  * on the socket.
1073  *
1074  * Returns: the file descriptor of the socket.
1075  *
1076  * Since: 2.22
1077  **/
1078 int
1079 g_socket_get_fd (GSocket *socket)
1080 {
1081   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1082
1083   return socket->priv->fd;
1084 }
1085
1086 /**
1087  * g_socket_get_local_address:
1088  * @socket: a #GSocket.
1089  * @error: #GError for error reporting, or %NULL to ignore.
1090  *
1091  * Try to get the local address of a bound socket. This is only
1092  * useful if the socket has been bound to a local address.
1093  *
1094  * Returns: a #GSocketAddress or %NULL on error.
1095  *
1096  * Since: 2.22
1097  **/
1098 GSocketAddress *
1099 g_socket_get_local_address (GSocket  *socket,
1100                             GError  **error)
1101 {
1102   gchar buffer[256];
1103   guint32 len = 256;
1104
1105   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1106
1107   if (socket->priv->local_address)
1108     return socket->priv->local_address;
1109
1110   if (getsockname (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
1111     {
1112       int errsv = get_socket_errno ();
1113       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1114                    _("could not get local address: %s"), socket_strerror (errsv));
1115       return NULL;
1116     }
1117
1118   socket->priv->local_address = g_socket_address_new_from_native (buffer, len);
1119   return socket->priv->local_address;
1120 }
1121
1122 /**
1123  * g_socket_get_remote_address:
1124  * @socket: a #GSocket.
1125  * @error: #GError for error reporting, or %NULL to ignore.
1126  *
1127  * Try to get the remove address of a connected socket. This is only
1128  * useful for connection oriented sockets that have been connected.
1129  *
1130  * Returns: a #GSocketAddress or %NULL on error.
1131  *
1132  * Since: 2.22
1133  **/
1134 GSocketAddress *
1135 g_socket_get_remote_address (GSocket  *socket,
1136                              GError  **error)
1137 {
1138   gchar buffer[256];
1139   guint32 len = 256;
1140
1141   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1142
1143   if (socket->priv->remote_address)
1144     return socket->priv->remote_address;
1145
1146   if (getpeername (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
1147     {
1148       int errsv = get_socket_errno ();
1149       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1150                    _("could not get remote address: %s"), socket_strerror (errsv));
1151       return NULL;
1152     }
1153
1154   socket->priv->remote_address = g_socket_address_new_from_native (buffer, len);
1155   return socket->priv->remote_address;
1156 }
1157
1158 /**
1159  * g_socket_is_connected:
1160  * @socket: a #GSocket.
1161  *
1162  * Check whether the socket is connected. This is only useful for
1163  * connection-oriented sockets.
1164  *
1165  * Returns: %TRUE if socket is connected, %FALSE otherwise.
1166  *
1167  * Since: 2.22
1168  **/
1169 gboolean
1170 g_socket_is_connected (GSocket *socket)
1171 {
1172   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1173
1174   return socket->priv->remote_address != NULL;
1175 }
1176
1177 /**
1178  * g_socket_listen:
1179  * @socket: a #GSocket.
1180  * @error: #GError for error reporting, or %NULL to ignore.
1181  *
1182  * Marks the socket as a server socket, i.e. a socket that is used
1183  * to accept incoming requests using g_socket_accept().
1184  *
1185  * Before calling this the socket must be bound to a local address using
1186  * g_socket_bind().
1187  *
1188  * Returns: %TRUE on success, %FALSE on error.
1189  *
1190  * Since: 2.22
1191  **/
1192 gboolean
1193 g_socket_listen (GSocket  *socket,
1194                  GError  **error)
1195 {
1196   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1197
1198   if (!check_socket (socket, error))
1199     return FALSE;
1200
1201   if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1202     {
1203       int errsv = get_socket_errno ();
1204
1205       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1206                    _("could not listen: %s"), socket_strerror (errsv));
1207       return FALSE;
1208     }
1209
1210   return TRUE;
1211 }
1212
1213 /**
1214  * g_socket_bind:
1215  * @socket: a #GSocket.
1216  * @address: a #GSocketAddress specifying the local address.
1217  * @allow_reuse: whether to allow reusing this address
1218  * @error: #GError for error reporting, or %NULL to ignore.
1219  *
1220  * When a socket is created it is attached to an address family, but it
1221  * doesn't have an address in this family. g_socket_bind() assigns the
1222  * address (sometimes called name) of the socket.
1223  *
1224  * It is generally required to bind to a local address before you can
1225  * receive connections. (See g_socket_listen() and g_socket_accept() ).
1226  *
1227  * If @allow_reuse is %TRUE this allows the bind call to succeed in some
1228  * situation where it would otherwise return a %G_IO_ERROR_ADDRESS_IN_USE
1229  * error. The main example is for a TCP server socket where there are
1230  * outstanding connections in the WAIT state, which are generally safe
1231  * to ignore. However, setting it to %TRUE doesn't mean the call will
1232  * succeed if there is a socket actively bound to the address.
1233  *
1234  * In general, pass %TRUE if the socket will be used to accept connections,
1235  * otherwise pass %FALSE.
1236  *
1237  * Returns: %TRUE on success, %FALSE on error.
1238  *
1239  * Since: 2.22
1240  **/
1241 gboolean
1242 g_socket_bind (GSocket         *socket,
1243                GSocketAddress  *address,
1244                gboolean         reuse_address,
1245                GError         **error)
1246 {
1247   gchar addr[256];
1248   int value;
1249
1250   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1251
1252   if (!check_socket (socket, error))
1253     return FALSE;
1254
1255   /* SO_REUSEADDR on windows means something else and is not what we want.
1256      It always allows the unix variant of SO_REUSEADDR anyway */
1257 #ifndef G_OS_WIN32
1258   value = (int) !!reuse_address;
1259   if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1260                   (gpointer) &value, sizeof (value)) < 0)
1261     {
1262       int errsv = get_socket_errno ();
1263       g_set_error (error,
1264                    G_IO_ERROR, socket_io_error_from_errno (errsv),
1265                    _("Error setting reuse_address: %s"), socket_strerror (errsv));
1266       return FALSE;
1267     }
1268 #endif
1269
1270   if (!g_socket_address_to_native (address, addr, sizeof addr))
1271     return FALSE;
1272
1273   if (bind (socket->priv->fd, (struct sockaddr *) addr,
1274             g_socket_address_get_native_size (address)) < 0)
1275     {
1276       int errsv = get_socket_errno ();
1277       g_set_error (error,
1278                    G_IO_ERROR, socket_io_error_from_errno (errsv),
1279                    _("Error binding to address: %s"), socket_strerror (errsv));
1280       return FALSE;
1281     }
1282
1283   socket->priv->local_address = g_object_ref (address);
1284
1285   return TRUE;
1286 }
1287
1288 /**
1289  * g_socket_accept:
1290  * @socket: a #GSocket.
1291  * @error: #GError for error reporting, or %NULL to ignore.
1292  *
1293  * Accept incoming connections on a connection-based socket. This removes
1294  * the first outstanding connection request from the listening socket and
1295  * creates a #GSocket object for it.
1296  *
1297  * The @socket must be bound to a local address with g_socket_bind() and
1298  * must be listening for incoming connections (g_socket_listen()).
1299  *
1300  * If there are no outstanding connections then the operation will block
1301  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1302  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1303  *
1304  * Returns: a new #GSocket, or %NULL on error.
1305  *     Free the returned object with g_object_unref().
1306  *
1307  * Since: 2.22
1308  **/
1309 GSocket *
1310 g_socket_accept (GSocket       *socket,
1311                  GError       **error)
1312 {
1313   GSocket *new_socket;
1314   gint ret;
1315
1316   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1317
1318   if (!check_socket (socket, error))
1319     return NULL;
1320
1321   while (1)
1322     {
1323       if (socket->priv->blocking &&
1324           !g_socket_condition_wait (socket,
1325                                     G_IO_IN, NULL, error))
1326         return NULL;
1327
1328       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1329         {
1330           int errsv = get_socket_errno ();
1331
1332           win32_unset_event_mask (socket, FD_ACCEPT);
1333
1334           if (errsv == EINTR)
1335             continue;
1336
1337           if (socket->priv->blocking)
1338             {
1339 #ifdef WSAEWOULDBLOCK
1340               if (errsv == WSAEWOULDBLOCK)
1341                 continue;
1342 #else
1343               if (errsv == EWOULDBLOCK ||
1344                   errsv == EAGAIN)
1345                 continue;
1346 #endif
1347             }
1348
1349           g_set_error (error, G_IO_ERROR,
1350                        socket_io_error_from_errno (errsv),
1351                        _("Error accepting connection: %s"), socket_strerror (errsv));
1352           return NULL;
1353         }
1354       break;
1355     }
1356
1357   win32_unset_event_mask (socket, FD_ACCEPT);
1358
1359 #ifdef G_OS_WIN32
1360   {
1361     /* The socket inherits the accepting sockets event mask and even object,
1362        we need to remove that */
1363     WSAEventSelect (ret, NULL, 0);
1364   }
1365 #else
1366   {
1367     int flags;
1368
1369     /* We always want to set close-on-exec to protect users. If you
1370        need to so some weird inheritance to exec you can re-enable this
1371        using lower level hacks with g_socket_get_fd(). */
1372     flags = fcntl (ret, F_GETFD, 0);
1373     if (flags != -1 &&
1374         (flags & FD_CLOEXEC) == 0)
1375       {
1376         flags |= FD_CLOEXEC;
1377         fcntl (ret, F_SETFD, flags);
1378       }
1379   }
1380 #endif
1381
1382   new_socket = g_socket_new_from_fd (ret, error);
1383   if (new_socket == NULL)
1384     {
1385 #ifdef G_OS_WIN32
1386       closesocket (ret);
1387 #else
1388       close (ret);
1389 #endif
1390     }
1391
1392   return new_socket;
1393 }
1394
1395 /**
1396  * g_socket_connect:
1397  * @socket: a #GSocket.
1398  * @address: a #GSocketAddress specifying the remote address.
1399  * @error: #GError for error reporting, or %NULL to ignore.
1400  *
1401  * Connect the socket to the specified remote address.
1402  *
1403  * For connection oriented socket this generally means we attempt to make
1404  * a connection to the @address. For a connection-less socket it sets
1405  * the default address for g_socket_send() and discards all incoming datagrams
1406  * from other sources.
1407  *
1408  * Generally connection oriented sockets can only connect once, but connection-less
1409  * sockets can connect multiple times to change the default address.
1410  *
1411  * If the connect call needs to do network I/O it will block, unless
1412  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1413  * and the user can be notified of the connection finishing by waiting
1414  * for the G_IO_OUT condition. The result of the connection can then be
1415  * checked with g_socket_check_pending_error().
1416  *
1417  * Returns: %TRUE if connected, %FALSE on error.
1418  *
1419  * Since: 2.22
1420  **/
1421 gboolean
1422 g_socket_connect (GSocket         *socket,
1423                   GSocketAddress  *address,
1424                   GError         **error)
1425 {
1426   gchar buffer[256];
1427
1428   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1429
1430   if (!check_socket (socket, error))
1431     return FALSE;
1432
1433   g_socket_address_to_native (address, buffer, sizeof buffer);
1434
1435   while (1)
1436     {
1437       if (socket->priv->blocking &&
1438           !g_socket_condition_wait (socket,
1439                                     G_IO_IN, NULL, error))
1440         return FALSE;
1441
1442       if (connect (socket->priv->fd, (struct sockaddr *) buffer,
1443                    g_socket_address_get_native_size (address)) < 0)
1444         {
1445           int errsv = get_socket_errno ();
1446
1447           if (errsv == EINTR)
1448             continue;
1449
1450 #ifndef G_OS_WIN32
1451           if (errsv == EINPROGRESS)
1452 #else
1453           if (errsv == WSAEINPROGRESS)
1454 #endif
1455             {
1456               if (socket->priv->blocking)
1457                 {
1458                   g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1459                   if (g_socket_check_pending_error (socket, error))
1460                     break;
1461                   else
1462                     g_prefix_error (error, _("Error connecting: "));
1463                 }
1464               else
1465                 g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1466                              _("Connection in progress"));
1467             }
1468           else
1469             g_set_error (error, G_IO_ERROR,
1470                          socket_io_error_from_errno (errsv),
1471                          _("Error connecting: %s"), socket_strerror (errsv));
1472
1473           return FALSE;
1474         }
1475       break;
1476     }
1477
1478   win32_unset_event_mask (socket, FD_CONNECT);
1479
1480   socket->priv->remote_address = g_object_ref (address);
1481
1482   return TRUE;
1483 }
1484
1485 /**
1486  * g_socket_check_pending_error:
1487  * @socket: a #GSocket
1488  * @error: #GError for error reporting, or %NULL to ignore.
1489  *
1490  * Checks and resets the pending error for the socket. This is typically
1491  * used to check for errors when g_socket_connect() is used in non-blocking mode.
1492  *
1493  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1494  *
1495  * Since: 2.22
1496  **/
1497 gboolean
1498 g_socket_check_pending_error (GSocket  *socket,
1499                               GError  **error)
1500 {
1501   guint optlen;
1502   int value;
1503
1504   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1505     {
1506       int errsv = get_socket_errno ();
1507
1508       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1509                    _("Unable to get pending error: %s"), socket_strerror (errsv));
1510       return FALSE;
1511     }
1512
1513   if (value != 0)
1514     {
1515       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (value),
1516                    "%s", socket_strerror (value));
1517       return FALSE;
1518     }
1519   return TRUE;
1520 }
1521
1522 /**
1523  * g_socket_receive:
1524  * @socket: a #GSocket
1525  * @buffer: a buffer to read data into (which should be at least count bytes long).
1526  * @size: the number of bytes that will be read from the stream
1527  * @error: #GError for error reporting, or %NULL to ignore.
1528  *
1529  * Receive data (up to @size bytes) from a socket. This is mainly used by
1530  * connection oriented sockets, it is identical to g_socket_receive_from()
1531  * with @address set to %NULL.
1532  *
1533  * If a message is too long to fit in @buffer, excess bytes may be discarded
1534  * depending on the type of socket the message is received from.
1535  *
1536  * If the socket is in blocking mode the call will block until there is
1537  * some data to receive or there is an error. If there is no data available
1538  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1539  * will be returned. To be notified of available data, wait for the %G_IO_IN
1540  * condition.
1541  *
1542  * On error -1 is returned and @error is set accordingly.
1543  *
1544  * Returns: Number of bytes read, or -1 on error
1545  *
1546  * Since: 2.22
1547  **/
1548 gssize
1549 g_socket_receive (GSocket       *socket,
1550                   gchar         *buffer,
1551                   gsize          size,
1552                   GError       **error)
1553 {
1554   gssize ret;
1555
1556   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1557
1558   if (!check_socket (socket, error))
1559     return -1;
1560
1561   while (1)
1562     {
1563       if (socket->priv->blocking &&
1564           !g_socket_condition_wait (socket,
1565                                     G_IO_IN, NULL, error))
1566         return -1;
1567
1568       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1569         {
1570           int errsv = get_socket_errno ();
1571
1572           if (errsv == EINTR)
1573             continue;
1574
1575           if (socket->priv->blocking)
1576             {
1577 #ifdef WSAEWOULDBLOCK
1578               if (errsv == WSAEWOULDBLOCK)
1579                 continue;
1580 #else
1581               if (errsv == EWOULDBLOCK ||
1582                   errsv == EAGAIN)
1583                 continue;
1584 #endif
1585             }
1586
1587           win32_unset_event_mask (socket, FD_READ);
1588
1589           g_set_error (error, G_IO_ERROR,
1590                        socket_io_error_from_errno (errsv),
1591                        _("Error receiving data: %s"), socket_strerror (errsv));
1592           return -1;
1593         }
1594
1595       win32_unset_event_mask (socket, FD_READ);
1596
1597       break;
1598     }
1599
1600   return ret;
1601 }
1602
1603 /**
1604  * g_socket_receive_from:
1605  * @socket: a #GSocket
1606  * @address: a pointer to a #GSocketAddress pointer, or %NULL
1607  * @buffer: a buffer to read data into (which should be at least count bytes long).
1608  * @size: the number of bytes that will be read from the stream
1609  * @error: #GError for error reporting, or %NULL to ignore.
1610  *
1611  * Receive data (up to @size bytes) from a socket.
1612  *
1613  * If @address is non-%NULL then @address will be set equal to the
1614  * source address of the received packet.
1615  * @address is owned by the caller.
1616  *
1617  * If the socket is in blocking mode the call will block until there is
1618  * some data to receive or there is an error. If there is no data available
1619  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1620  * will be returned. To be notified of available data, wait for the %G_IO_IN
1621  * condition.
1622  *
1623  * On error -1 is returned and @error is set accordingly.
1624  *
1625  * Returns: Number of bytes read, or -1 on error
1626  *
1627  * Since: 2.22
1628  **/
1629 gssize
1630 g_socket_receive_from (GSocket       *socket,
1631                        GSocketAddress  **address,
1632                        gchar         *buffer,
1633                        gsize          size,
1634                        GError       **error)
1635 {
1636   GInputVector v;
1637
1638   v.buffer = buffer;
1639   v.size = size;
1640
1641   return g_socket_receive_message (socket,
1642                                    address,
1643                                    &v, 1,
1644                                    NULL, 0, NULL,
1645                                    error);
1646 }
1647
1648 /**
1649  * g_socket_send:
1650  * @socket: a #GSocket
1651  * @buffer: the buffer containing the data to send.
1652  * @size: the number of bytes to send
1653  * @error: #GError for error reporting, or %NULL to ignore.
1654  *
1655  * Tries to send @size bytes from @buffer on the socket. This is mainly used by
1656  * connection oriented sockets, it is identical to g_socket_send_to()
1657  * with @address set to %NULL.
1658  *
1659  * If the socket is in blocking mode the call will block until there is
1660  * space for the data in the socket queue. If there is no space available
1661  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1662  * will be returned. To be notified of available space, wait for the %G_IO_OUT
1663  * condition.
1664  *
1665  * Note that on Windows you can't rely on a %G_IO_OUT condition
1666  * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1667  * write notification works. However, robust apps should always be able to
1668  * handle this since it can easily appear in other cases too.
1669  *
1670  * On error -1 is returned and @error is set accordingly.
1671  *
1672  * Returns: Number of bytes read, or -1 on error
1673  *
1674  * Since: 2.22
1675  **/
1676 gssize
1677 g_socket_send (GSocket      *socket,
1678                const gchar  *buffer,
1679                gsize         size,
1680                GError      **error)
1681 {
1682   gssize ret;
1683
1684   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1685
1686   if (!check_socket (socket, error))
1687     return -1;
1688
1689   while (1)
1690     {
1691       if (socket->priv->blocking &&
1692           !g_socket_condition_wait (socket,
1693                                     G_IO_OUT, NULL, error))
1694         return -1;
1695
1696       if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1697         {
1698           int errsv = get_socket_errno ();
1699
1700           if (errsv == EINTR)
1701             continue;
1702
1703 #ifdef WSAEWOULDBLOCK
1704           if (errsv == WSAEWOULDBLOCK)
1705             win32_unset_event_mask (socket, FD_WRITE);
1706 #endif
1707
1708           if (socket->priv->blocking)
1709             {
1710 #ifdef WSAEWOULDBLOCK
1711               if (errsv == WSAEWOULDBLOCK)
1712                 continue;
1713 #else
1714               if (errsv == EWOULDBLOCK ||
1715                   errsv == EAGAIN)
1716                 continue;
1717 #endif
1718             }
1719
1720           g_set_error (error, G_IO_ERROR,
1721                        socket_io_error_from_errno (errsv),
1722                        _("Error sending data: %s"), socket_strerror (errsv));
1723           return -1;
1724         }
1725       break;
1726     }
1727
1728   return ret;
1729 }
1730
1731 /**
1732  * g_socket_send_to:
1733  * @socket: a #GSocket
1734  * @address: a #GSocketAddress, or %NULL
1735  * @buffer: the buffer containing the data to send.
1736  * @size: the number of bytes to send
1737  * @error: #GError for error reporting, or %NULL to ignore.
1738  *
1739  * Tries to send @size bytes from @buffer to @address. If @address is
1740  * %NULL then the message is sent to the default receiver (set by
1741  * g_socket_connect()).
1742  *
1743  * If the socket is in blocking mode the call will block until there is
1744  * space for the data in the socket queue. If there is no space available
1745  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1746  * will be returned. To be notified of available space, wait for the %G_IO_OUT
1747  * condition.
1748  *
1749  * Note that on Windows you can't rely on a %G_IO_OUT condition
1750  * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1751  * write notification works. However, robust apps should always be able to
1752  * handle this since it can easily appear in other cases too.
1753  *
1754  * On error -1 is returned and @error is set accordingly.
1755  *
1756  * Returns: Number of bytes read, or -1 on error
1757  *
1758  * Since: 2.22
1759  **/
1760 gssize
1761 g_socket_send_to (GSocket      *socket,
1762                   GSocketAddress *address,
1763                   const gchar  *buffer,
1764                   gsize         size,
1765                   GError      **error)
1766 {
1767   GOutputVector v;
1768
1769   v.buffer = buffer;
1770   v.size = size;
1771
1772   return g_socket_send_message (socket,
1773                                 address,
1774                                 &v, 1,
1775                                 NULL, 0,
1776                                 0, error);
1777 }
1778
1779 /**
1780  * g_socket_close:
1781  * @socket: a #GSocket
1782  * @error: #GError for error reporting, or %NULL to ignore.
1783  *
1784  * Closes the socket, shutting down any active connection.
1785  *
1786  * Closing a socket does not wait for all outstanding I/O operations to finish,
1787  * so the caller should not rely on them to be guaranteed to complete even
1788  * if the close returns with no error.
1789  *
1790  * Once the socket is closed, all other operations will return %G_IO_ERROR_CLOSED.
1791  * Closing a stream multiple times will not return an error.
1792  *
1793  * Sockets will be automatically closed when the last reference
1794  * is dropped, but you might want to call this function to make sure
1795  * resources are released as early as possible.
1796  *
1797  * Returns: %TRUE on success, %FALSE on error
1798  *
1799  * Since: 2.22
1800  **/
1801 gboolean
1802 g_socket_close (GSocket *socket,
1803                 GError **error)
1804 {
1805   int res;
1806
1807   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1808
1809   if (socket->priv->closed)
1810     return TRUE; /* Multiple close not an error */
1811
1812   if (!check_socket (socket, NULL))
1813     return FALSE;
1814
1815   while (1)
1816     {
1817 #ifdef G_OS_WIN32
1818       res = closesocket (socket->priv->fd);
1819 #else
1820       res = close (socket->priv->fd);
1821 #endif
1822       if (res == -1)
1823         {
1824           int errsv = get_socket_errno ();
1825
1826           if (errsv == EINTR)
1827             continue;
1828
1829           g_set_error (error, G_IO_ERROR,
1830                        socket_io_error_from_errno (errsv),
1831                        _("Error closing socket: %s"),
1832                        socket_strerror (errsv));
1833           return FALSE;
1834         }
1835       break;
1836     }
1837
1838 #ifdef G_OS_WIN32
1839   if (socket->priv->event != WSA_INVALID_EVENT)
1840     {
1841       WSACloseEvent (socket->priv->event);
1842       socket->priv->event = WSA_INVALID_EVENT;
1843     }
1844 #endif
1845
1846   socket->priv->closed = TRUE;
1847
1848   return TRUE;
1849 }
1850
1851 /**
1852  * g_socket_is_closed:
1853  * @socket: a #GSocket
1854  *
1855  * Checks whether a socket is closed.
1856  *
1857  * Returns: %TRUE if socket is closed, %FALSE otherwise
1858  *
1859  * Since: 2.22
1860  **/
1861 gboolean
1862 g_socket_is_closed (GSocket *socket)
1863 {
1864   return socket->priv->closed;
1865 }
1866
1867 #ifdef G_OS_WIN32
1868 /* Broken source, used on errors */
1869 static gboolean
1870 broken_prepare  (GSource  *source,
1871                  gint     *timeout)
1872 {
1873   return FALSE;
1874 }
1875
1876 static gboolean
1877 broken_check    (GSource  *source)
1878 {
1879   return FALSE;
1880 }
1881
1882 static gboolean
1883 broken_dispatch (GSource    *source,
1884                  GSourceFunc callback,
1885                  gpointer    user_data)
1886 {
1887   return TRUE;
1888 }
1889
1890 static GSourceFuncs broken_funcs =
1891 {
1892   broken_prepare,
1893   broken_check,
1894   broken_dispatch,
1895   NULL
1896 };
1897
1898 static gint
1899 network_events_for_condition (GIOCondition condition)
1900 {
1901   int event_mask = 0;
1902
1903   if (condition & G_IO_IN)
1904     event_mask |= (FD_READ | FD_ACCEPT);
1905   if (condition & G_IO_OUT)
1906     event_mask |= (FD_WRITE | FD_CONNECT);
1907   event_mask |= FD_CLOSE;
1908
1909   return event_mask;
1910 }
1911
1912 static void
1913 ensure_event (GSocket *socket)
1914 {
1915   if (socket->priv->event == WSA_INVALID_EVENT)
1916     socket->priv->event = WSACreateEvent();
1917 }
1918
1919 static void
1920 update_select_events (GSocket *socket)
1921 {
1922   int event_mask;
1923   GIOCondition *ptr;
1924   GList *l;
1925   WSAEVENT event;
1926
1927   ensure_event (socket);
1928
1929   event_mask = 0;
1930   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
1931     {
1932       ptr = l->data;
1933       event_mask |= network_events_for_condition (*ptr);
1934     }
1935
1936   if (event_mask != socket->priv->selected_events)
1937     {
1938       /* If no events selected, disable event so we can unset
1939          nonblocking mode */
1940
1941       if (event_mask == 0)
1942         event = NULL;
1943       else
1944         event = socket->priv->event;
1945
1946       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
1947         socket->priv->selected_events = event_mask;
1948     }
1949 }
1950
1951 static void
1952 add_condition_watch (GSocket *socket,
1953                      GIOCondition *condition)
1954 {
1955   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
1956
1957   socket->priv->requested_conditions =
1958     g_list_prepend (socket->priv->requested_conditions, condition);
1959
1960   update_select_events (socket);
1961 }
1962
1963 static void
1964 remove_condition_watch (GSocket *socket,
1965                         GIOCondition *condition)
1966 {
1967   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
1968
1969   socket->priv->requested_conditions =
1970     g_list_remove (socket->priv->requested_conditions, condition);
1971
1972   update_select_events (socket);
1973 }
1974
1975 static GIOCondition
1976 update_condition (GSocket *socket)
1977 {
1978   WSANETWORKEVENTS events;
1979   GIOCondition condition;
1980
1981   if (WSAEnumNetworkEvents (socket->priv->fd,
1982                             socket->priv->event,
1983                             &events) == 0)
1984     {
1985       socket->priv->current_events |= events.lNetworkEvents;
1986       if (events.lNetworkEvents & FD_WRITE &&
1987           events.iErrorCode[FD_WRITE_BIT] != 0)
1988         socket->priv->current_errors |= FD_WRITE;
1989       if (events.lNetworkEvents & FD_CONNECT &&
1990           events.iErrorCode[FD_CONNECT_BIT] != 0)
1991         socket->priv->current_errors |= FD_CONNECT;
1992     }
1993
1994   condition = 0;
1995   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
1996     condition |= G_IO_IN;
1997
1998   if (socket->priv->current_events & FD_CLOSE ||
1999       socket->priv->closed)
2000     condition |= G_IO_HUP;
2001
2002   /* Never report both G_IO_OUT and HUP, these are
2003      mutually exclusive (can't write to a closed socket) */
2004   if ((condition & G_IO_HUP) == 0 &&
2005       socket->priv->current_events & FD_WRITE)
2006     {
2007       if (socket->priv->current_errors & FD_WRITE)
2008         condition |= G_IO_ERR;
2009       else
2010         condition |= G_IO_OUT;
2011     }
2012   else
2013     {
2014       if (socket->priv->current_events & FD_CONNECT)
2015         {
2016           if (socket->priv->current_errors & FD_CONNECT)
2017             condition |= (G_IO_HUP | G_IO_ERR);
2018           else
2019             condition |= G_IO_OUT;
2020         }
2021     }
2022
2023   return condition;
2024 }
2025
2026 typedef struct {
2027   GSource       source;
2028   GPollFD       pollfd;
2029   GSocket      *socket;
2030   GIOCondition  condition;
2031   GCancellable *cancellable;
2032   GPollFD       cancel_pollfd;
2033   GIOCondition  result_condition;
2034 } GWinsockSource;
2035
2036 static gboolean
2037 winsock_prepare (GSource  *source,
2038                  gint     *timeout)
2039 {
2040   GWinsockSource *winsock_source = (GWinsockSource *)source;
2041   GIOCondition current_condition;
2042
2043   current_condition = update_condition (winsock_source->socket);
2044
2045   if (g_cancellable_is_cancelled (winsock_source->cancellable))
2046     {
2047       winsock_source->result_condition = current_condition;
2048       return TRUE;
2049     }
2050
2051   if ((winsock_source->condition & current_condition) != 0)
2052     {
2053       winsock_source->result_condition = current_condition;
2054       return TRUE;
2055     }
2056
2057   return FALSE;
2058 }
2059
2060 static gboolean
2061 winsock_check (GSource  *source)
2062 {
2063   GWinsockSource *winsock_source = (GWinsockSource *)source;
2064   GIOCondition current_condition;
2065
2066   current_condition = update_condition (winsock_source->socket);
2067
2068   if (g_cancellable_is_cancelled (winsock_source->cancellable))
2069     {
2070       winsock_source->result_condition = current_condition;
2071       return TRUE;
2072     }
2073
2074   if ((winsock_source->condition & current_condition) != 0)
2075     {
2076       winsock_source->result_condition = current_condition;
2077       return TRUE;
2078     }
2079
2080   return FALSE;
2081 }
2082
2083 static gboolean
2084 winsock_dispatch (GSource    *source,
2085                   GSourceFunc callback,
2086                   gpointer    user_data)
2087 {
2088   GSocketSourceFunc func = (GSocketSourceFunc)callback;
2089   GWinsockSource *winsock_source = (GWinsockSource *)source;
2090
2091   return (*func) (user_data,
2092                   winsock_source->result_condition & winsock_source->condition);
2093 }
2094
2095 static void
2096 winsock_finalize (GSource *source)
2097 {
2098   GWinsockSource *winsock_source = (GWinsockSource *)source;
2099   GSocket *socket;
2100
2101   socket = winsock_source->socket;
2102
2103   remove_condition_watch (socket, &winsock_source->condition);
2104   g_object_unref (socket);
2105
2106   if (winsock_source->cancellable)
2107     g_object_unref (winsock_source->cancellable);
2108 }
2109
2110 static GSourceFuncs winsock_funcs =
2111 {
2112   winsock_prepare,
2113   winsock_check,
2114   winsock_dispatch,
2115   winsock_finalize
2116 };
2117
2118 static GSource *
2119 winsock_source_new (GSocket      *socket,
2120                     GIOCondition  condition,
2121                     GCancellable *cancellable)
2122 {
2123   GSource *source;
2124   GWinsockSource *winsock_source;
2125
2126   ensure_event (socket);
2127
2128   if (socket->priv->event == WSA_INVALID_EVENT)
2129     {
2130       g_warning ("Failed to create WSAEvent");
2131       return g_source_new (&broken_funcs, sizeof (GSource));
2132     }
2133
2134   condition |= G_IO_HUP | G_IO_ERR;
2135
2136   source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2137   winsock_source = (GWinsockSource *)source;
2138
2139   winsock_source->socket = g_object_ref (socket);
2140   winsock_source->condition = condition;
2141   add_condition_watch (socket, &winsock_source->condition);
2142
2143   if (cancellable)
2144     {
2145       winsock_source->cancellable = g_object_ref (cancellable);
2146       g_cancellable_make_pollfd (cancellable,
2147                                  &winsock_source->cancel_pollfd);
2148       g_source_add_poll (source, &winsock_source->cancel_pollfd);
2149     }
2150
2151   winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2152   winsock_source->pollfd.events = condition;
2153   g_source_add_poll (source, &winsock_source->pollfd);
2154
2155   return source;
2156 }
2157 #endif
2158
2159 /**
2160  * g_socket_create_source:
2161  * @socket: a #GSocket
2162  * @condition: a #GIOCondition mask to monitor
2163  * @cancellable: a %GCancellable or %NULL
2164  *
2165  * Creates a %GSource that can be attached to a %GMainContext to monitor
2166  * for the availibility of the specified @condition on the socket.
2167  *
2168  * The callback on the source is of the #GSocketSourceFunc type.
2169  *
2170  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2171  * these conditions will always be reported output if they are true.
2172  *
2173  * @cancellable if not %NULL can be used to cancel the source, which will
2174  * cause the source to trigger, reporting the current condition. You can
2175  * check for this in the callback using g_cancellable_is_cancelled().
2176  *
2177  * Returns: a newly allocated %GSource, free with g_source_unref().
2178  *
2179  * Since: 2.22
2180  **/
2181 GSource *
2182 g_socket_create_source (GSocket      *socket,
2183                         GIOCondition  condition,
2184                         GCancellable *cancellable)
2185 {
2186   GSource *source;
2187   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2188
2189 #ifdef G_OS_WIN32
2190   source = winsock_source_new (socket, condition, cancellable);
2191 #else
2192   source =_g_fd_source_new (socket->priv->fd, condition, cancellable);
2193 #endif
2194   return source;
2195 }
2196
2197 /**
2198  * g_socket_condition_check:
2199  * @socket: a #GSocket
2200  * @condition: a #GIOCondition mask to check
2201  *
2202  * Checks on the readiness of @socket to perform operations.  The
2203  * operations specified in @condition are checked for and masked
2204  * against the currently-satisfied conditions on @socket.  The result
2205  * is returned.
2206  *
2207  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2208  * these conditions will always be set in the output if they are true.
2209  *
2210  * This call never blocks.
2211  *
2212  * Returns: the @GIOCondition mask of the current state
2213  *
2214  * Since: 2.22
2215  **/
2216 GIOCondition
2217 g_socket_condition_check (GSocket       *socket,
2218                           GIOCondition   condition)
2219 {
2220   if (!check_socket (socket, NULL))
2221     return 0;
2222
2223 #ifdef G_OS_WIN32
2224   {
2225     GIOCondition current_condition;
2226
2227     condition |= G_IO_ERR | G_IO_HUP;
2228
2229     add_condition_watch (socket, &condition);
2230     current_condition = update_condition (socket);
2231     remove_condition_watch (socket, &condition);
2232     return condition & current_condition;
2233   }
2234 #else
2235   {
2236     GPollFD poll_fd;
2237     gint result;
2238     poll_fd.fd = socket->priv->fd;
2239     poll_fd.events = condition;
2240
2241     do
2242       result = g_poll (&poll_fd, 1, 0);
2243     while (result == -1 && get_socket_errno () == EINTR);
2244
2245     return poll_fd.revents;
2246   }
2247 #endif
2248 }
2249
2250 /**
2251  * g_socket_condition_wait:
2252  * @socket: a #GSocket
2253  * @condition: a #GIOCondition mask to wait for
2254  * @cancellable: a #GCancellable, or %NULL
2255  * @error: a #GError pointer, or %NULL
2256  *
2257  * Waits for @condition to become true on @socket.  When the condition
2258  * becomes true, %TRUE is returned.
2259  *
2260  * If @cancellable is cancelled before the condition becomes true then
2261  * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2262  *
2263  * Returns: %TRUE if the condition was met, %FALSE otherwise
2264  *
2265  * Since: 2.22
2266  **/
2267 gboolean
2268 g_socket_condition_wait (GSocket       *socket,
2269                          GIOCondition   condition,
2270                          GCancellable  *cancellable,
2271                          GError       **error)
2272 {
2273   if (!check_socket (socket, error))
2274     return FALSE;
2275
2276   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2277     return FALSE;
2278
2279 #ifdef G_OS_WIN32
2280   {
2281     GIOCondition current_condition;
2282     WSAEVENT events[2];
2283     DWORD res;
2284     GPollFD cancel_fd;
2285     int num_events;
2286
2287     /* Always check these */
2288     condition |=  G_IO_ERR | G_IO_HUP;
2289
2290     add_condition_watch (socket, &condition);
2291
2292     num_events = 0;
2293     events[num_events++] = socket->priv->event;
2294
2295     if (cancellable)
2296       {
2297         g_cancellable_make_pollfd (cancellable, &cancel_fd);
2298         events[num_events++] = (WSAEVENT)cancel_fd.fd;
2299       }
2300
2301     current_condition = update_condition (socket);
2302     while ((condition & current_condition) == 0)
2303       {
2304         res = WSAWaitForMultipleEvents(num_events, events,
2305                                        FALSE, WSA_INFINITE, FALSE);
2306         if (res == WSA_WAIT_FAILED)
2307           {
2308             int errsv = get_socket_errno ();
2309
2310             g_set_error (error, G_IO_ERROR,
2311                          socket_io_error_from_errno (errsv),
2312                          _("Waiting for socket condition: %s"),
2313                          socket_strerror (errsv));
2314             break;
2315           }
2316
2317         if (g_cancellable_set_error_if_cancelled (cancellable, error))
2318           break;
2319
2320         current_condition = update_condition (socket);
2321       }
2322     remove_condition_watch (socket, &condition);
2323
2324     return (condition & current_condition) != 0;
2325   }
2326 #else
2327   {
2328     GPollFD poll_fd[2];
2329     gint result;
2330     gint num;
2331
2332     poll_fd[0].fd = socket->priv->fd;
2333     poll_fd[0].events = condition;
2334     num = 1;
2335
2336     if (cancellable)
2337       {
2338         g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2339         num++;
2340       }
2341
2342     do
2343       result = g_poll (poll_fd, num, -1);
2344     while (result == -1 && get_socket_errno () == EINTR);
2345
2346     return cancellable == NULL ||
2347       !g_cancellable_set_error_if_cancelled (cancellable, error);
2348   }
2349   #endif
2350 }
2351
2352 /**
2353  * g_socket_send_to:
2354  * @socket: a #GSocket
2355  * @address: a #GSocketAddress, or %NULL
2356  * @vectors: an array of #GOutputVector structs
2357  * @num_vectors: the number of elements in @vectors, or -1
2358  * @messages: a pointer to an array of #GSocketControlMessages, or
2359  *   %NULL.
2360  * @num_messages: number of elements in @messages, or -1.
2361  * @flags: an int containing #GSocketMsgFlags flags
2362  * @error: #GError for error reporting, or %NULL to ignore.
2363  *
2364  * Send data to @address on @socket.  This is the most complicated and
2365  * fully-featured version of this call. For easier use, see
2366  * g_socket_send() and g_socket_send_to().
2367  *
2368  * If @address is %NULL then the message is sent to the default receiver
2369  * (set by g_socket_connect()).
2370  *
2371  * @vector must point to an array of #GOutputVector structs and
2372  * @num_vectors must be the length of this array.  These structs
2373  * describe the buffers that the sent data will be gathered from.
2374  * If @num_vector is -1, then @vector is assumed to be terminated
2375  * by a #GOutputVector with a %NULL buffer pointer.
2376  *
2377  *
2378  * @messages, if non-%NULL, is taken to point to an array of @num_messages
2379  * #GSocketControlMessage instances. These correspond to the control
2380  * messages to be sent on the socket.
2381  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2382  * array.
2383  *
2384  * @flags modify how the message sent. The commonly available arguments
2385  * for this is available in the #GSocketMsgFlags enum, but the
2386  * values there are the same as the system values, and the flags
2387  * are passed in as-is, so you can pass in system specific flags too.
2388  *
2389  * If the socket is in blocking mode the call will block until there is
2390  * space for the data in the socket queue. If there is no space available
2391  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2392  * will be returned. To be notified of available space, wait for the %G_IO_OUT
2393  * condition.
2394  *
2395  * Note that on Windows you can't rely on a %G_IO_OUT condition
2396  * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2397  * write notification works. However, robust apps should always be able to
2398  * handle this since it can easily appear in other cases too.
2399  *
2400  * On error -1 is returned and @error is set accordingly.
2401  *
2402  * Returns: Number of bytes read, or -1 on error
2403  *
2404  * Since: 2.22
2405  **/
2406 gssize
2407 g_socket_send_message (GSocket                *socket,
2408                        GSocketAddress         *address,
2409                        GOutputVector          *vectors,
2410                        gint                    num_vectors,
2411                        GSocketControlMessage **messages,
2412                        gint                    num_messages,
2413                        gint                    flags,
2414                        GError                **error)
2415 {
2416   GOutputVector one_vector;
2417   char zero;
2418
2419   if (!check_socket (socket, error))
2420     return -1;
2421
2422   if (num_vectors == -1)
2423     {
2424       for (num_vectors = 0;
2425            vectors[num_vectors].buffer != NULL;
2426            num_vectors++)
2427         ;
2428     }
2429
2430   if (num_messages == -1)
2431     {
2432       for (num_messages = 0;
2433            messages != NULL && messages[num_messages] != NULL;
2434            num_messages++)
2435         ;
2436     }
2437
2438   if (num_vectors == 0)
2439     {
2440       zero = '\0';
2441
2442       one_vector.buffer = &zero;
2443       one_vector.size = 1;
2444       num_vectors = 1;
2445       vectors = &one_vector;
2446     }
2447
2448 #ifndef G_OS_WIN32
2449   {
2450     struct msghdr msg;
2451     gssize result;
2452
2453     /* name */
2454     if (address)
2455       {
2456         msg.msg_namelen = g_socket_address_get_native_size (address);
2457         msg.msg_name = g_alloca (msg.msg_namelen);
2458         g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen);
2459       }
2460
2461     /* iov */
2462     {
2463       /* this entire expression will be evaluated at compile time */
2464       if (sizeof *msg.msg_iov == sizeof *vectors &&
2465           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2466           G_STRUCT_OFFSET (struct iovec, iov_base) ==
2467           G_STRUCT_OFFSET (GOutputVector, buffer) &&
2468           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2469           G_STRUCT_OFFSET (struct iovec, iov_len) ==
2470           G_STRUCT_OFFSET (GOutputVector, size))
2471         /* ABI is compatible */
2472         {
2473           msg.msg_iov = (struct iovec *) vectors;
2474           msg.msg_iovlen = num_vectors;
2475         }
2476       else
2477         /* ABI is incompatible */
2478         {
2479           gint i;
2480
2481           msg.msg_iov = g_newa (struct iovec, num_vectors);
2482           for (i = 0; i < num_vectors; i++)
2483             {
2484               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2485               msg.msg_iov[i].iov_len = vectors[i].size;
2486             }
2487           msg.msg_iovlen = num_vectors;
2488         }
2489     }
2490
2491     /* control */
2492     {
2493       struct cmsghdr *cmsg;
2494       gint i;
2495
2496       msg.msg_controllen = 0;
2497       for (i = 0; i < num_messages; i++)
2498         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2499
2500       msg.msg_control = g_alloca (msg.msg_controllen);
2501
2502       cmsg = CMSG_FIRSTHDR (&msg);
2503       for (i = 0; i < num_messages; i++)
2504         {
2505           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2506           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2507           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2508           g_socket_control_message_serialize (messages[i],
2509                                               CMSG_DATA (cmsg));
2510           cmsg = CMSG_NXTHDR (&msg, cmsg);
2511         }
2512       g_assert (cmsg == NULL);
2513     }
2514
2515     while (1)
2516       {
2517         if (socket->priv->blocking &&
2518             !g_socket_condition_wait (socket,
2519                                       G_IO_OUT, NULL, error))
2520           return -1;
2521
2522         result = sendmsg (socket->priv->fd, &msg, flags);
2523         if (result < 0)
2524           {
2525             int errsv = get_socket_errno ();
2526
2527             if (errsv == EINTR)
2528               continue;
2529
2530             if (socket->priv->blocking &&
2531                 (errsv == EWOULDBLOCK ||
2532                  errsv == EAGAIN))
2533               continue;
2534
2535             g_set_error (error, G_IO_ERROR,
2536                          socket_io_error_from_errno (errsv),
2537                          _("Error sending message: %s"), socket_strerror (errsv));
2538
2539             return -1;
2540           }
2541         break;
2542       }
2543
2544     return result;
2545   }
2546 #else
2547   {
2548     struct sockaddr_storage addr;
2549     guint addrlen;
2550     DWORD bytes_sent;
2551     int result;
2552     WSABUF *bufs;
2553     gint i;
2554
2555     /* Win32 doesn't support control messages.
2556        Actually this is possible for raw and datagram sockets
2557        via WSASendMessage on Vista or later, but that doesn't
2558        seem very useful */
2559     if (num_messages != 0)
2560       {
2561         g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2562                      _("GSocketControlMessage not supported on windows"));
2563         return -1;
2564       }
2565
2566     /* iov */
2567     bufs = g_newa (WSABUF, num_vectors);
2568     for (i = 0; i < num_vectors; i++)
2569       {
2570         bufs[i].buf = (char *)vectors[i].buffer;
2571         bufs[i].len = (gulong)vectors[i].size;
2572       }
2573
2574     /* name */
2575     if (address)
2576       {
2577         addrlen = g_socket_address_get_native_size (address);
2578         g_socket_address_to_native (address, &addr, sizeof addr);
2579       }
2580
2581     while (1)
2582       {
2583         if (socket->priv->blocking &&
2584             !g_socket_condition_wait (socket,
2585                                       G_IO_OUT, NULL, error))
2586           return -1;
2587
2588         if (address)
2589           result = WSASendTo (socket->priv->fd,
2590                               bufs, num_vectors,
2591                               &bytes_sent, flags,
2592                               (const struct sockaddr *)&addr, addrlen,
2593                               NULL, NULL);
2594         else
2595           result = WSASend (socket->priv->fd,
2596                             bufs, num_vectors,
2597                             &bytes_sent, flags,
2598                             NULL, NULL);
2599
2600         if (result != 0)
2601           {
2602             int errsv = get_socket_errno ();
2603
2604             if (errsv == WSAEINTR)
2605               continue;
2606
2607             if (errsv == WSAEWOULDBLOCK)
2608               win32_unset_event_mask (socket, FD_WRITE);
2609
2610             if (socket->priv->blocking &&
2611                 errsv == WSAEWOULDBLOCK)
2612               continue;
2613
2614             g_set_error (error, G_IO_ERROR,
2615                          socket_io_error_from_errno (errsv),
2616                          _("Error sending message: %s"), socket_strerror (errsv));
2617
2618             return -1;
2619           }
2620         break;
2621       }
2622
2623     return bytes_sent;
2624   }
2625 #endif
2626 }
2627
2628 /**
2629  * g_socket_receive_message:
2630  * @socket: a #GSocket
2631  * @address: a pointer to a #GSocketAddress pointer, or %NULL
2632  * @vectors: an array of #GInputVector structs
2633  * @num_vectors: the number of elements in @vectors, or -1
2634  * @messages: a pointer which will be filled with an array of
2635  *     #GSocketControlMessages, or %NULL
2636  * @num_messages: a pointer which will be filled with the number of
2637  *    elements in @messages, or %NULL
2638  * @flags: a pointer to an int containing #GSocketMsgFlags flags
2639  * @error: a #GError pointer, or %NULL
2640  *
2641  * Receive data from a socket.  This is the most complicated and
2642  * fully-featured version of this call. For easier use, see
2643  * g_socket_receive() and g_socket_receive_from().
2644  *
2645  * If @address is non-%NULL then @address will be set equal to the
2646  * source address of the received packet.
2647  * @address is owned by the caller.
2648  *
2649  * @vector must point to an array of #GInputVector structs and
2650  * @num_vectors must be the length of this array.  These structs
2651  * describe the buffers that received data will be scattered into.
2652  * If @num_vector is -1, then @vector is assumed to be terminated
2653  * by a #GInputVector with a %NULL buffer pointer.
2654  *
2655  * As a special case, if the size of the array is zero (in which case,
2656  * @vectors may of course be %NULL), then a single byte is received
2657  * and discarded.  This is to facilitate the common practice of
2658  * sending a single '\0' byte for the purposes of transferring
2659  * ancillary data.
2660  *
2661  * @messages, if non-%NULL, is taken to point to a pointer that will
2662  * be set to point to a newly-allocated array of
2663  * #GSocketControlMessage instances.  These correspond to the control
2664  * messages received from the kernel, one #GSocketControlMessage per
2665  * message from the kernel.  This array is %NULL-terminated and must be
2666  * freed by the caller using g_free().
2667  *
2668  * @num_messages, if non-%NULL, will be set to the number of control
2669  * messages received.
2670  *
2671  * If both @messages and @num_messages are non-%NULL, then
2672  * @num_messages gives the number of #GSocketControlMessage instances
2673  * in @messages (ie: not including the %NULL terminator).
2674  *
2675  * @flags is an in/out parameter. The commonly available arguments
2676  * for this is available in the #GSocketMsgFlags enum, but the
2677  * values there are the same as the system values, and the flags
2678  * are passed in as-is, so you can pass in system specific flags too.
2679  *
2680  * If the socket is in blocking mode the call will block until there is
2681  * some data to receive or there is an error. If there is no data available
2682  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2683  * will be returned. To be notified of available data, wait for the %G_IO_IN
2684  * condition.
2685  *
2686  * On error -1 is returned and @error is set accordingly.
2687  *
2688  * Returns: Number of bytes read, or -1 on error
2689  *
2690  * Since: 2.22
2691  **/
2692 gssize
2693 g_socket_receive_message (GSocket                 *socket,
2694                           GSocketAddress         **address,
2695                           GInputVector            *vectors,
2696                           gint                     num_vectors,
2697                           GSocketControlMessage ***messages,
2698                           gint                    *num_messages,
2699                           gint                    *flags,
2700                           GError                 **error)
2701 {
2702   GInputVector one_vector;
2703   char one_byte;
2704
2705   if (!check_socket (socket, error))
2706     return -1;
2707
2708   if (num_vectors == -1)
2709     {
2710       for (num_vectors = 0;
2711            vectors[num_vectors].buffer != NULL;
2712            num_vectors++)
2713         ;
2714     }
2715
2716   if (num_vectors == 0)
2717     {
2718       one_vector.buffer = &one_byte;
2719       one_vector.size = 1;
2720       num_vectors = 1;
2721       vectors = &one_vector;
2722     }
2723
2724 #ifndef G_OS_WIN32
2725   {
2726     struct msghdr msg;
2727     gssize result;
2728     struct sockaddr_storage one_sockaddr;
2729
2730     /* name */
2731     if (address)
2732       {
2733         msg.msg_name = &one_sockaddr;
2734         msg.msg_namelen = sizeof (struct sockaddr_storage);
2735       }
2736     else
2737       {
2738         msg.msg_name = NULL;
2739         msg.msg_namelen = 0;
2740       }
2741
2742     /* iov */
2743     /* this entire expression will be evaluated at compile time */
2744     if (sizeof *msg.msg_iov == sizeof *vectors &&
2745         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2746         G_STRUCT_OFFSET (struct iovec, iov_base) ==
2747         G_STRUCT_OFFSET (GInputVector, buffer) &&
2748         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2749         G_STRUCT_OFFSET (struct iovec, iov_len) ==
2750         G_STRUCT_OFFSET (GInputVector, size))
2751       /* ABI is compatible */
2752       {
2753         msg.msg_iov = (struct iovec *) vectors;
2754         msg.msg_iovlen = num_vectors;
2755       }
2756     else
2757       /* ABI is incompatible */
2758       {
2759         gint i;
2760
2761         msg.msg_iov = g_newa (struct iovec, num_vectors);
2762         for (i = 0; i < num_vectors; i++)
2763           {
2764             msg.msg_iov[i].iov_base = vectors[i].buffer;
2765             msg.msg_iov[i].iov_len = vectors[i].size;
2766           }
2767         msg.msg_iovlen = num_vectors;
2768       }
2769
2770     /* control */
2771     msg.msg_control = g_alloca (2048);
2772     msg.msg_controllen = 2048;
2773
2774     /* flags */
2775     if (flags != NULL)
2776       msg.msg_flags = *flags;
2777     else
2778       msg.msg_flags = 0;
2779
2780     /* do it */
2781     while (1)
2782       {
2783         if (socket->priv->blocking &&
2784             !g_socket_condition_wait (socket,
2785                                       G_IO_IN, NULL, error))
2786           return -1;
2787
2788         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2789
2790         if (result < 0)
2791           {
2792             int errsv = get_socket_errno ();
2793
2794             if (errsv == EINTR)
2795               continue;
2796
2797             if (socket->priv->blocking &&
2798                 (errsv == EWOULDBLOCK ||
2799                  errsv == EAGAIN))
2800               continue;
2801
2802             g_set_error (error, G_IO_ERROR,
2803                          socket_io_error_from_errno (errsv),
2804                          _("Error receiving message: %s"), socket_strerror (errsv));
2805
2806             return -1;
2807           }
2808         break;
2809       }
2810
2811     /* decode address */
2812     if (address != NULL)
2813       {
2814         if (msg.msg_namelen > 0)
2815           *address = g_socket_address_new_from_native (msg.msg_name,
2816                                                        msg.msg_namelen);
2817         else
2818           *address = NULL;
2819       }
2820
2821     /* decode control messages */
2822     {
2823       GSocketControlMessage **my_messages = NULL;
2824       gint allocated = 0, index = 0;
2825       const gchar *scm_pointer;
2826       struct cmsghdr *cmsg;
2827       gsize scm_size;
2828
2829       scm_pointer = (const gchar *) msg.msg_control;
2830       scm_size = msg.msg_controllen;
2831
2832       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2833         {
2834           GSocketControlMessage *message;
2835
2836           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2837                                                           cmsg->cmsg_type,
2838                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2839                                                           CMSG_DATA (cmsg));
2840           if (message == NULL)
2841             /* We've already spewed about the problem in the
2842                deserialization code, so just continue */
2843             continue;
2844
2845           if (index == allocated)
2846             {
2847               /* estimated 99% case: exactly 1 control message */
2848               allocated = MIN (allocated * 2, 1);
2849               my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2850               allocated = 1;
2851             }
2852
2853           my_messages[index++] = message;
2854         }
2855
2856       if (num_messages)
2857         *num_messages = index;
2858
2859       if (messages)
2860         {
2861           my_messages[index++] = NULL;
2862           *messages = my_messages;
2863         }
2864       else
2865         {
2866           gint i;
2867
2868           /* free all those messages we just constructed.
2869            * we have to do it this way if the user ignores the
2870            * messages so that we will close any received fds.
2871            */
2872           for (i = 0; i < index; i++)
2873             g_object_unref (my_messages[i]);
2874           g_free (my_messages);
2875         }
2876     }
2877
2878     /* capture the flags */
2879     if (flags != NULL)
2880       *flags = msg.msg_flags;
2881
2882     return result;
2883   }
2884 #else
2885   {
2886     struct sockaddr_storage addr;
2887     int addrlen;
2888     DWORD bytes_received;
2889     DWORD win_flags;
2890     int result;
2891     WSABUF *bufs;
2892     gint i;
2893
2894     /* iov */
2895     bufs = g_newa (WSABUF, num_vectors);
2896     for (i = 0; i < num_vectors; i++)
2897       {
2898         bufs[i].buf = (char *)vectors[i].buffer;
2899         bufs[i].len = (gulong)vectors[i].size;
2900       }
2901
2902     /* flags */
2903     if (flags != NULL)
2904       win_flags = *flags;
2905     else
2906       win_flags = 0;
2907
2908     /* do it */
2909     while (1)
2910       {
2911         if (socket->priv->blocking &&
2912             !g_socket_condition_wait (socket,
2913                                       G_IO_IN, NULL, error))
2914           return -1;
2915
2916         addrlen = sizeof addr;
2917         if (address)
2918           result = WSARecvFrom (socket->priv->fd,
2919                                 bufs, num_vectors,
2920                                 &bytes_received, &win_flags,
2921                                 (struct sockaddr *)&addr, &addrlen,
2922                                 NULL, NULL);
2923         else
2924           result = WSARecv (socket->priv->fd,
2925                             bufs, num_vectors,
2926                             &bytes_received, &win_flags,
2927                             NULL, NULL);
2928         if (result != 0)
2929           {
2930             int errsv = get_socket_errno ();
2931
2932             if (errsv == WSAEINTR)
2933               continue;
2934
2935             win32_unset_event_mask (socket, FD_READ);
2936
2937             if (socket->priv->blocking &&
2938                 errsv == WSAEWOULDBLOCK)
2939               continue;
2940
2941             g_set_error (error, G_IO_ERROR,
2942                          socket_io_error_from_errno (errsv),
2943                          _("Error receiving message: %s"), socket_strerror (errsv));
2944
2945             return -1;
2946           }
2947         win32_unset_event_mask (socket, FD_READ);
2948         break;
2949       }
2950
2951     /* decode address */
2952     if (address != NULL)
2953       {
2954         if (addrlen > 0)
2955           *address = g_socket_address_new_from_native (&addr, addrlen);
2956         else
2957           *address = NULL;
2958       }
2959
2960     /* capture the flags */
2961     if (flags != NULL)
2962       *flags = win_flags;
2963
2964     return bytes_received;
2965   }
2966 #endif
2967 }
2968
2969 #define __G_SOCKET_C__
2970 #include "gioaliasdef.c"