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