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