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