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