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