Update docs on listen backlog
[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_pending_error().
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_pending_error (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_pending_error:
1548  * @socket: a #GSocket
1549  * @error: #GError for error reporting, or %NULL to ignore.
1550  *
1551  * Checks and resets the pending error for the socket. This is typically
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_pending_error (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_close:
1843  * @socket: a #GSocket
1844  * @error: #GError for error reporting, or %NULL to ignore.
1845  *
1846  * Closes the socket, shutting down any active connection.
1847  *
1848  * Closing a socket does not wait for all outstanding I/O operations to finish,
1849  * so the caller should not rely on them to be guaranteed to complete even
1850  * if the close returns with no error.
1851  *
1852  * Once the socket is closed, all other operations will return %G_IO_ERROR_CLOSED.
1853  * Closing a stream multiple times will not return an error.
1854  *
1855  * Sockets will be automatically closed when the last reference
1856  * is dropped, but you might want to call this function to make sure
1857  * resources are released as early as possible.
1858  *
1859  * Returns: %TRUE on success, %FALSE on error
1860  *
1861  * Since: 2.22
1862  **/
1863 gboolean
1864 g_socket_close (GSocket *socket,
1865                 GError **error)
1866 {
1867   int res;
1868
1869   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1870
1871   if (socket->priv->closed)
1872     return TRUE; /* Multiple close not an error */
1873
1874   if (!check_socket (socket, NULL))
1875     return FALSE;
1876
1877   while (1)
1878     {
1879 #ifdef G_OS_WIN32
1880       res = closesocket (socket->priv->fd);
1881 #else
1882       res = close (socket->priv->fd);
1883 #endif
1884       if (res == -1)
1885         {
1886           int errsv = get_socket_errno ();
1887
1888           if (errsv == EINTR)
1889             continue;
1890
1891           g_set_error (error, G_IO_ERROR,
1892                        socket_io_error_from_errno (errsv),
1893                        _("Error closing socket: %s"),
1894                        socket_strerror (errsv));
1895           return FALSE;
1896         }
1897       break;
1898     }
1899
1900 #ifdef G_OS_WIN32
1901   if (socket->priv->event != WSA_INVALID_EVENT)
1902     {
1903       WSACloseEvent (socket->priv->event);
1904       socket->priv->event = WSA_INVALID_EVENT;
1905     }
1906 #endif
1907
1908   socket->priv->connected = FALSE;
1909   socket->priv->closed = TRUE;
1910
1911   return TRUE;
1912 }
1913
1914 /**
1915  * g_socket_is_closed:
1916  * @socket: a #GSocket
1917  *
1918  * Checks whether a socket is closed.
1919  *
1920  * Returns: %TRUE if socket is closed, %FALSE otherwise
1921  *
1922  * Since: 2.22
1923  **/
1924 gboolean
1925 g_socket_is_closed (GSocket *socket)
1926 {
1927   return socket->priv->closed;
1928 }
1929
1930 #ifdef G_OS_WIN32
1931 /* Broken source, used on errors */
1932 static gboolean
1933 broken_prepare  (GSource  *source,
1934                  gint     *timeout)
1935 {
1936   return FALSE;
1937 }
1938
1939 static gboolean
1940 broken_check    (GSource  *source)
1941 {
1942   return FALSE;
1943 }
1944
1945 static gboolean
1946 broken_dispatch (GSource    *source,
1947                  GSourceFunc callback,
1948                  gpointer    user_data)
1949 {
1950   return TRUE;
1951 }
1952
1953 static GSourceFuncs broken_funcs =
1954 {
1955   broken_prepare,
1956   broken_check,
1957   broken_dispatch,
1958   NULL
1959 };
1960
1961 static gint
1962 network_events_for_condition (GIOCondition condition)
1963 {
1964   int event_mask = 0;
1965
1966   if (condition & G_IO_IN)
1967     event_mask |= (FD_READ | FD_ACCEPT);
1968   if (condition & G_IO_OUT)
1969     event_mask |= (FD_WRITE | FD_CONNECT);
1970   event_mask |= FD_CLOSE;
1971
1972   return event_mask;
1973 }
1974
1975 static void
1976 ensure_event (GSocket *socket)
1977 {
1978   if (socket->priv->event == WSA_INVALID_EVENT)
1979     socket->priv->event = WSACreateEvent();
1980 }
1981
1982 static void
1983 update_select_events (GSocket *socket)
1984 {
1985   int event_mask;
1986   GIOCondition *ptr;
1987   GList *l;
1988   WSAEVENT event;
1989
1990   ensure_event (socket);
1991
1992   event_mask = 0;
1993   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
1994     {
1995       ptr = l->data;
1996       event_mask |= network_events_for_condition (*ptr);
1997     }
1998
1999   if (event_mask != socket->priv->selected_events)
2000     {
2001       /* If no events selected, disable event so we can unset
2002          nonblocking mode */
2003
2004       if (event_mask == 0)
2005         event = NULL;
2006       else
2007         event = socket->priv->event;
2008
2009       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2010         socket->priv->selected_events = event_mask;
2011     }
2012 }
2013
2014 static void
2015 add_condition_watch (GSocket *socket,
2016                      GIOCondition *condition)
2017 {
2018   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2019
2020   socket->priv->requested_conditions =
2021     g_list_prepend (socket->priv->requested_conditions, condition);
2022
2023   update_select_events (socket);
2024 }
2025
2026 static void
2027 remove_condition_watch (GSocket *socket,
2028                         GIOCondition *condition)
2029 {
2030   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2031
2032   socket->priv->requested_conditions =
2033     g_list_remove (socket->priv->requested_conditions, condition);
2034
2035   update_select_events (socket);
2036 }
2037
2038 static GIOCondition
2039 update_condition (GSocket *socket)
2040 {
2041   WSANETWORKEVENTS events;
2042   GIOCondition condition;
2043
2044   if (WSAEnumNetworkEvents (socket->priv->fd,
2045                             socket->priv->event,
2046                             &events) == 0)
2047     {
2048       socket->priv->current_events |= events.lNetworkEvents;
2049       if (events.lNetworkEvents & FD_WRITE &&
2050           events.iErrorCode[FD_WRITE_BIT] != 0)
2051         socket->priv->current_errors |= FD_WRITE;
2052       if (events.lNetworkEvents & FD_CONNECT &&
2053           events.iErrorCode[FD_CONNECT_BIT] != 0)
2054         socket->priv->current_errors |= FD_CONNECT;
2055     }
2056
2057   condition = 0;
2058   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2059     condition |= G_IO_IN;
2060
2061   if (socket->priv->current_events & FD_CLOSE ||
2062       socket->priv->closed)
2063     condition |= G_IO_HUP;
2064
2065   /* Never report both G_IO_OUT and HUP, these are
2066      mutually exclusive (can't write to a closed socket) */
2067   if ((condition & G_IO_HUP) == 0 &&
2068       socket->priv->current_events & FD_WRITE)
2069     {
2070       if (socket->priv->current_errors & FD_WRITE)
2071         condition |= G_IO_ERR;
2072       else
2073         condition |= G_IO_OUT;
2074     }
2075   else
2076     {
2077       if (socket->priv->current_events & FD_CONNECT)
2078         {
2079           if (socket->priv->current_errors & FD_CONNECT)
2080             condition |= (G_IO_HUP | G_IO_ERR);
2081           else
2082             condition |= G_IO_OUT;
2083         }
2084     }
2085
2086   return condition;
2087 }
2088
2089 typedef struct {
2090   GSource       source;
2091   GPollFD       pollfd;
2092   GSocket      *socket;
2093   GIOCondition  condition;
2094   GCancellable *cancellable;
2095   GPollFD       cancel_pollfd;
2096   GIOCondition  result_condition;
2097 } GWinsockSource;
2098
2099 static gboolean
2100 winsock_prepare (GSource  *source,
2101                  gint     *timeout)
2102 {
2103   GWinsockSource *winsock_source = (GWinsockSource *)source;
2104   GIOCondition current_condition;
2105
2106   current_condition = update_condition (winsock_source->socket);
2107
2108   if (g_cancellable_is_cancelled (winsock_source->cancellable))
2109     {
2110       winsock_source->result_condition = current_condition;
2111       return TRUE;
2112     }
2113
2114   if ((winsock_source->condition & current_condition) != 0)
2115     {
2116       winsock_source->result_condition = current_condition;
2117       return TRUE;
2118     }
2119
2120   return FALSE;
2121 }
2122
2123 static gboolean
2124 winsock_check (GSource  *source)
2125 {
2126   GWinsockSource *winsock_source = (GWinsockSource *)source;
2127   GIOCondition current_condition;
2128
2129   current_condition = update_condition (winsock_source->socket);
2130
2131   if (g_cancellable_is_cancelled (winsock_source->cancellable))
2132     {
2133       winsock_source->result_condition = current_condition;
2134       return TRUE;
2135     }
2136
2137   if ((winsock_source->condition & current_condition) != 0)
2138     {
2139       winsock_source->result_condition = current_condition;
2140       return TRUE;
2141     }
2142
2143   return FALSE;
2144 }
2145
2146 static gboolean
2147 winsock_dispatch (GSource    *source,
2148                   GSourceFunc callback,
2149                   gpointer    user_data)
2150 {
2151   GSocketSourceFunc func = (GSocketSourceFunc)callback;
2152   GWinsockSource *winsock_source = (GWinsockSource *)source;
2153
2154   return (*func) (winsock_source->socket,
2155                   winsock_source->result_condition & winsock_source->condition,
2156                   user_data);
2157 }
2158
2159 static void
2160 winsock_finalize (GSource *source)
2161 {
2162   GWinsockSource *winsock_source = (GWinsockSource *)source;
2163   GSocket *socket;
2164
2165   socket = winsock_source->socket;
2166
2167   remove_condition_watch (socket, &winsock_source->condition);
2168   g_object_unref (socket);
2169
2170   if (winsock_source->cancellable)
2171     g_object_unref (winsock_source->cancellable);
2172 }
2173
2174 static GSourceFuncs winsock_funcs =
2175 {
2176   winsock_prepare,
2177   winsock_check,
2178   winsock_dispatch,
2179   winsock_finalize
2180 };
2181
2182 static GSource *
2183 winsock_source_new (GSocket      *socket,
2184                     GIOCondition  condition,
2185                     GCancellable *cancellable)
2186 {
2187   GSource *source;
2188   GWinsockSource *winsock_source;
2189
2190   ensure_event (socket);
2191
2192   if (socket->priv->event == WSA_INVALID_EVENT)
2193     {
2194       g_warning ("Failed to create WSAEvent");
2195       return g_source_new (&broken_funcs, sizeof (GSource));
2196     }
2197
2198   condition |= G_IO_HUP | G_IO_ERR;
2199
2200   source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2201   winsock_source = (GWinsockSource *)source;
2202
2203   winsock_source->socket = g_object_ref (socket);
2204   winsock_source->condition = condition;
2205   add_condition_watch (socket, &winsock_source->condition);
2206
2207   if (cancellable)
2208     {
2209       winsock_source->cancellable = g_object_ref (cancellable);
2210       g_cancellable_make_pollfd (cancellable,
2211                                  &winsock_source->cancel_pollfd);
2212       g_source_add_poll (source, &winsock_source->cancel_pollfd);
2213     }
2214
2215   winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2216   winsock_source->pollfd.events = condition;
2217   g_source_add_poll (source, &winsock_source->pollfd);
2218
2219   return source;
2220 }
2221 #endif
2222
2223 /**
2224  * g_socket_create_source:
2225  * @socket: a #GSocket
2226  * @condition: a #GIOCondition mask to monitor
2227  * @cancellable: a %GCancellable or %NULL
2228  *
2229  * Creates a %GSource that can be attached to a %GMainContext to monitor
2230  * for the availibility of the specified @condition on the socket.
2231  *
2232  * The callback on the source is of the #GSocketSourceFunc type.
2233  *
2234  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2235  * these conditions will always be reported output if they are true.
2236  *
2237  * @cancellable if not %NULL can be used to cancel the source, which will
2238  * cause the source to trigger, reporting the current condition. You can
2239  * check for this in the callback using g_cancellable_is_cancelled().
2240  *
2241  * Returns: a newly allocated %GSource, free with g_source_unref().
2242  *
2243  * Since: 2.22
2244  **/
2245 GSource *
2246 g_socket_create_source (GSocket      *socket,
2247                         GIOCondition  condition,
2248                         GCancellable *cancellable)
2249 {
2250   GSource *source;
2251   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2252
2253 #ifdef G_OS_WIN32
2254   source = winsock_source_new (socket, condition, cancellable);
2255 #else
2256   source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2257                                         condition, cancellable);
2258 #endif
2259   return source;
2260 }
2261
2262 /**
2263  * g_socket_condition_check:
2264  * @socket: a #GSocket
2265  * @condition: a #GIOCondition mask to check
2266  *
2267  * Checks on the readiness of @socket to perform operations.  The
2268  * operations specified in @condition are checked for and masked
2269  * against the currently-satisfied conditions on @socket.  The result
2270  * is returned.
2271  *
2272  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2273  * these conditions will always be set in the output if they are true.
2274  *
2275  * This call never blocks.
2276  *
2277  * Returns: the @GIOCondition mask of the current state
2278  *
2279  * Since: 2.22
2280  **/
2281 GIOCondition
2282 g_socket_condition_check (GSocket       *socket,
2283                           GIOCondition   condition)
2284 {
2285   if (!check_socket (socket, NULL))
2286     return 0;
2287
2288 #ifdef G_OS_WIN32
2289   {
2290     GIOCondition current_condition;
2291
2292     condition |= G_IO_ERR | G_IO_HUP;
2293
2294     add_condition_watch (socket, &condition);
2295     current_condition = update_condition (socket);
2296     remove_condition_watch (socket, &condition);
2297     return condition & current_condition;
2298   }
2299 #else
2300   {
2301     GPollFD poll_fd;
2302     gint result;
2303     poll_fd.fd = socket->priv->fd;
2304     poll_fd.events = condition;
2305
2306     do
2307       result = g_poll (&poll_fd, 1, 0);
2308     while (result == -1 && get_socket_errno () == EINTR);
2309
2310     return poll_fd.revents;
2311   }
2312 #endif
2313 }
2314
2315 /**
2316  * g_socket_condition_wait:
2317  * @socket: a #GSocket
2318  * @condition: a #GIOCondition mask to wait for
2319  * @cancellable: a #GCancellable, or %NULL
2320  * @error: a #GError pointer, or %NULL
2321  *
2322  * Waits for @condition to become true on @socket.  When the condition
2323  * becomes true, %TRUE is returned.
2324  *
2325  * If @cancellable is cancelled before the condition becomes true then
2326  * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2327  *
2328  * Returns: %TRUE if the condition was met, %FALSE otherwise
2329  *
2330  * Since: 2.22
2331  **/
2332 gboolean
2333 g_socket_condition_wait (GSocket       *socket,
2334                          GIOCondition   condition,
2335                          GCancellable  *cancellable,
2336                          GError       **error)
2337 {
2338   if (!check_socket (socket, error))
2339     return FALSE;
2340
2341   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2342     return FALSE;
2343
2344 #ifdef G_OS_WIN32
2345   {
2346     GIOCondition current_condition;
2347     WSAEVENT events[2];
2348     DWORD res;
2349     GPollFD cancel_fd;
2350     int num_events;
2351
2352     /* Always check these */
2353     condition |=  G_IO_ERR | G_IO_HUP;
2354
2355     add_condition_watch (socket, &condition);
2356
2357     num_events = 0;
2358     events[num_events++] = socket->priv->event;
2359
2360     if (cancellable)
2361       {
2362         g_cancellable_make_pollfd (cancellable, &cancel_fd);
2363         events[num_events++] = (WSAEVENT)cancel_fd.fd;
2364       }
2365
2366     current_condition = update_condition (socket);
2367     while ((condition & current_condition) == 0)
2368       {
2369         res = WSAWaitForMultipleEvents(num_events, events,
2370                                        FALSE, WSA_INFINITE, FALSE);
2371         if (res == WSA_WAIT_FAILED)
2372           {
2373             int errsv = get_socket_errno ();
2374
2375             g_set_error (error, G_IO_ERROR,
2376                          socket_io_error_from_errno (errsv),
2377                          _("Waiting for socket condition: %s"),
2378                          socket_strerror (errsv));
2379             break;
2380           }
2381
2382         if (g_cancellable_set_error_if_cancelled (cancellable, error))
2383           break;
2384
2385         current_condition = update_condition (socket);
2386       }
2387     remove_condition_watch (socket, &condition);
2388
2389     return (condition & current_condition) != 0;
2390   }
2391 #else
2392   {
2393     GPollFD poll_fd[2];
2394     gint result;
2395     gint num;
2396
2397     poll_fd[0].fd = socket->priv->fd;
2398     poll_fd[0].events = condition;
2399     num = 1;
2400
2401     if (cancellable)
2402       {
2403         g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2404         num++;
2405       }
2406
2407     do
2408       result = g_poll (poll_fd, num, -1);
2409     while (result == -1 && get_socket_errno () == EINTR);
2410
2411     return cancellable == NULL ||
2412       !g_cancellable_set_error_if_cancelled (cancellable, error);
2413   }
2414   #endif
2415 }
2416
2417 /**
2418  * g_socket_send_message:
2419  * @socket: a #GSocket
2420  * @address: a #GSocketAddress, or %NULL
2421  * @vectors: an array of #GOutputVector structs
2422  * @num_vectors: the number of elements in @vectors, or -1
2423  * @messages: a pointer to an array of #GSocketControlMessages, or
2424  *   %NULL.
2425  * @num_messages: number of elements in @messages, or -1.
2426  * @flags: an int containing #GSocketMsgFlags flags
2427  * @error: #GError for error reporting, or %NULL to ignore.
2428  *
2429  * Send data to @address on @socket.  This is the most complicated and
2430  * fully-featured version of this call. For easier use, see
2431  * g_socket_send() and g_socket_send_to().
2432  *
2433  * If @address is %NULL then the message is sent to the default receiver
2434  * (set by g_socket_connect()).
2435  *
2436  * @vector must point to an array of #GOutputVector structs and
2437  * @num_vectors must be the length of this array.  These structs
2438  * describe the buffers that the sent data will be gathered from.
2439  * If @num_vector is -1, then @vector is assumed to be terminated
2440  * by a #GOutputVector with a %NULL buffer pointer.
2441  *
2442  *
2443  * @messages, if non-%NULL, is taken to point to an array of @num_messages
2444  * #GSocketControlMessage instances. These correspond to the control
2445  * messages to be sent on the socket.
2446  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2447  * array.
2448  *
2449  * @flags modify how the message sent. The commonly available arguments
2450  * for this is available in the #GSocketMsgFlags enum, but the
2451  * values there are the same as the system values, and the flags
2452  * are passed in as-is, so you can pass in system specific flags too.
2453  *
2454  * If the socket is in blocking mode the call will block until there is
2455  * space for the data in the socket queue. If there is no space available
2456  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2457  * will be returned. To be notified of available space, wait for the %G_IO_OUT
2458  * condition.
2459  *
2460  * Note that on Windows you can't rely on a %G_IO_OUT condition
2461  * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2462  * write notification works. However, robust apps should always be able to
2463  * handle this since it can easily appear in other cases too.
2464  *
2465  * On error -1 is returned and @error is set accordingly.
2466  *
2467  * Returns: Number of bytes read, or -1 on error
2468  *
2469  * Since: 2.22
2470  **/
2471 gssize
2472 g_socket_send_message (GSocket                *socket,
2473                        GSocketAddress         *address,
2474                        GOutputVector          *vectors,
2475                        gint                    num_vectors,
2476                        GSocketControlMessage **messages,
2477                        gint                    num_messages,
2478                        gint                    flags,
2479                        GError                **error)
2480 {
2481   GOutputVector one_vector;
2482   char zero;
2483
2484   if (!check_socket (socket, error))
2485     return -1;
2486
2487   if (num_vectors == -1)
2488     {
2489       for (num_vectors = 0;
2490            vectors[num_vectors].buffer != NULL;
2491            num_vectors++)
2492         ;
2493     }
2494
2495   if (num_messages == -1)
2496     {
2497       for (num_messages = 0;
2498            messages != NULL && messages[num_messages] != NULL;
2499            num_messages++)
2500         ;
2501     }
2502
2503   if (num_vectors == 0)
2504     {
2505       zero = '\0';
2506
2507       one_vector.buffer = &zero;
2508       one_vector.size = 1;
2509       num_vectors = 1;
2510       vectors = &one_vector;
2511     }
2512
2513 #ifndef G_OS_WIN32
2514   {
2515     struct msghdr msg;
2516     gssize result;
2517
2518     /* name */
2519     if (address)
2520       {
2521         msg.msg_namelen = g_socket_address_get_native_size (address);
2522         msg.msg_name = g_alloca (msg.msg_namelen);
2523         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2524           return -1;
2525       }
2526
2527     /* iov */
2528     {
2529       /* this entire expression will be evaluated at compile time */
2530       if (sizeof *msg.msg_iov == sizeof *vectors &&
2531           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2532           G_STRUCT_OFFSET (struct iovec, iov_base) ==
2533           G_STRUCT_OFFSET (GOutputVector, buffer) &&
2534           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2535           G_STRUCT_OFFSET (struct iovec, iov_len) ==
2536           G_STRUCT_OFFSET (GOutputVector, size))
2537         /* ABI is compatible */
2538         {
2539           msg.msg_iov = (struct iovec *) vectors;
2540           msg.msg_iovlen = num_vectors;
2541         }
2542       else
2543         /* ABI is incompatible */
2544         {
2545           gint i;
2546
2547           msg.msg_iov = g_newa (struct iovec, num_vectors);
2548           for (i = 0; i < num_vectors; i++)
2549             {
2550               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2551               msg.msg_iov[i].iov_len = vectors[i].size;
2552             }
2553           msg.msg_iovlen = num_vectors;
2554         }
2555     }
2556
2557     /* control */
2558     {
2559       struct cmsghdr *cmsg;
2560       gint i;
2561
2562       msg.msg_controllen = 0;
2563       for (i = 0; i < num_messages; i++)
2564         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2565
2566       msg.msg_control = g_alloca (msg.msg_controllen);
2567
2568       cmsg = CMSG_FIRSTHDR (&msg);
2569       for (i = 0; i < num_messages; i++)
2570         {
2571           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2572           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2573           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2574           g_socket_control_message_serialize (messages[i],
2575                                               CMSG_DATA (cmsg));
2576           cmsg = CMSG_NXTHDR (&msg, cmsg);
2577         }
2578       g_assert (cmsg == NULL);
2579     }
2580
2581     while (1)
2582       {
2583         if (socket->priv->blocking &&
2584             !g_socket_condition_wait (socket,
2585                                       G_IO_OUT, NULL, error))
2586           return -1;
2587
2588         result = sendmsg (socket->priv->fd, &msg, flags);
2589         if (result < 0)
2590           {
2591             int errsv = get_socket_errno ();
2592
2593             if (errsv == EINTR)
2594               continue;
2595
2596             if (socket->priv->blocking &&
2597                 (errsv == EWOULDBLOCK ||
2598                  errsv == EAGAIN))
2599               continue;
2600
2601             g_set_error (error, G_IO_ERROR,
2602                          socket_io_error_from_errno (errsv),
2603                          _("Error sending message: %s"), socket_strerror (errsv));
2604
2605             return -1;
2606           }
2607         break;
2608       }
2609
2610     return result;
2611   }
2612 #else
2613   {
2614     struct sockaddr_storage addr;
2615     guint addrlen;
2616     DWORD bytes_sent;
2617     int result;
2618     WSABUF *bufs;
2619     gint i;
2620
2621     /* Win32 doesn't support control messages.
2622        Actually this is possible for raw and datagram sockets
2623        via WSASendMessage on Vista or later, but that doesn't
2624        seem very useful */
2625     if (num_messages != 0)
2626       {
2627         g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2628                      _("GSocketControlMessage not supported on windows"));
2629         return -1;
2630       }
2631
2632     /* iov */
2633     bufs = g_newa (WSABUF, num_vectors);
2634     for (i = 0; i < num_vectors; i++)
2635       {
2636         bufs[i].buf = (char *)vectors[i].buffer;
2637         bufs[i].len = (gulong)vectors[i].size;
2638       }
2639
2640     /* name */
2641     if (address)
2642       {
2643         addrlen = g_socket_address_get_native_size (address);
2644         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2645           return -1;
2646       }
2647
2648     while (1)
2649       {
2650         if (socket->priv->blocking &&
2651             !g_socket_condition_wait (socket,
2652                                       G_IO_OUT, NULL, error))
2653           return -1;
2654
2655         if (address)
2656           result = WSASendTo (socket->priv->fd,
2657                               bufs, num_vectors,
2658                               &bytes_sent, flags,
2659                               (const struct sockaddr *)&addr, addrlen,
2660                               NULL, NULL);
2661         else
2662           result = WSASend (socket->priv->fd,
2663                             bufs, num_vectors,
2664                             &bytes_sent, flags,
2665                             NULL, NULL);
2666
2667         if (result != 0)
2668           {
2669             int errsv = get_socket_errno ();
2670
2671             if (errsv == WSAEINTR)
2672               continue;
2673
2674             if (errsv == WSAEWOULDBLOCK)
2675               win32_unset_event_mask (socket, FD_WRITE);
2676
2677             if (socket->priv->blocking &&
2678                 errsv == WSAEWOULDBLOCK)
2679               continue;
2680
2681             g_set_error (error, G_IO_ERROR,
2682                          socket_io_error_from_errno (errsv),
2683                          _("Error sending message: %s"), socket_strerror (errsv));
2684
2685             return -1;
2686           }
2687         break;
2688       }
2689
2690     return bytes_sent;
2691   }
2692 #endif
2693 }
2694
2695 /**
2696  * g_socket_receive_message:
2697  * @socket: a #GSocket
2698  * @address: a pointer to a #GSocketAddress pointer, or %NULL
2699  * @vectors: an array of #GInputVector structs
2700  * @num_vectors: the number of elements in @vectors, or -1
2701  * @messages: a pointer which will be filled with an array of
2702  *     #GSocketControlMessages, or %NULL
2703  * @num_messages: a pointer which will be filled with the number of
2704  *    elements in @messages, or %NULL
2705  * @flags: a pointer to an int containing #GSocketMsgFlags flags
2706  * @error: a #GError pointer, or %NULL
2707  *
2708  * Receive data from a socket.  This is the most complicated and
2709  * fully-featured version of this call. For easier use, see
2710  * g_socket_receive() and g_socket_receive_from().
2711  *
2712  * If @address is non-%NULL then @address will be set equal to the
2713  * source address of the received packet.
2714  * @address is owned by the caller.
2715  *
2716  * @vector must point to an array of #GInputVector structs and
2717  * @num_vectors must be the length of this array.  These structs
2718  * describe the buffers that received data will be scattered into.
2719  * If @num_vector is -1, then @vector is assumed to be terminated
2720  * by a #GInputVector with a %NULL buffer pointer.
2721  *
2722  * As a special case, if the size of the array is zero (in which case,
2723  * @vectors may of course be %NULL), then a single byte is received
2724  * and discarded.  This is to facilitate the common practice of
2725  * sending a single '\0' byte for the purposes of transferring
2726  * ancillary data.
2727  *
2728  * @messages, if non-%NULL, is taken to point to a pointer that will
2729  * be set to point to a newly-allocated array of
2730  * #GSocketControlMessage instances.  These correspond to the control
2731  * messages received from the kernel, one #GSocketControlMessage per
2732  * message from the kernel.  This array is %NULL-terminated and must be
2733  * freed by the caller using g_free().
2734  *
2735  * @num_messages, if non-%NULL, will be set to the number of control
2736  * messages received.
2737  *
2738  * If both @messages and @num_messages are non-%NULL, then
2739  * @num_messages gives the number of #GSocketControlMessage instances
2740  * in @messages (ie: not including the %NULL terminator).
2741  *
2742  * @flags is an in/out parameter. The commonly available arguments
2743  * for this is available in the #GSocketMsgFlags enum, but the
2744  * values there are the same as the system values, and the flags
2745  * are passed in as-is, so you can pass in system specific flags too.
2746  *
2747  * If the socket is in blocking mode the call will block until there is
2748  * some data to receive or there is an error. If there is no data available
2749  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2750  * will be returned. To be notified of available data, wait for the %G_IO_IN
2751  * condition.
2752  *
2753  * On error -1 is returned and @error is set accordingly.
2754  *
2755  * Returns: Number of bytes read, or -1 on error
2756  *
2757  * Since: 2.22
2758  **/
2759 gssize
2760 g_socket_receive_message (GSocket                 *socket,
2761                           GSocketAddress         **address,
2762                           GInputVector            *vectors,
2763                           gint                     num_vectors,
2764                           GSocketControlMessage ***messages,
2765                           gint                    *num_messages,
2766                           gint                    *flags,
2767                           GError                 **error)
2768 {
2769   GInputVector one_vector;
2770   char one_byte;
2771
2772   if (!check_socket (socket, error))
2773     return -1;
2774
2775   if (num_vectors == -1)
2776     {
2777       for (num_vectors = 0;
2778            vectors[num_vectors].buffer != NULL;
2779            num_vectors++)
2780         ;
2781     }
2782
2783   if (num_vectors == 0)
2784     {
2785       one_vector.buffer = &one_byte;
2786       one_vector.size = 1;
2787       num_vectors = 1;
2788       vectors = &one_vector;
2789     }
2790
2791 #ifndef G_OS_WIN32
2792   {
2793     struct msghdr msg;
2794     gssize result;
2795     struct sockaddr_storage one_sockaddr;
2796
2797     /* name */
2798     if (address)
2799       {
2800         msg.msg_name = &one_sockaddr;
2801         msg.msg_namelen = sizeof (struct sockaddr_storage);
2802       }
2803     else
2804       {
2805         msg.msg_name = NULL;
2806         msg.msg_namelen = 0;
2807       }
2808
2809     /* iov */
2810     /* this entire expression will be evaluated at compile time */
2811     if (sizeof *msg.msg_iov == sizeof *vectors &&
2812         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2813         G_STRUCT_OFFSET (struct iovec, iov_base) ==
2814         G_STRUCT_OFFSET (GInputVector, buffer) &&
2815         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2816         G_STRUCT_OFFSET (struct iovec, iov_len) ==
2817         G_STRUCT_OFFSET (GInputVector, size))
2818       /* ABI is compatible */
2819       {
2820         msg.msg_iov = (struct iovec *) vectors;
2821         msg.msg_iovlen = num_vectors;
2822       }
2823     else
2824       /* ABI is incompatible */
2825       {
2826         gint i;
2827
2828         msg.msg_iov = g_newa (struct iovec, num_vectors);
2829         for (i = 0; i < num_vectors; i++)
2830           {
2831             msg.msg_iov[i].iov_base = vectors[i].buffer;
2832             msg.msg_iov[i].iov_len = vectors[i].size;
2833           }
2834         msg.msg_iovlen = num_vectors;
2835       }
2836
2837     /* control */
2838     msg.msg_control = g_alloca (2048);
2839     msg.msg_controllen = 2048;
2840
2841     /* flags */
2842     if (flags != NULL)
2843       msg.msg_flags = *flags;
2844     else
2845       msg.msg_flags = 0;
2846
2847     /* do it */
2848     while (1)
2849       {
2850         if (socket->priv->blocking &&
2851             !g_socket_condition_wait (socket,
2852                                       G_IO_IN, NULL, error))
2853           return -1;
2854
2855         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2856
2857         if (result < 0)
2858           {
2859             int errsv = get_socket_errno ();
2860
2861             if (errsv == EINTR)
2862               continue;
2863
2864             if (socket->priv->blocking &&
2865                 (errsv == EWOULDBLOCK ||
2866                  errsv == EAGAIN))
2867               continue;
2868
2869             g_set_error (error, G_IO_ERROR,
2870                          socket_io_error_from_errno (errsv),
2871                          _("Error receiving message: %s"), socket_strerror (errsv));
2872
2873             return -1;
2874           }
2875         break;
2876       }
2877
2878     /* decode address */
2879     if (address != NULL)
2880       {
2881         if (msg.msg_namelen > 0)
2882           *address = g_socket_address_new_from_native (msg.msg_name,
2883                                                        msg.msg_namelen);
2884         else
2885           *address = NULL;
2886       }
2887
2888     /* decode control messages */
2889     {
2890       GSocketControlMessage **my_messages = NULL;
2891       gint allocated = 0, index = 0;
2892       const gchar *scm_pointer;
2893       struct cmsghdr *cmsg;
2894       gsize scm_size;
2895
2896       scm_pointer = (const gchar *) msg.msg_control;
2897       scm_size = msg.msg_controllen;
2898
2899       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2900         {
2901           GSocketControlMessage *message;
2902
2903           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2904                                                           cmsg->cmsg_type,
2905                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2906                                                           CMSG_DATA (cmsg));
2907           if (message == NULL)
2908             /* We've already spewed about the problem in the
2909                deserialization code, so just continue */
2910             continue;
2911
2912           if (index == allocated)
2913             {
2914               /* estimated 99% case: exactly 1 control message */
2915               allocated = MIN (allocated * 2, 1);
2916               my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2917               allocated = 1;
2918             }
2919
2920           my_messages[index++] = message;
2921         }
2922
2923       if (num_messages)
2924         *num_messages = index;
2925
2926       if (messages)
2927         {
2928           my_messages[index++] = NULL;
2929           *messages = my_messages;
2930         }
2931       else
2932         {
2933           gint i;
2934
2935           /* free all those messages we just constructed.
2936            * we have to do it this way if the user ignores the
2937            * messages so that we will close any received fds.
2938            */
2939           for (i = 0; i < index; i++)
2940             g_object_unref (my_messages[i]);
2941           g_free (my_messages);
2942         }
2943     }
2944
2945     /* capture the flags */
2946     if (flags != NULL)
2947       *flags = msg.msg_flags;
2948
2949     return result;
2950   }
2951 #else
2952   {
2953     struct sockaddr_storage addr;
2954     int addrlen;
2955     DWORD bytes_received;
2956     DWORD win_flags;
2957     int result;
2958     WSABUF *bufs;
2959     gint i;
2960
2961     /* iov */
2962     bufs = g_newa (WSABUF, num_vectors);
2963     for (i = 0; i < num_vectors; i++)
2964       {
2965         bufs[i].buf = (char *)vectors[i].buffer;
2966         bufs[i].len = (gulong)vectors[i].size;
2967       }
2968
2969     /* flags */
2970     if (flags != NULL)
2971       win_flags = *flags;
2972     else
2973       win_flags = 0;
2974
2975     /* do it */
2976     while (1)
2977       {
2978         if (socket->priv->blocking &&
2979             !g_socket_condition_wait (socket,
2980                                       G_IO_IN, NULL, error))
2981           return -1;
2982
2983         addrlen = sizeof addr;
2984         if (address)
2985           result = WSARecvFrom (socket->priv->fd,
2986                                 bufs, num_vectors,
2987                                 &bytes_received, &win_flags,
2988                                 (struct sockaddr *)&addr, &addrlen,
2989                                 NULL, NULL);
2990         else
2991           result = WSARecv (socket->priv->fd,
2992                             bufs, num_vectors,
2993                             &bytes_received, &win_flags,
2994                             NULL, NULL);
2995         if (result != 0)
2996           {
2997             int errsv = get_socket_errno ();
2998
2999             if (errsv == WSAEINTR)
3000               continue;
3001
3002             win32_unset_event_mask (socket, FD_READ);
3003
3004             if (socket->priv->blocking &&
3005                 errsv == WSAEWOULDBLOCK)
3006               continue;
3007
3008             g_set_error (error, G_IO_ERROR,
3009                          socket_io_error_from_errno (errsv),
3010                          _("Error receiving message: %s"), socket_strerror (errsv));
3011
3012             return -1;
3013           }
3014         win32_unset_event_mask (socket, FD_READ);
3015         break;
3016       }
3017
3018     /* decode address */
3019     if (address != NULL)
3020       {
3021         if (addrlen > 0)
3022           *address = g_socket_address_new_from_native (&addr, addrlen);
3023         else
3024           *address = NULL;
3025       }
3026
3027     /* capture the flags */
3028     if (flags != NULL)
3029       *flags = win_flags;
3030
3031     return bytes_received;
3032   }
3033 #endif
3034 }
3035
3036 #define __G_SOCKET_C__
3037 #include "gioaliasdef.c"