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