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