gsocket: Fix g_socket_get_available_bytes() on Windows and OS X
[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 "gsocket.h"
31
32 #ifdef G_OS_UNIX
33 #include "glib-unix.h"
34 #endif
35
36 #include <errno.h>
37 #include <signal.h>
38 #include <string.h>
39 #include <stdlib.h>
40
41 #ifndef G_OS_WIN32
42 # include <fcntl.h>
43 # include <unistd.h>
44 # include <sys/ioctl.h>
45 #endif
46
47 #ifdef HAVE_SYS_FILIO_H
48 # include <sys/filio.h>
49 #endif
50
51 #ifdef HAVE_SYS_UIO_H
52 #include <sys/uio.h>
53 #endif
54
55 #include "gcancellable.h"
56 #include "gioenumtypes.h"
57 #include "ginetaddress.h"
58 #include "ginitable.h"
59 #include "gioerror.h"
60 #include "gioenums.h"
61 #include "gioerror.h"
62 #include "gnetworkingprivate.h"
63 #include "gsocketaddress.h"
64 #include "gsocketcontrolmessage.h"
65 #include "gcredentials.h"
66 #include "glibintl.h"
67
68 /**
69  * SECTION:gsocket
70  * @short_description: Low-level socket object
71  * @include: gio/gio.h
72  * @see_also: #GInitable, <link linkend="gio-gnetworking.h">gnetworking.h</link>
73  *
74  * A #GSocket is a low-level networking primitive. It is a more or less
75  * direct mapping of the BSD socket API in a portable GObject based API.
76  * It supports both the UNIX socket implementations and winsock2 on Windows.
77  *
78  * #GSocket is the platform independent base upon which the higher level
79  * network primitives are based. Applications are not typically meant to
80  * use it directly, but rather through classes like #GSocketClient,
81  * #GSocketService and #GSocketConnection. However there may be cases where
82  * direct use of #GSocket is useful.
83  *
84  * #GSocket implements the #GInitable interface, so if it is manually constructed
85  * by e.g. g_object_new() you must call g_initable_init() and check the
86  * results before using the object. This is done automatically in
87  * g_socket_new() and g_socket_new_from_fd(), so these functions can return
88  * %NULL.
89  *
90  * Sockets operate in two general modes, blocking or non-blocking. When
91  * in blocking mode all operations block until the requested operation
92  * is finished or there is an error. In non-blocking mode all calls that
93  * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
94  * To know when a call would successfully run you can call g_socket_condition_check(),
95  * or g_socket_condition_wait(). You can also use g_socket_create_source() and
96  * attach it to a #GMainContext to get callbacks when I/O is possible.
97  * Note that all sockets are always set to non blocking mode in the system, and
98  * blocking mode is emulated in GSocket.
99  *
100  * When working in non-blocking mode applications should always be able to
101  * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
102  * function said that I/O was possible. This can easily happen in case
103  * of a race condition in the application, but it can also happen for other
104  * reasons. For instance, on Windows a socket is always seen as writable
105  * until a write returns %G_IO_ERROR_WOULD_BLOCK.
106  *
107  * #GSocket<!-- -->s can be either connection oriented or datagram based.
108  * For connection oriented types you must first establish a connection by
109  * either connecting to an address or accepting a connection from another
110  * address. For connectionless socket types the target/source address is
111  * specified or received in each I/O operation.
112  *
113  * All socket file descriptors are set to be close-on-exec.
114  *
115  * Note that creating a #GSocket causes the signal %SIGPIPE to be
116  * ignored for the remainder of the program. If you are writing a
117  * command-line utility that uses #GSocket, you may need to take into
118  * account the fact that your program will not automatically be killed
119  * if it tries to write to %stdout after it has been closed.
120  *
121  * Since: 2.22
122  */
123
124 static void     g_socket_initable_iface_init (GInitableIface  *iface);
125 static gboolean g_socket_initable_init       (GInitable       *initable,
126                                               GCancellable    *cancellable,
127                                               GError         **error);
128
129 enum
130 {
131   PROP_0,
132   PROP_FAMILY,
133   PROP_TYPE,
134   PROP_PROTOCOL,
135   PROP_FD,
136   PROP_BLOCKING,
137   PROP_LISTEN_BACKLOG,
138   PROP_KEEPALIVE,
139   PROP_LOCAL_ADDRESS,
140   PROP_REMOTE_ADDRESS,
141   PROP_TIMEOUT,
142   PROP_TTL,
143   PROP_BROADCAST,
144   PROP_MULTICAST_LOOPBACK,
145   PROP_MULTICAST_TTL
146 };
147
148 /* Size of the receiver cache for g_socket_receive_from() */
149 #define RECV_ADDR_CACHE_SIZE 8
150
151 struct _GSocketPrivate
152 {
153   GSocketFamily   family;
154   GSocketType     type;
155   GSocketProtocol protocol;
156   gint            fd;
157   gint            listen_backlog;
158   guint           timeout;
159   GError         *construct_error;
160   GSocketAddress *remote_address;
161   guint           inited : 1;
162   guint           blocking : 1;
163   guint           keepalive : 1;
164   guint           closed : 1;
165   guint           connected : 1;
166   guint           listening : 1;
167   guint           timed_out : 1;
168   guint           connect_pending : 1;
169 #ifdef G_OS_WIN32
170   WSAEVENT        event;
171   int             current_events;
172   int             current_errors;
173   int             selected_events;
174   GList          *requested_conditions; /* list of requested GIOCondition * */
175   GMutex          win32_source_lock;
176 #endif
177
178   struct {
179     GSocketAddress *addr;
180     struct sockaddr *native;
181     gint native_len;
182     guint64 last_used;
183   } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
184 };
185
186 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
187                          G_ADD_PRIVATE (GSocket)
188                          g_networking_init ();
189                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
190                                                 g_socket_initable_iface_init));
191
192 static int
193 get_socket_errno (void)
194 {
195 #ifndef G_OS_WIN32
196   return errno;
197 #else
198   return WSAGetLastError ();
199 #endif
200 }
201
202 static GIOErrorEnum
203 socket_io_error_from_errno (int err)
204 {
205 #ifndef G_OS_WIN32
206   return g_io_error_from_errno (err);
207 #else
208   switch (err)
209     {
210     case WSAEADDRINUSE:
211       return G_IO_ERROR_ADDRESS_IN_USE;
212     case WSAEWOULDBLOCK:
213       return G_IO_ERROR_WOULD_BLOCK;
214     case WSAEACCES:
215       return G_IO_ERROR_PERMISSION_DENIED;
216     case WSA_INVALID_HANDLE:
217     case WSA_INVALID_PARAMETER:
218     case WSAEBADF:
219     case WSAENOTSOCK:
220       return G_IO_ERROR_INVALID_ARGUMENT;
221     case WSAEPROTONOSUPPORT:
222       return G_IO_ERROR_NOT_SUPPORTED;
223     case WSAECANCELLED:
224       return G_IO_ERROR_CANCELLED;
225     case WSAESOCKTNOSUPPORT:
226     case WSAEOPNOTSUPP:
227     case WSAEPFNOSUPPORT:
228     case WSAEAFNOSUPPORT:
229       return G_IO_ERROR_NOT_SUPPORTED;
230     default:
231       return G_IO_ERROR_FAILED;
232     }
233 #endif
234 }
235
236 static const char *
237 socket_strerror (int err)
238 {
239 #ifndef G_OS_WIN32
240   return g_strerror (err);
241 #else
242   const char *msg_ret;
243   char *msg;
244
245   msg = g_win32_error_message (err);
246
247   msg_ret = g_intern_string (msg);
248   g_free (msg);
249
250   return msg_ret;
251 #endif
252 }
253
254 #ifdef G_OS_WIN32
255 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
256 static void
257 _win32_unset_event_mask (GSocket *socket, int mask)
258 {
259   socket->priv->current_events &= ~mask;
260   socket->priv->current_errors &= ~mask;
261 }
262 #else
263 #define win32_unset_event_mask(_socket, _mask)
264 #endif
265
266 /* Windows has broken prototypes... */
267 #ifdef G_OS_WIN32
268 #define getsockopt(sockfd, level, optname, optval, optlen) \
269   getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
270 #define setsockopt(sockfd, level, optname, optval, optlen) \
271   setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
272 #define getsockname(sockfd, addr, addrlen) \
273   getsockname (sockfd, addr, (int *)addrlen)
274 #define getpeername(sockfd, addr, addrlen) \
275   getpeername (sockfd, addr, (int *)addrlen)
276 #define recv(sockfd, buf, len, flags) \
277   recv (sockfd, (gpointer)buf, len, flags)
278 #endif
279
280 static void
281 set_fd_nonblocking (int fd)
282 {
283 #ifndef G_OS_WIN32
284   GError *error = NULL;
285 #else
286   gulong arg;
287 #endif
288
289 #ifndef G_OS_WIN32
290   if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
291     {
292       g_warning ("Error setting socket nonblocking: %s", error->message);
293       g_clear_error (&error);
294     }
295 #else
296   arg = TRUE;
297
298   if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
299     {
300       int errsv = get_socket_errno ();
301       g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
302     }
303 #endif
304 }
305
306 static gboolean
307 check_socket (GSocket *socket,
308               GError **error)
309 {
310   if (!socket->priv->inited)
311     {
312       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
313                            _("Invalid socket, not initialized"));
314       return FALSE;
315     }
316
317   if (socket->priv->construct_error)
318     {
319       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
320                    _("Invalid socket, initialization failed due to: %s"),
321                    socket->priv->construct_error->message);
322       return FALSE;
323     }
324
325   if (socket->priv->closed)
326     {
327       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
328                            _("Socket is already closed"));
329       return FALSE;
330     }
331
332   if (socket->priv->timed_out)
333     {
334       socket->priv->timed_out = FALSE;
335       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
336                            _("Socket I/O timed out"));
337       return FALSE;
338     }
339
340   return TRUE;
341 }
342
343 static void
344 g_socket_details_from_fd (GSocket *socket)
345 {
346   struct sockaddr_storage address;
347   gint fd;
348   guint addrlen;
349   int value, family;
350   int errsv;
351
352   fd = socket->priv->fd;
353   if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
354     {
355       errsv = get_socket_errno ();
356
357       switch (errsv)
358         {
359 #ifdef ENOTSOCK
360          case ENOTSOCK:
361 #else
362 #ifdef WSAENOTSOCK
363          case WSAENOTSOCK:
364 #endif
365 #endif
366          case EBADF:
367           /* programmer error */
368           g_error ("creating GSocket from fd %d: %s\n",
369                    fd, socket_strerror (errsv));
370          default:
371            break;
372         }
373
374       goto err;
375     }
376
377   switch (value)
378     {
379      case SOCK_STREAM:
380       socket->priv->type = G_SOCKET_TYPE_STREAM;
381       break;
382
383      case SOCK_DGRAM:
384       socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
385       break;
386
387      case SOCK_SEQPACKET:
388       socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
389       break;
390
391      default:
392       socket->priv->type = G_SOCKET_TYPE_INVALID;
393       break;
394     }
395
396   addrlen = sizeof address;
397   if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
398     {
399       errsv = get_socket_errno ();
400       goto err;
401     }
402
403   if (addrlen > 0)
404     {
405       g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
406                 sizeof address.ss_family <= addrlen);
407       family = address.ss_family;
408     }
409   else
410     {
411       /* On Solaris, this happens if the socket is not yet connected.
412        * But we can use SO_DOMAIN as a workaround there.
413        */
414 #ifdef SO_DOMAIN
415       if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
416         {
417           errsv = get_socket_errno ();
418           goto err;
419         }
420 #else
421       /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
422       errsv = -1;
423       goto err;
424 #endif
425     }
426
427   switch (family)
428     {
429      case G_SOCKET_FAMILY_IPV4:
430      case G_SOCKET_FAMILY_IPV6:
431        socket->priv->family = address.ss_family;
432        switch (socket->priv->type)
433          {
434          case G_SOCKET_TYPE_STREAM:
435            socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
436            break;
437
438          case G_SOCKET_TYPE_DATAGRAM:
439            socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
440            break;
441
442          case G_SOCKET_TYPE_SEQPACKET:
443            socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
444            break;
445
446          default:
447            break;
448          }
449        break;
450
451      case G_SOCKET_FAMILY_UNIX:
452        socket->priv->family = G_SOCKET_FAMILY_UNIX;
453        socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
454        break;
455
456      default:
457        socket->priv->family = G_SOCKET_FAMILY_INVALID;
458        break;
459     }
460
461   if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
462     {
463       addrlen = sizeof address;
464       if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
465         socket->priv->connected = TRUE;
466     }
467
468   if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
469     {
470       socket->priv->keepalive = !!value;
471     }
472   else
473     {
474       /* Can't read, maybe not supported, assume FALSE */
475       socket->priv->keepalive = FALSE;
476     }
477
478   return;
479
480  err:
481   g_set_error (&socket->priv->construct_error, G_IO_ERROR,
482                socket_io_error_from_errno (errsv),
483                _("creating GSocket from fd: %s"),
484                socket_strerror (errsv));
485 }
486
487 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
488 gint
489 g_socket (gint     domain,
490           gint     type,
491           gint     protocol,
492           GError **error)
493 {
494   int fd;
495
496 #ifdef SOCK_CLOEXEC
497   fd = socket (domain, type | SOCK_CLOEXEC, protocol);
498   if (fd != -1)
499     return fd;
500
501   /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
502   if (fd < 0 && errno == EINVAL)
503 #endif
504     fd = socket (domain, type, protocol);
505
506   if (fd < 0)
507     {
508       int errsv = get_socket_errno ();
509
510       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
511                    _("Unable to create socket: %s"), socket_strerror (errsv));
512       errno = errsv;
513       return -1;
514     }
515
516 #ifndef G_OS_WIN32
517   {
518     int flags;
519
520     /* We always want to set close-on-exec to protect users. If you
521        need to so some weird inheritance to exec you can re-enable this
522        using lower level hacks with g_socket_get_fd(). */
523     flags = fcntl (fd, F_GETFD, 0);
524     if (flags != -1 &&
525         (flags & FD_CLOEXEC) == 0)
526       {
527         flags |= FD_CLOEXEC;
528         fcntl (fd, F_SETFD, flags);
529       }
530   }
531 #endif
532
533   return fd;
534 }
535
536 static gint
537 g_socket_create_socket (GSocketFamily   family,
538                         GSocketType     type,
539                         int             protocol,
540                         GError        **error)
541 {
542   gint native_type;
543
544   switch (type)
545     {
546      case G_SOCKET_TYPE_STREAM:
547       native_type = SOCK_STREAM;
548       break;
549
550      case G_SOCKET_TYPE_DATAGRAM:
551       native_type = SOCK_DGRAM;
552       break;
553
554      case G_SOCKET_TYPE_SEQPACKET:
555       native_type = SOCK_SEQPACKET;
556       break;
557
558      default:
559       g_assert_not_reached ();
560     }
561
562   if (family <= 0)
563     {
564       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
565                    _("Unable to create socket: %s"), _("Unknown family was specified"));
566       return -1;
567     }
568
569   if (protocol == -1)
570     {
571       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
572                    _("Unable to create socket: %s"), _("Unknown protocol was specified"));
573       return -1;
574     }
575
576   return g_socket (family, native_type, protocol, error);
577 }
578
579 static void
580 g_socket_constructed (GObject *object)
581 {
582   GSocket *socket = G_SOCKET (object);
583
584   if (socket->priv->fd >= 0)
585     /* create socket->priv info from the fd */
586     g_socket_details_from_fd (socket);
587
588   else
589     /* create the fd from socket->priv info */
590     socket->priv->fd = g_socket_create_socket (socket->priv->family,
591                                                socket->priv->type,
592                                                socket->priv->protocol,
593                                                &socket->priv->construct_error);
594
595   /* Always use native nonblocking sockets, as
596      windows sets sockets to nonblocking automatically
597      in certain operations. This way we make things work
598      the same on all platforms */
599   if (socket->priv->fd != -1)
600     set_fd_nonblocking (socket->priv->fd);
601 }
602
603 static void
604 g_socket_get_property (GObject    *object,
605                        guint       prop_id,
606                        GValue     *value,
607                        GParamSpec *pspec)
608 {
609   GSocket *socket = G_SOCKET (object);
610   GSocketAddress *address;
611
612   switch (prop_id)
613     {
614       case PROP_FAMILY:
615         g_value_set_enum (value, socket->priv->family);
616         break;
617
618       case PROP_TYPE:
619         g_value_set_enum (value, socket->priv->type);
620         break;
621
622       case PROP_PROTOCOL:
623         g_value_set_enum (value, socket->priv->protocol);
624         break;
625
626       case PROP_FD:
627         g_value_set_int (value, socket->priv->fd);
628         break;
629
630       case PROP_BLOCKING:
631         g_value_set_boolean (value, socket->priv->blocking);
632         break;
633
634       case PROP_LISTEN_BACKLOG:
635         g_value_set_int (value, socket->priv->listen_backlog);
636         break;
637
638       case PROP_KEEPALIVE:
639         g_value_set_boolean (value, socket->priv->keepalive);
640         break;
641
642       case PROP_LOCAL_ADDRESS:
643         address = g_socket_get_local_address (socket, NULL);
644         g_value_take_object (value, address);
645         break;
646
647       case PROP_REMOTE_ADDRESS:
648         address = g_socket_get_remote_address (socket, NULL);
649         g_value_take_object (value, address);
650         break;
651
652       case PROP_TIMEOUT:
653         g_value_set_uint (value, socket->priv->timeout);
654         break;
655
656       case PROP_TTL:
657         g_value_set_uint (value, g_socket_get_ttl (socket));
658         break;
659
660       case PROP_BROADCAST:
661         g_value_set_boolean (value, g_socket_get_broadcast (socket));
662         break;
663
664       case PROP_MULTICAST_LOOPBACK:
665         g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
666         break;
667
668       case PROP_MULTICAST_TTL:
669         g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
670         break;
671
672       default:
673         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
674     }
675 }
676
677 static void
678 g_socket_set_property (GObject      *object,
679                        guint         prop_id,
680                        const GValue *value,
681                        GParamSpec   *pspec)
682 {
683   GSocket *socket = G_SOCKET (object);
684
685   switch (prop_id)
686     {
687       case PROP_FAMILY:
688         socket->priv->family = g_value_get_enum (value);
689         break;
690
691       case PROP_TYPE:
692         socket->priv->type = g_value_get_enum (value);
693         break;
694
695       case PROP_PROTOCOL:
696         socket->priv->protocol = g_value_get_enum (value);
697         break;
698
699       case PROP_FD:
700         socket->priv->fd = g_value_get_int (value);
701         break;
702
703       case PROP_BLOCKING:
704         g_socket_set_blocking (socket, g_value_get_boolean (value));
705         break;
706
707       case PROP_LISTEN_BACKLOG:
708         g_socket_set_listen_backlog (socket, g_value_get_int (value));
709         break;
710
711       case PROP_KEEPALIVE:
712         g_socket_set_keepalive (socket, g_value_get_boolean (value));
713         break;
714
715       case PROP_TIMEOUT:
716         g_socket_set_timeout (socket, g_value_get_uint (value));
717         break;
718
719       case PROP_TTL:
720         g_socket_set_ttl (socket, g_value_get_uint (value));
721         break;
722
723       case PROP_BROADCAST:
724         g_socket_set_broadcast (socket, g_value_get_boolean (value));
725         break;
726
727       case PROP_MULTICAST_LOOPBACK:
728         g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
729         break;
730
731       case PROP_MULTICAST_TTL:
732         g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
733         break;
734
735       default:
736         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
737     }
738 }
739
740 static void
741 g_socket_finalize (GObject *object)
742 {
743   GSocket *socket = G_SOCKET (object);
744   gint i;
745
746   g_clear_error (&socket->priv->construct_error);
747
748   if (socket->priv->fd != -1 &&
749       !socket->priv->closed)
750     g_socket_close (socket, NULL);
751
752   if (socket->priv->remote_address)
753     g_object_unref (socket->priv->remote_address);
754
755 #ifdef G_OS_WIN32
756   if (socket->priv->event != WSA_INVALID_EVENT)
757     {
758       WSACloseEvent (socket->priv->event);
759       socket->priv->event = WSA_INVALID_EVENT;
760     }
761
762   g_assert (socket->priv->requested_conditions == NULL);
763   g_mutex_clear (&socket->priv->win32_source_lock);
764 #endif
765
766   for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
767     {
768       if (socket->priv->recv_addr_cache[i].addr)
769         {
770           g_object_unref (socket->priv->recv_addr_cache[i].addr);
771           g_free (socket->priv->recv_addr_cache[i].native);
772         }
773     }
774
775   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
776     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
777 }
778
779 static void
780 g_socket_class_init (GSocketClass *klass)
781 {
782   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
783
784 #ifdef SIGPIPE
785   /* There is no portable, thread-safe way to avoid having the process
786    * be killed by SIGPIPE when calling send() or sendmsg(), so we are
787    * forced to simply ignore the signal process-wide.
788    */
789   signal (SIGPIPE, SIG_IGN);
790 #endif
791
792   gobject_class->finalize = g_socket_finalize;
793   gobject_class->constructed = g_socket_constructed;
794   gobject_class->set_property = g_socket_set_property;
795   gobject_class->get_property = g_socket_get_property;
796
797   g_object_class_install_property (gobject_class, PROP_FAMILY,
798                                    g_param_spec_enum ("family",
799                                                       P_("Socket family"),
800                                                       P_("The sockets address family"),
801                                                       G_TYPE_SOCKET_FAMILY,
802                                                       G_SOCKET_FAMILY_INVALID,
803                                                       G_PARAM_CONSTRUCT_ONLY |
804                                                       G_PARAM_READWRITE |
805                                                       G_PARAM_STATIC_STRINGS));
806
807   g_object_class_install_property (gobject_class, PROP_TYPE,
808                                    g_param_spec_enum ("type",
809                                                       P_("Socket type"),
810                                                       P_("The sockets type"),
811                                                       G_TYPE_SOCKET_TYPE,
812                                                       G_SOCKET_TYPE_STREAM,
813                                                       G_PARAM_CONSTRUCT_ONLY |
814                                                       G_PARAM_READWRITE |
815                                                       G_PARAM_STATIC_STRINGS));
816
817   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
818                                    g_param_spec_enum ("protocol",
819                                                       P_("Socket protocol"),
820                                                       P_("The id of the protocol to use, or -1 for unknown"),
821                                                       G_TYPE_SOCKET_PROTOCOL,
822                                                       G_SOCKET_PROTOCOL_UNKNOWN,
823                                                       G_PARAM_CONSTRUCT_ONLY |
824                                                       G_PARAM_READWRITE |
825                                                       G_PARAM_STATIC_STRINGS));
826
827   g_object_class_install_property (gobject_class, PROP_FD,
828                                    g_param_spec_int ("fd",
829                                                      P_("File descriptor"),
830                                                      P_("The sockets file descriptor"),
831                                                      G_MININT,
832                                                      G_MAXINT,
833                                                      -1,
834                                                      G_PARAM_CONSTRUCT_ONLY |
835                                                      G_PARAM_READWRITE |
836                                                      G_PARAM_STATIC_STRINGS));
837
838   g_object_class_install_property (gobject_class, PROP_BLOCKING,
839                                    g_param_spec_boolean ("blocking",
840                                                          P_("blocking"),
841                                                          P_("Whether or not I/O on this socket is blocking"),
842                                                          TRUE,
843                                                          G_PARAM_READWRITE |
844                                                          G_PARAM_STATIC_STRINGS));
845
846   g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
847                                    g_param_spec_int ("listen-backlog",
848                                                      P_("Listen backlog"),
849                                                      P_("Outstanding connections in the listen queue"),
850                                                      0,
851                                                      SOMAXCONN,
852                                                      10,
853                                                      G_PARAM_READWRITE |
854                                                      G_PARAM_STATIC_STRINGS));
855
856   g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
857                                    g_param_spec_boolean ("keepalive",
858                                                          P_("Keep connection alive"),
859                                                          P_("Keep connection alive by sending periodic pings"),
860                                                          FALSE,
861                                                          G_PARAM_READWRITE |
862                                                          G_PARAM_STATIC_STRINGS));
863
864   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
865                                    g_param_spec_object ("local-address",
866                                                         P_("Local address"),
867                                                         P_("The local address the socket is bound to"),
868                                                         G_TYPE_SOCKET_ADDRESS,
869                                                         G_PARAM_READABLE |
870                                                         G_PARAM_STATIC_STRINGS));
871
872   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
873                                    g_param_spec_object ("remote-address",
874                                                         P_("Remote address"),
875                                                         P_("The remote address the socket is connected to"),
876                                                         G_TYPE_SOCKET_ADDRESS,
877                                                         G_PARAM_READABLE |
878                                                         G_PARAM_STATIC_STRINGS));
879
880   /**
881    * GSocket:timeout:
882    *
883    * The timeout in seconds on socket I/O
884    *
885    * Since: 2.26
886    */
887   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
888                                    g_param_spec_uint ("timeout",
889                                                       P_("Timeout"),
890                                                       P_("The timeout in seconds on socket I/O"),
891                                                       0,
892                                                       G_MAXUINT,
893                                                       0,
894                                                       G_PARAM_READWRITE |
895                                                       G_PARAM_STATIC_STRINGS));
896
897   /**
898    * GSocket:broadcast:
899    *
900    * Whether the socket should allow sending to broadcast addresses.
901    *
902    * Since: 2.32
903    */
904   g_object_class_install_property (gobject_class, PROP_BROADCAST,
905                                    g_param_spec_boolean ("broadcast",
906                                                          P_("Broadcast"),
907                                                          P_("Whether to allow sending to broadcast addresses"),
908                                                          FALSE,
909                                                          G_PARAM_READWRITE |
910                                                          G_PARAM_STATIC_STRINGS));
911
912   /**
913    * GSocket:ttl:
914    *
915    * Time-to-live for outgoing unicast packets
916    *
917    * Since: 2.32
918    */
919   g_object_class_install_property (gobject_class, PROP_TTL,
920                                    g_param_spec_uint ("ttl",
921                                                       P_("TTL"),
922                                                       P_("Time-to-live of outgoing unicast packets"),
923                                                       0, G_MAXUINT, 0,
924                                                       G_PARAM_READWRITE |
925                                                       G_PARAM_STATIC_STRINGS));
926
927   /**
928    * GSocket:multicast-loopback:
929    *
930    * Whether outgoing multicast packets loop back to the local host.
931    *
932    * Since: 2.32
933    */
934   g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
935                                    g_param_spec_boolean ("multicast-loopback",
936                                                          P_("Multicast loopback"),
937                                                          P_("Whether outgoing multicast packets loop back to the local host"),
938                                                          TRUE,
939                                                          G_PARAM_READWRITE |
940                                                          G_PARAM_STATIC_STRINGS));
941
942   /**
943    * GSocket:multicast-ttl:
944    *
945    * Time-to-live out outgoing multicast packets
946    *
947    * Since: 2.32
948    */
949   g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
950                                    g_param_spec_uint ("multicast-ttl",
951                                                       P_("Multicast TTL"),
952                                                       P_("Time-to-live of outgoing multicast packets"),
953                                                       0, G_MAXUINT, 1,
954                                                       G_PARAM_READWRITE |
955                                                       G_PARAM_STATIC_STRINGS));
956 }
957
958 static void
959 g_socket_initable_iface_init (GInitableIface *iface)
960 {
961   iface->init = g_socket_initable_init;
962 }
963
964 static void
965 g_socket_init (GSocket *socket)
966 {
967   socket->priv = g_socket_get_instance_private (socket);
968
969   socket->priv->fd = -1;
970   socket->priv->blocking = TRUE;
971   socket->priv->listen_backlog = 10;
972   socket->priv->construct_error = NULL;
973 #ifdef G_OS_WIN32
974   socket->priv->event = WSA_INVALID_EVENT;
975   g_mutex_init (&socket->priv->win32_source_lock);
976 #endif
977 }
978
979 static gboolean
980 g_socket_initable_init (GInitable *initable,
981                         GCancellable *cancellable,
982                         GError  **error)
983 {
984   GSocket  *socket;
985
986   g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
987
988   socket = G_SOCKET (initable);
989
990   if (cancellable != NULL)
991     {
992       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
993                            _("Cancellable initialization not supported"));
994       return FALSE;
995     }
996
997   socket->priv->inited = TRUE;
998
999   if (socket->priv->construct_error)
1000     {
1001       if (error)
1002         *error = g_error_copy (socket->priv->construct_error);
1003       return FALSE;
1004     }
1005
1006
1007   return TRUE;
1008 }
1009
1010 /**
1011  * g_socket_new:
1012  * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1013  * @type: the socket type to use.
1014  * @protocol: the id of the protocol to use, or 0 for default.
1015  * @error: #GError for error reporting, or %NULL to ignore.
1016  *
1017  * Creates a new #GSocket with the defined family, type and protocol.
1018  * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1019  * for the family and type is used.
1020  *
1021  * The @protocol is a family and type specific int that specifies what
1022  * kind of protocol to use. #GSocketProtocol lists several common ones.
1023  * Many families only support one protocol, and use 0 for this, others
1024  * support several and using 0 means to use the default protocol for
1025  * the family and type.
1026  *
1027  * The protocol id is passed directly to the operating
1028  * system, so you can use protocols not listed in #GSocketProtocol if you
1029  * know the protocol number used for it.
1030  *
1031  * Returns: a #GSocket or %NULL on error.
1032  *     Free the returned object with g_object_unref().
1033  *
1034  * Since: 2.22
1035  */
1036 GSocket *
1037 g_socket_new (GSocketFamily     family,
1038               GSocketType       type,
1039               GSocketProtocol   protocol,
1040               GError          **error)
1041 {
1042   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1043                                    NULL, error,
1044                                    "family", family,
1045                                    "type", type,
1046                                    "protocol", protocol,
1047                                    NULL));
1048 }
1049
1050 /**
1051  * g_socket_new_from_fd:
1052  * @fd: a native socket file descriptor.
1053  * @error: #GError for error reporting, or %NULL to ignore.
1054  *
1055  * Creates a new #GSocket from a native file descriptor
1056  * or winsock SOCKET handle.
1057  *
1058  * This reads all the settings from the file descriptor so that
1059  * all properties should work. Note that the file descriptor
1060  * will be set to non-blocking mode, independent on the blocking
1061  * mode of the #GSocket.
1062  *
1063  * Returns: a #GSocket or %NULL on error.
1064  *     Free the returned object with g_object_unref().
1065  *
1066  * Since: 2.22
1067  */
1068 GSocket *
1069 g_socket_new_from_fd (gint     fd,
1070                       GError **error)
1071 {
1072   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1073                                    NULL, error,
1074                                    "fd", fd,
1075                                    NULL));
1076 }
1077
1078 /**
1079  * g_socket_set_blocking:
1080  * @socket: a #GSocket.
1081  * @blocking: Whether to use blocking I/O or not.
1082  *
1083  * Sets the blocking mode of the socket. In blocking mode
1084  * all operations block until they succeed or there is an error. In
1085  * non-blocking mode all functions return results immediately or
1086  * with a %G_IO_ERROR_WOULD_BLOCK error.
1087  *
1088  * All sockets are created in blocking mode. However, note that the
1089  * platform level socket is always non-blocking, and blocking mode
1090  * is a GSocket level feature.
1091  *
1092  * Since: 2.22
1093  */
1094 void
1095 g_socket_set_blocking (GSocket  *socket,
1096                        gboolean  blocking)
1097 {
1098   g_return_if_fail (G_IS_SOCKET (socket));
1099
1100   blocking = !!blocking;
1101
1102   if (socket->priv->blocking == blocking)
1103     return;
1104
1105   socket->priv->blocking = blocking;
1106   g_object_notify (G_OBJECT (socket), "blocking");
1107 }
1108
1109 /**
1110  * g_socket_get_blocking:
1111  * @socket: a #GSocket.
1112  *
1113  * Gets the blocking mode of the socket. For details on blocking I/O,
1114  * see g_socket_set_blocking().
1115  *
1116  * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1117  *
1118  * Since: 2.22
1119  */
1120 gboolean
1121 g_socket_get_blocking (GSocket *socket)
1122 {
1123   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1124
1125   return socket->priv->blocking;
1126 }
1127
1128 /**
1129  * g_socket_set_keepalive:
1130  * @socket: a #GSocket.
1131  * @keepalive: Value for the keepalive flag
1132  *
1133  * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1134  * this flag is set on a socket, the system will attempt to verify that the
1135  * remote socket endpoint is still present if a sufficiently long period of
1136  * time passes with no data being exchanged. If the system is unable to
1137  * verify the presence of the remote endpoint, it will automatically close
1138  * the connection.
1139  *
1140  * This option is only functional on certain kinds of sockets. (Notably,
1141  * %G_SOCKET_PROTOCOL_TCP sockets.)
1142  *
1143  * The exact time between pings is system- and protocol-dependent, but will
1144  * normally be at least two hours. Most commonly, you would set this flag
1145  * on a server socket if you want to allow clients to remain idle for long
1146  * periods of time, but also want to ensure that connections are eventually
1147  * garbage-collected if clients crash or become unreachable.
1148  *
1149  * Since: 2.22
1150  */
1151 void
1152 g_socket_set_keepalive (GSocket  *socket,
1153                         gboolean  keepalive)
1154 {
1155   GError *error = NULL;
1156
1157   g_return_if_fail (G_IS_SOCKET (socket));
1158
1159   keepalive = !!keepalive;
1160   if (socket->priv->keepalive == keepalive)
1161     return;
1162
1163   if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1164                             keepalive, &error))
1165     {
1166       g_warning ("error setting keepalive: %s", error->message);
1167       g_error_free (error);
1168       return;
1169     }
1170
1171   socket->priv->keepalive = keepalive;
1172   g_object_notify (G_OBJECT (socket), "keepalive");
1173 }
1174
1175 /**
1176  * g_socket_get_keepalive:
1177  * @socket: a #GSocket.
1178  *
1179  * Gets the keepalive mode of the socket. For details on this,
1180  * see g_socket_set_keepalive().
1181  *
1182  * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1183  *
1184  * Since: 2.22
1185  */
1186 gboolean
1187 g_socket_get_keepalive (GSocket *socket)
1188 {
1189   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1190
1191   return socket->priv->keepalive;
1192 }
1193
1194 /**
1195  * g_socket_get_listen_backlog:
1196  * @socket: a #GSocket.
1197  *
1198  * Gets the listen backlog setting of the socket. For details on this,
1199  * see g_socket_set_listen_backlog().
1200  *
1201  * Returns: the maximum number of pending connections.
1202  *
1203  * Since: 2.22
1204  */
1205 gint
1206 g_socket_get_listen_backlog  (GSocket *socket)
1207 {
1208   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1209
1210   return socket->priv->listen_backlog;
1211 }
1212
1213 /**
1214  * g_socket_set_listen_backlog:
1215  * @socket: a #GSocket.
1216  * @backlog: the maximum number of pending connections.
1217  *
1218  * Sets the maximum number of outstanding connections allowed
1219  * when listening on this socket. If more clients than this are
1220  * connecting to the socket and the application is not handling them
1221  * on time then the new connections will be refused.
1222  *
1223  * Note that this must be called before g_socket_listen() and has no
1224  * effect if called after that.
1225  *
1226  * Since: 2.22
1227  */
1228 void
1229 g_socket_set_listen_backlog (GSocket *socket,
1230                              gint     backlog)
1231 {
1232   g_return_if_fail (G_IS_SOCKET (socket));
1233   g_return_if_fail (!socket->priv->listening);
1234
1235   if (backlog != socket->priv->listen_backlog)
1236     {
1237       socket->priv->listen_backlog = backlog;
1238       g_object_notify (G_OBJECT (socket), "listen-backlog");
1239     }
1240 }
1241
1242 /**
1243  * g_socket_get_timeout:
1244  * @socket: a #GSocket.
1245  *
1246  * Gets the timeout setting of the socket. For details on this, see
1247  * g_socket_set_timeout().
1248  *
1249  * Returns: the timeout in seconds
1250  *
1251  * Since: 2.26
1252  */
1253 guint
1254 g_socket_get_timeout (GSocket *socket)
1255 {
1256   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1257
1258   return socket->priv->timeout;
1259 }
1260
1261 /**
1262  * g_socket_set_timeout:
1263  * @socket: a #GSocket.
1264  * @timeout: the timeout for @socket, in seconds, or 0 for none
1265  *
1266  * Sets the time in seconds after which I/O operations on @socket will
1267  * time out if they have not yet completed.
1268  *
1269  * On a blocking socket, this means that any blocking #GSocket
1270  * operation will time out after @timeout seconds of inactivity,
1271  * returning %G_IO_ERROR_TIMED_OUT.
1272  *
1273  * On a non-blocking socket, calls to g_socket_condition_wait() will
1274  * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1275  * created with g_socket_create_source() will trigger after
1276  * @timeout seconds of inactivity, with the requested condition
1277  * set, at which point calling g_socket_receive(), g_socket_send(),
1278  * g_socket_check_connect_result(), etc, will fail with
1279  * %G_IO_ERROR_TIMED_OUT.
1280  *
1281  * If @timeout is 0 (the default), operations will never time out
1282  * on their own.
1283  *
1284  * Note that if an I/O operation is interrupted by a signal, this may
1285  * cause the timeout to be reset.
1286  *
1287  * Since: 2.26
1288  */
1289 void
1290 g_socket_set_timeout (GSocket *socket,
1291                       guint    timeout)
1292 {
1293   g_return_if_fail (G_IS_SOCKET (socket));
1294
1295   if (timeout != socket->priv->timeout)
1296     {
1297       socket->priv->timeout = timeout;
1298       g_object_notify (G_OBJECT (socket), "timeout");
1299     }
1300 }
1301
1302 /**
1303  * g_socket_get_ttl:
1304  * @socket: a #GSocket.
1305  *
1306  * Gets the unicast time-to-live setting on @socket; see
1307  * g_socket_set_ttl() for more details.
1308  *
1309  * Returns: the time-to-live setting on @socket
1310  *
1311  * Since: 2.32
1312  */
1313 guint
1314 g_socket_get_ttl (GSocket *socket)
1315 {
1316   GError *error = NULL;
1317   gint value;
1318
1319   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1320
1321   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1322     {
1323       g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1324                            &value, &error);
1325     }
1326   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1327     {
1328       g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1329                            &value, &error);
1330     }
1331   else
1332     g_return_val_if_reached (0);
1333
1334   if (error)
1335     {
1336       g_warning ("error getting unicast ttl: %s", error->message);
1337       g_error_free (error);
1338       return 0;
1339     }
1340
1341   return value;
1342 }
1343
1344 /**
1345  * g_socket_set_ttl:
1346  * @socket: a #GSocket.
1347  * @ttl: the time-to-live value for all unicast packets on @socket
1348  *
1349  * Sets the time-to-live for outgoing unicast packets on @socket.
1350  * By default the platform-specific default value is used.
1351  *
1352  * Since: 2.32
1353  */
1354 void
1355 g_socket_set_ttl (GSocket  *socket,
1356                   guint     ttl)
1357 {
1358   GError *error = NULL;
1359
1360   g_return_if_fail (G_IS_SOCKET (socket));
1361
1362   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1363     {
1364       g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1365                            ttl, &error);
1366     }
1367   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1368     {
1369       g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1370                            ttl, NULL);
1371       g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1372                            ttl, &error);
1373     }
1374   else
1375     g_return_if_reached ();
1376
1377   if (error)
1378     {
1379       g_warning ("error setting unicast ttl: %s", error->message);
1380       g_error_free (error);
1381       return;
1382     }
1383
1384   g_object_notify (G_OBJECT (socket), "ttl");
1385 }
1386
1387 /**
1388  * g_socket_get_broadcast:
1389  * @socket: a #GSocket.
1390  *
1391  * Gets the broadcast setting on @socket; if %TRUE,
1392  * it is possible to send packets to broadcast
1393  * addresses.
1394  *
1395  * Returns: the broadcast setting on @socket
1396  *
1397  * Since: 2.32
1398  */
1399 gboolean
1400 g_socket_get_broadcast (GSocket *socket)
1401 {
1402   GError *error = NULL;
1403   gint value;
1404
1405   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1406
1407   if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1408                             &value, &error))
1409     {
1410       g_warning ("error getting broadcast: %s", error->message);
1411       g_error_free (error);
1412       return FALSE;
1413     }
1414
1415   return !!value;
1416 }
1417
1418 /**
1419  * g_socket_set_broadcast:
1420  * @socket: a #GSocket.
1421  * @broadcast: whether @socket should allow sending to broadcast
1422  *     addresses
1423  *
1424  * Sets whether @socket should allow sending to broadcast addresses.
1425  * This is %FALSE by default.
1426  *
1427  * Since: 2.32
1428  */
1429 void
1430 g_socket_set_broadcast (GSocket    *socket,
1431                         gboolean    broadcast)
1432 {
1433   GError *error = NULL;
1434
1435   g_return_if_fail (G_IS_SOCKET (socket));
1436
1437   broadcast = !!broadcast;
1438
1439   if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1440                             broadcast, &error))
1441     {
1442       g_warning ("error setting broadcast: %s", error->message);
1443       g_error_free (error);
1444       return;
1445     }
1446
1447   g_object_notify (G_OBJECT (socket), "broadcast");
1448 }
1449
1450 /**
1451  * g_socket_get_multicast_loopback:
1452  * @socket: a #GSocket.
1453  *
1454  * Gets the multicast loopback setting on @socket; if %TRUE (the
1455  * default), outgoing multicast packets will be looped back to
1456  * multicast listeners on the same host.
1457  *
1458  * Returns: the multicast loopback setting on @socket
1459  *
1460  * Since: 2.32
1461  */
1462 gboolean
1463 g_socket_get_multicast_loopback (GSocket *socket)
1464 {
1465   GError *error = NULL;
1466   gint value;
1467
1468   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1469
1470   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1471     {
1472       g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1473                            &value, &error);
1474     }
1475   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1476     {
1477       g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1478                            &value, &error);
1479     }
1480   else
1481     g_return_val_if_reached (FALSE);
1482
1483   if (error)
1484     {
1485       g_warning ("error getting multicast loopback: %s", error->message);
1486       g_error_free (error);
1487       return FALSE;
1488     }
1489
1490   return !!value;
1491 }
1492
1493 /**
1494  * g_socket_set_multicast_loopback:
1495  * @socket: a #GSocket.
1496  * @loopback: whether @socket should receive messages sent to its
1497  *   multicast groups from the local host
1498  *
1499  * Sets whether outgoing multicast packets will be received by sockets
1500  * listening on that multicast address on the same host. This is %TRUE
1501  * by default.
1502  *
1503  * Since: 2.32
1504  */
1505 void
1506 g_socket_set_multicast_loopback (GSocket    *socket,
1507                                  gboolean    loopback)
1508 {
1509   GError *error = NULL;
1510
1511   g_return_if_fail (G_IS_SOCKET (socket));
1512
1513   loopback = !!loopback;
1514
1515   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1516     {
1517       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1518                            loopback, &error);
1519     }
1520   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1521     {
1522       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1523                            loopback, NULL);
1524       g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1525                            loopback, &error);
1526     }
1527   else
1528     g_return_if_reached ();
1529
1530   if (error)
1531     {
1532       g_warning ("error setting multicast loopback: %s", error->message);
1533       g_error_free (error);
1534       return;
1535     }
1536
1537   g_object_notify (G_OBJECT (socket), "multicast-loopback");
1538 }
1539
1540 /**
1541  * g_socket_get_multicast_ttl:
1542  * @socket: a #GSocket.
1543  *
1544  * Gets the multicast time-to-live setting on @socket; see
1545  * g_socket_set_multicast_ttl() for more details.
1546  *
1547  * Returns: the multicast time-to-live setting on @socket
1548  *
1549  * Since: 2.32
1550  */
1551 guint
1552 g_socket_get_multicast_ttl (GSocket *socket)
1553 {
1554   GError *error = NULL;
1555   gint value;
1556
1557   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1558
1559   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1560     {
1561       g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1562                            &value, &error);
1563     }
1564   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1565     {
1566       g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1567                            &value, &error);
1568     }
1569   else
1570     g_return_val_if_reached (FALSE);
1571
1572   if (error)
1573     {
1574       g_warning ("error getting multicast ttl: %s", error->message);
1575       g_error_free (error);
1576       return FALSE;
1577     }
1578
1579   return value;
1580 }
1581
1582 /**
1583  * g_socket_set_multicast_ttl:
1584  * @socket: a #GSocket.
1585  * @ttl: the time-to-live value for all multicast datagrams on @socket
1586  *
1587  * Sets the time-to-live for outgoing multicast datagrams on @socket.
1588  * By default, this is 1, meaning that multicast packets will not leave
1589  * the local network.
1590  *
1591  * Since: 2.32
1592  */
1593 void
1594 g_socket_set_multicast_ttl (GSocket  *socket,
1595                             guint     ttl)
1596 {
1597   GError *error = NULL;
1598
1599   g_return_if_fail (G_IS_SOCKET (socket));
1600
1601   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1602     {
1603       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1604                            ttl, &error);
1605     }
1606   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1607     {
1608       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1609                            ttl, NULL);
1610       g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1611                            ttl, &error);
1612     }
1613   else
1614     g_return_if_reached ();
1615
1616   if (error)
1617     {
1618       g_warning ("error setting multicast ttl: %s", error->message);
1619       g_error_free (error);
1620       return;
1621     }
1622
1623   g_object_notify (G_OBJECT (socket), "multicast-ttl");
1624 }
1625
1626 /**
1627  * g_socket_get_family:
1628  * @socket: a #GSocket.
1629  *
1630  * Gets the socket family of the socket.
1631  *
1632  * Returns: a #GSocketFamily
1633  *
1634  * Since: 2.22
1635  */
1636 GSocketFamily
1637 g_socket_get_family (GSocket *socket)
1638 {
1639   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1640
1641   return socket->priv->family;
1642 }
1643
1644 /**
1645  * g_socket_get_socket_type:
1646  * @socket: a #GSocket.
1647  *
1648  * Gets the socket type of the socket.
1649  *
1650  * Returns: a #GSocketType
1651  *
1652  * Since: 2.22
1653  */
1654 GSocketType
1655 g_socket_get_socket_type (GSocket *socket)
1656 {
1657   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1658
1659   return socket->priv->type;
1660 }
1661
1662 /**
1663  * g_socket_get_protocol:
1664  * @socket: a #GSocket.
1665  *
1666  * Gets the socket protocol id the socket was created with.
1667  * In case the protocol is unknown, -1 is returned.
1668  *
1669  * Returns: a protocol id, or -1 if unknown
1670  *
1671  * Since: 2.22
1672  */
1673 GSocketProtocol
1674 g_socket_get_protocol (GSocket *socket)
1675 {
1676   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1677
1678   return socket->priv->protocol;
1679 }
1680
1681 /**
1682  * g_socket_get_fd:
1683  * @socket: a #GSocket.
1684  *
1685  * Returns the underlying OS socket object. On unix this
1686  * is a socket file descriptor, and on Windows this is
1687  * a Winsock2 SOCKET handle. This may be useful for
1688  * doing platform specific or otherwise unusual operations
1689  * on the socket.
1690  *
1691  * Returns: the file descriptor of the socket.
1692  *
1693  * Since: 2.22
1694  */
1695 int
1696 g_socket_get_fd (GSocket *socket)
1697 {
1698   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1699
1700   return socket->priv->fd;
1701 }
1702
1703 /**
1704  * g_socket_get_local_address:
1705  * @socket: a #GSocket.
1706  * @error: #GError for error reporting, or %NULL to ignore.
1707  *
1708  * Try to get the local address of a bound socket. This is only
1709  * useful if the socket has been bound to a local address,
1710  * either explicitly or implicitly when connecting.
1711  *
1712  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1713  *     Free the returned object with g_object_unref().
1714  *
1715  * Since: 2.22
1716  */
1717 GSocketAddress *
1718 g_socket_get_local_address (GSocket  *socket,
1719                             GError  **error)
1720 {
1721   struct sockaddr_storage buffer;
1722   guint len = sizeof (buffer);
1723
1724   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1725
1726   if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1727     {
1728       int errsv = get_socket_errno ();
1729       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1730                    _("could not get local address: %s"), socket_strerror (errsv));
1731       return NULL;
1732     }
1733
1734   return g_socket_address_new_from_native (&buffer, len);
1735 }
1736
1737 /**
1738  * g_socket_get_remote_address:
1739  * @socket: a #GSocket.
1740  * @error: #GError for error reporting, or %NULL to ignore.
1741  *
1742  * Try to get the remove address of a connected socket. This is only
1743  * useful for connection oriented sockets that have been connected.
1744  *
1745  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1746  *     Free the returned object with g_object_unref().
1747  *
1748  * Since: 2.22
1749  */
1750 GSocketAddress *
1751 g_socket_get_remote_address (GSocket  *socket,
1752                              GError  **error)
1753 {
1754   struct sockaddr_storage buffer;
1755   guint len = sizeof (buffer);
1756
1757   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1758
1759   if (socket->priv->connect_pending)
1760     {
1761       if (!g_socket_check_connect_result (socket, error))
1762         return NULL;
1763       else
1764         socket->priv->connect_pending = FALSE;
1765     }
1766
1767   if (!socket->priv->remote_address)
1768     {
1769       if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1770         {
1771           int errsv = get_socket_errno ();
1772           g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1773                        _("could not get remote address: %s"), socket_strerror (errsv));
1774           return NULL;
1775         }
1776
1777       socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1778     }
1779
1780   return g_object_ref (socket->priv->remote_address);
1781 }
1782
1783 /**
1784  * g_socket_is_connected:
1785  * @socket: a #GSocket.
1786  *
1787  * Check whether the socket is connected. This is only useful for
1788  * connection-oriented sockets.
1789  *
1790  * Returns: %TRUE if socket is connected, %FALSE otherwise.
1791  *
1792  * Since: 2.22
1793  */
1794 gboolean
1795 g_socket_is_connected (GSocket *socket)
1796 {
1797   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1798
1799   return socket->priv->connected;
1800 }
1801
1802 /**
1803  * g_socket_listen:
1804  * @socket: a #GSocket.
1805  * @error: #GError for error reporting, or %NULL to ignore.
1806  *
1807  * Marks the socket as a server socket, i.e. a socket that is used
1808  * to accept incoming requests using g_socket_accept().
1809  *
1810  * Before calling this the socket must be bound to a local address using
1811  * g_socket_bind().
1812  *
1813  * To set the maximum amount of outstanding clients, use
1814  * g_socket_set_listen_backlog().
1815  *
1816  * Returns: %TRUE on success, %FALSE on error.
1817  *
1818  * Since: 2.22
1819  */
1820 gboolean
1821 g_socket_listen (GSocket  *socket,
1822                  GError  **error)
1823 {
1824   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1825
1826   if (!check_socket (socket, error))
1827     return FALSE;
1828
1829   if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1830     {
1831       int errsv = get_socket_errno ();
1832
1833       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1834                    _("could not listen: %s"), socket_strerror (errsv));
1835       return FALSE;
1836     }
1837
1838   socket->priv->listening = TRUE;
1839
1840   return TRUE;
1841 }
1842
1843 /**
1844  * g_socket_bind:
1845  * @socket: a #GSocket.
1846  * @address: a #GSocketAddress specifying the local address.
1847  * @allow_reuse: whether to allow reusing this address
1848  * @error: #GError for error reporting, or %NULL to ignore.
1849  *
1850  * When a socket is created it is attached to an address family, but it
1851  * doesn't have an address in this family. g_socket_bind() assigns the
1852  * address (sometimes called name) of the socket.
1853  *
1854  * It is generally required to bind to a local address before you can
1855  * receive connections. (See g_socket_listen() and g_socket_accept() ).
1856  * In certain situations, you may also want to bind a socket that will be
1857  * used to initiate connections, though this is not normally required.
1858  *
1859  * If @socket is a TCP socket, then @allow_reuse controls the setting
1860  * of the <literal>SO_REUSEADDR</literal> socket option; normally it
1861  * should be %TRUE for server sockets (sockets that you will
1862  * eventually call g_socket_accept() on), and %FALSE for client
1863  * sockets. (Failing to set this flag on a server socket may cause
1864  * g_socket_bind() to return %G_IO_ERROR_ADDRESS_IN_USE if the server
1865  * program is stopped and then immediately restarted.)
1866  *
1867  * If @socket is a UDP socket, then @allow_reuse determines whether or
1868  * not other UDP sockets can be bound to the same address at the same
1869  * time. In particular, you can have several UDP sockets bound to the
1870  * same address, and they will all receive all of the multicast and
1871  * broadcast packets sent to that address. (The behavior of unicast
1872  * UDP packets to an address with multiple listeners is not defined.)
1873  *
1874  * Returns: %TRUE on success, %FALSE on error.
1875  *
1876  * Since: 2.22
1877  */
1878 gboolean
1879 g_socket_bind (GSocket         *socket,
1880                GSocketAddress  *address,
1881                gboolean         reuse_address,
1882                GError         **error)
1883 {
1884   struct sockaddr_storage addr;
1885   gboolean so_reuseaddr;
1886 #ifdef SO_REUSEPORT
1887   gboolean so_reuseport;
1888 #endif
1889
1890   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1891
1892   if (!check_socket (socket, error))
1893     return FALSE;
1894
1895   if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1896     return FALSE;
1897
1898   /* On Windows, SO_REUSEADDR has the semantics we want for UDP
1899    * sockets, but has nasty side effects we don't want for TCP
1900    * sockets.
1901    *
1902    * On other platforms, we set SO_REUSEPORT, if it exists, for
1903    * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
1904    * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
1905    * the desired semantics on UDP (as it does on Linux, although
1906    * Linux has SO_REUSEPORT too as of 3.9).
1907    */
1908
1909 #ifdef G_OS_WIN32
1910   so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1911 #else
1912   so_reuseaddr = !!reuse_address;
1913 #endif
1914
1915 #ifdef SO_REUSEPORT
1916   so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1917 #endif
1918
1919   /* Ignore errors here, the only likely error is "not supported", and
1920    * this is a "best effort" thing mainly.
1921    */
1922   g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
1923 #ifdef SO_REUSEPORT
1924   g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
1925 #endif
1926
1927   if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1928             g_socket_address_get_native_size (address)) < 0)
1929     {
1930       int errsv = get_socket_errno ();
1931       g_set_error (error,
1932                    G_IO_ERROR, socket_io_error_from_errno (errsv),
1933                    _("Error binding to address: %s"), socket_strerror (errsv));
1934       return FALSE;
1935     }
1936
1937   return TRUE;
1938 }
1939
1940 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
1941 static guint
1942 if_nametoindex (const gchar *iface)
1943 {
1944   PIP_ADAPTER_ADDRESSES addresses = NULL, p;
1945   gulong addresses_len = 0;
1946   guint idx = 0;
1947   DWORD res;
1948
1949   res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
1950   if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
1951     {
1952       if (res == ERROR_NO_DATA)
1953         errno = ENXIO;
1954       else
1955         errno = EINVAL;
1956       return 0;
1957     }
1958
1959   addresses = g_malloc (addresses_len);
1960   res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
1961
1962   if (res != NO_ERROR)
1963     {
1964       g_free (addresses);
1965       if (res == ERROR_NO_DATA)
1966         errno = ENXIO;
1967       else
1968         errno = EINVAL;
1969       return 0;
1970     }
1971
1972   p = addresses;
1973   while (p)
1974     {
1975       if (strcmp (p->AdapterName, iface) == 0)
1976         {
1977           idx = p->IfIndex;
1978           break;
1979         }
1980       p = p->Next;
1981     }
1982
1983   if (p == NULL)
1984     errno = ENXIO;
1985
1986   g_free (addresses);
1987
1988   return idx;
1989 }
1990
1991 #define HAVE_IF_NAMETOINDEX 1
1992 #endif
1993
1994 static gboolean
1995 g_socket_multicast_group_operation (GSocket       *socket,
1996                                     GInetAddress  *group,
1997                                     gboolean       source_specific,
1998                                     const gchar   *iface,
1999                                     gboolean       join_group,
2000                                     GError       **error)
2001 {
2002   const guint8 *native_addr;
2003   gint optname, result;
2004
2005   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2006   g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2007   g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2008
2009   if (!check_socket (socket, error))
2010     return FALSE;
2011
2012   native_addr = g_inet_address_to_bytes (group);
2013   if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2014     {
2015 #ifdef HAVE_IP_MREQN
2016       struct ip_mreqn mc_req;
2017 #else
2018       struct ip_mreq mc_req;
2019 #endif
2020
2021       memset (&mc_req, 0, sizeof (mc_req));
2022       memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2023
2024 #ifdef HAVE_IP_MREQN
2025       if (iface)
2026         mc_req.imr_ifindex = if_nametoindex (iface);
2027       else
2028         mc_req.imr_ifindex = 0;  /* Pick any.  */
2029 #elif defined(G_OS_WIN32)
2030       if (iface)
2031         mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2032       else
2033         mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2034 #else
2035       mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2036 #endif
2037
2038       if (source_specific)
2039         {
2040 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2041           optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2042 #else
2043           g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2044                        join_group ?
2045                        _("Error joining multicast group: %s") :
2046                        _("Error leaving multicast group: %s"),
2047                        _("No support for source-specific multicast"));
2048           return FALSE;
2049 #endif
2050         }
2051       else
2052         optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2053       result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2054                            &mc_req, sizeof (mc_req));
2055     }
2056   else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2057     {
2058       struct ipv6_mreq mc_req_ipv6;
2059
2060       memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2061       memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2062 #ifdef HAVE_IF_NAMETOINDEX
2063       if (iface)
2064         mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2065       else
2066 #endif
2067         mc_req_ipv6.ipv6mr_interface = 0;
2068
2069       optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2070       result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2071                            &mc_req_ipv6, sizeof (mc_req_ipv6));
2072     }
2073   else
2074     g_return_val_if_reached (FALSE);
2075
2076   if (result < 0)
2077     {
2078       int errsv = get_socket_errno ();
2079
2080       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2081                    join_group ?
2082                    _("Error joining multicast group: %s") :
2083                    _("Error leaving multicast group: %s"),
2084                    socket_strerror (errsv));
2085       return FALSE;
2086     }
2087
2088   return TRUE;
2089 }
2090
2091 /**
2092  * g_socket_join_multicast_group:
2093  * @socket: a #GSocket.
2094  * @group: a #GInetAddress specifying the group address to join.
2095  * @iface: (allow-none): Name of the interface to use, or %NULL
2096  * @source_specific: %TRUE if source-specific multicast should be used
2097  * @error: #GError for error reporting, or %NULL to ignore.
2098  *
2099  * Registers @socket to receive multicast messages sent to @group.
2100  * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2101  * been bound to an appropriate interface and port with
2102  * g_socket_bind().
2103  *
2104  * If @iface is %NULL, the system will automatically pick an interface
2105  * to bind to based on @group.
2106  *
2107  * If @source_specific is %TRUE, source-specific multicast as defined
2108  * in RFC 4604 is used. Note that on older platforms this may fail
2109  * with a %G_IO_ERROR_NOT_SUPPORTED error.
2110  *
2111  * Returns: %TRUE on success, %FALSE on error.
2112  *
2113  * Since: 2.32
2114  */
2115 gboolean
2116 g_socket_join_multicast_group (GSocket       *socket,
2117                                GInetAddress  *group,
2118                                gboolean       source_specific,
2119                                const gchar   *iface,
2120                                GError       **error)
2121 {
2122   return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2123 }
2124
2125 /**
2126  * g_socket_leave_multicast_group:
2127  * @socket: a #GSocket.
2128  * @group: a #GInetAddress specifying the group address to leave.
2129  * @iface: (allow-none): Interface used
2130  * @source_specific: %TRUE if source-specific multicast was used
2131  * @error: #GError for error reporting, or %NULL to ignore.
2132  *
2133  * Removes @socket from the multicast group defined by @group, @iface,
2134  * and @source_specific (which must all have the same values they had
2135  * when you joined the group).
2136  *
2137  * @socket remains bound to its address and port, and can still receive
2138  * unicast messages after calling this.
2139  *
2140  * Returns: %TRUE on success, %FALSE on error.
2141  *
2142  * Since: 2.32
2143  */
2144 gboolean
2145 g_socket_leave_multicast_group (GSocket       *socket,
2146                                 GInetAddress  *group,
2147                                 gboolean       source_specific,
2148                                 const gchar   *iface,
2149                                 GError       **error)
2150 {
2151   return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2152 }
2153
2154 /**
2155  * g_socket_speaks_ipv4:
2156  * @socket: a #GSocket
2157  *
2158  * Checks if a socket is capable of speaking IPv4.
2159  *
2160  * IPv4 sockets are capable of speaking IPv4.  On some operating systems
2161  * and under some combinations of circumstances IPv6 sockets are also
2162  * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
2163  * information.
2164  *
2165  * No other types of sockets are currently considered as being capable
2166  * of speaking IPv4.
2167  *
2168  * Returns: %TRUE if this socket can be used with IPv4.
2169  *
2170  * Since: 2.22
2171  **/
2172 gboolean
2173 g_socket_speaks_ipv4 (GSocket *socket)
2174 {
2175   switch (socket->priv->family)
2176     {
2177     case G_SOCKET_FAMILY_IPV4:
2178       return TRUE;
2179
2180     case G_SOCKET_FAMILY_IPV6:
2181 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2182       {
2183         gint v6_only;
2184
2185         if (!g_socket_get_option (socket,
2186                                   IPPROTO_IPV6, IPV6_V6ONLY,
2187                                   &v6_only, NULL))
2188           return FALSE;
2189
2190         return !v6_only;
2191       }
2192 #else
2193       return FALSE;
2194 #endif
2195
2196     default:
2197       return FALSE;
2198     }
2199 }
2200
2201 /**
2202  * g_socket_accept:
2203  * @socket: a #GSocket.
2204  * @cancellable: (allow-none): a %GCancellable or %NULL
2205  * @error: #GError for error reporting, or %NULL to ignore.
2206  *
2207  * Accept incoming connections on a connection-based socket. This removes
2208  * the first outstanding connection request from the listening socket and
2209  * creates a #GSocket object for it.
2210  *
2211  * The @socket must be bound to a local address with g_socket_bind() and
2212  * must be listening for incoming connections (g_socket_listen()).
2213  *
2214  * If there are no outstanding connections then the operation will block
2215  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2216  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2217  *
2218  * Returns: (transfer full): a new #GSocket, or %NULL on error.
2219  *     Free the returned object with g_object_unref().
2220  *
2221  * Since: 2.22
2222  */
2223 GSocket *
2224 g_socket_accept (GSocket       *socket,
2225                  GCancellable  *cancellable,
2226                  GError       **error)
2227 {
2228   GSocket *new_socket;
2229   gint ret;
2230
2231   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2232
2233   if (!check_socket (socket, error))
2234     return NULL;
2235
2236   while (TRUE)
2237     {
2238       if (socket->priv->blocking &&
2239           !g_socket_condition_wait (socket,
2240                                     G_IO_IN, cancellable, error))
2241         return NULL;
2242
2243       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2244         {
2245           int errsv = get_socket_errno ();
2246
2247           win32_unset_event_mask (socket, FD_ACCEPT);
2248
2249           if (errsv == EINTR)
2250             continue;
2251
2252           if (socket->priv->blocking)
2253             {
2254 #ifdef WSAEWOULDBLOCK
2255               if (errsv == WSAEWOULDBLOCK)
2256                 continue;
2257 #else
2258               if (errsv == EWOULDBLOCK ||
2259                   errsv == EAGAIN)
2260                 continue;
2261 #endif
2262             }
2263
2264           g_set_error (error, G_IO_ERROR,
2265                        socket_io_error_from_errno (errsv),
2266                        _("Error accepting connection: %s"), socket_strerror (errsv));
2267           return NULL;
2268         }
2269       break;
2270     }
2271
2272   win32_unset_event_mask (socket, FD_ACCEPT);
2273
2274 #ifdef G_OS_WIN32
2275   {
2276     /* The socket inherits the accepting sockets event mask and even object,
2277        we need to remove that */
2278     WSAEventSelect (ret, NULL, 0);
2279   }
2280 #else
2281   {
2282     int flags;
2283
2284     /* We always want to set close-on-exec to protect users. If you
2285        need to so some weird inheritance to exec you can re-enable this
2286        using lower level hacks with g_socket_get_fd(). */
2287     flags = fcntl (ret, F_GETFD, 0);
2288     if (flags != -1 &&
2289         (flags & FD_CLOEXEC) == 0)
2290       {
2291         flags |= FD_CLOEXEC;
2292         fcntl (ret, F_SETFD, flags);
2293       }
2294   }
2295 #endif
2296
2297   new_socket = g_socket_new_from_fd (ret, error);
2298   if (new_socket == NULL)
2299     {
2300 #ifdef G_OS_WIN32
2301       closesocket (ret);
2302 #else
2303       close (ret);
2304 #endif
2305     }
2306   else
2307     new_socket->priv->protocol = socket->priv->protocol;
2308
2309   return new_socket;
2310 }
2311
2312 /**
2313  * g_socket_connect:
2314  * @socket: a #GSocket.
2315  * @address: a #GSocketAddress specifying the remote address.
2316  * @cancellable: (allow-none): a %GCancellable or %NULL
2317  * @error: #GError for error reporting, or %NULL to ignore.
2318  *
2319  * Connect the socket to the specified remote address.
2320  *
2321  * For connection oriented socket this generally means we attempt to make
2322  * a connection to the @address. For a connection-less socket it sets
2323  * the default address for g_socket_send() and discards all incoming datagrams
2324  * from other sources.
2325  *
2326  * Generally connection oriented sockets can only connect once, but
2327  * connection-less sockets can connect multiple times to change the
2328  * default address.
2329  *
2330  * If the connect call needs to do network I/O it will block, unless
2331  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2332  * and the user can be notified of the connection finishing by waiting
2333  * for the G_IO_OUT condition. The result of the connection must then be
2334  * checked with g_socket_check_connect_result().
2335  *
2336  * Returns: %TRUE if connected, %FALSE on error.
2337  *
2338  * Since: 2.22
2339  */
2340 gboolean
2341 g_socket_connect (GSocket         *socket,
2342                   GSocketAddress  *address,
2343                   GCancellable    *cancellable,
2344                   GError         **error)
2345 {
2346   struct sockaddr_storage buffer;
2347
2348   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2349
2350   if (!check_socket (socket, error))
2351     return FALSE;
2352
2353   if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2354     return FALSE;
2355
2356   if (socket->priv->remote_address)
2357     g_object_unref (socket->priv->remote_address);
2358   socket->priv->remote_address = g_object_ref (address);
2359
2360   while (1)
2361     {
2362       if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2363                    g_socket_address_get_native_size (address)) < 0)
2364         {
2365           int errsv = get_socket_errno ();
2366
2367           if (errsv == EINTR)
2368             continue;
2369
2370 #ifndef G_OS_WIN32
2371           if (errsv == EINPROGRESS)
2372 #else
2373           if (errsv == WSAEWOULDBLOCK)
2374 #endif
2375             {
2376               if (socket->priv->blocking)
2377                 {
2378                   if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2379                     {
2380                       if (g_socket_check_connect_result (socket, error))
2381                         break;
2382                     }
2383                 }
2384               else
2385                 {
2386                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2387                                        _("Connection in progress"));
2388                   socket->priv->connect_pending = TRUE;
2389                 }
2390             }
2391           else
2392             g_set_error_literal (error, G_IO_ERROR,
2393                                  socket_io_error_from_errno (errsv),
2394                                  socket_strerror (errsv));
2395
2396           return FALSE;
2397         }
2398       break;
2399     }
2400
2401   win32_unset_event_mask (socket, FD_CONNECT);
2402
2403   socket->priv->connected = TRUE;
2404
2405   return TRUE;
2406 }
2407
2408 /**
2409  * g_socket_check_connect_result:
2410  * @socket: a #GSocket
2411  * @error: #GError for error reporting, or %NULL to ignore.
2412  *
2413  * Checks and resets the pending connect error for the socket.
2414  * This is used to check for errors when g_socket_connect() is
2415  * used in non-blocking mode.
2416  *
2417  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2418  *
2419  * Since: 2.22
2420  */
2421 gboolean
2422 g_socket_check_connect_result (GSocket  *socket,
2423                                GError  **error)
2424 {
2425   int value;
2426
2427   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2428
2429   if (!check_socket (socket, error))
2430     return FALSE;
2431
2432   if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2433     {
2434       g_prefix_error (error, _("Unable to get pending error: "));
2435       return FALSE;
2436     }
2437
2438   if (value != 0)
2439     {
2440       g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2441                            socket_strerror (value));
2442       if (socket->priv->remote_address)
2443         {
2444           g_object_unref (socket->priv->remote_address);
2445           socket->priv->remote_address = NULL;
2446         }
2447       return FALSE;
2448     }
2449
2450   socket->priv->connected = TRUE;
2451   return TRUE;
2452 }
2453
2454 /**
2455  * g_socket_get_available_bytes:
2456  * @socket: a #GSocket
2457  *
2458  * Get the amount of data pending in the OS input buffer.
2459  *
2460  * If @socket is a UDP or SCTP socket, this will return the size of
2461  * just the next packet, even if additional packets are buffered after
2462  * that one.
2463  *
2464  * Note that on Windows, this function is rather inefficient in the
2465  * UDP case, and so if you know any plausible upper bound on the size
2466  * of the incoming packet, it is better to just do a
2467  * g_socket_receive() with a buffer of that size, rather than calling
2468  * g_socket_get_available_bytes() first and then doing a receive of
2469  * exactly the right size.
2470  *
2471  * Returns: the number of bytes that can be read from the socket
2472  * without blocking or truncating, or -1 on error.
2473  *
2474  * Since: 2.32
2475  */
2476 gssize
2477 g_socket_get_available_bytes (GSocket *socket)
2478 {
2479 #ifdef G_OS_WIN32
2480   const gint bufsize = 64 * 1024;
2481   static guchar *buf = NULL;
2482 #endif
2483   gint avail;
2484
2485   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2486
2487 #if defined (SO_NREAD)
2488   if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2489       return -1;
2490 #elif !defined (G_OS_WIN32)
2491   if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2492     avail = -1;
2493 #else
2494   if (G_UNLIKELY (g_once_init_enter (&buf)))
2495     g_once_init_leave (&buf, g_malloc (bufsize));
2496
2497   avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2498 #endif
2499
2500   return avail;
2501 }
2502
2503 /**
2504  * g_socket_receive:
2505  * @socket: a #GSocket
2506  * @buffer: (array length=size) (element-type guint8): a buffer to
2507  *     read data into (which should be at least @size bytes long).
2508  * @size: the number of bytes you want to read from the socket
2509  * @cancellable: (allow-none): a %GCancellable or %NULL
2510  * @error: #GError for error reporting, or %NULL to ignore.
2511  *
2512  * Receive data (up to @size bytes) from a socket. This is mainly used by
2513  * connection-oriented sockets; it is identical to g_socket_receive_from()
2514  * with @address set to %NULL.
2515  *
2516  * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2517  * g_socket_receive() will always read either 0 or 1 complete messages from
2518  * the socket. If the received message is too large to fit in @buffer, then
2519  * the data beyond @size bytes will be discarded, without any explicit
2520  * indication that this has occurred.
2521  *
2522  * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2523  * number of bytes, up to @size. If more than @size bytes have been
2524  * received, the additional data will be returned in future calls to
2525  * g_socket_receive().
2526  *
2527  * If the socket is in blocking mode the call will block until there
2528  * is some data to receive, the connection is closed, or there is an
2529  * error. If there is no data available and the socket is in
2530  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2531  * returned. To be notified when data is available, wait for the
2532  * %G_IO_IN condition.
2533  *
2534  * On error -1 is returned and @error is set accordingly.
2535  *
2536  * Returns: Number of bytes read, or 0 if the connection was closed by
2537  * the peer, or -1 on error
2538  *
2539  * Since: 2.22
2540  */
2541 gssize
2542 g_socket_receive (GSocket       *socket,
2543                   gchar         *buffer,
2544                   gsize          size,
2545                   GCancellable  *cancellable,
2546                   GError       **error)
2547 {
2548   return g_socket_receive_with_blocking (socket, buffer, size,
2549                                          socket->priv->blocking,
2550                                          cancellable, error);
2551 }
2552
2553 /**
2554  * g_socket_receive_with_blocking:
2555  * @socket: a #GSocket
2556  * @buffer: (array length=size) (element-type guint8): a buffer to
2557  *     read data into (which should be at least @size bytes long).
2558  * @size: the number of bytes you want to read from the socket
2559  * @blocking: whether to do blocking or non-blocking I/O
2560  * @cancellable: (allow-none): a %GCancellable or %NULL
2561  * @error: #GError for error reporting, or %NULL to ignore.
2562  *
2563  * This behaves exactly the same as g_socket_receive(), except that
2564  * the choice of blocking or non-blocking behavior is determined by
2565  * the @blocking argument rather than by @socket's properties.
2566  *
2567  * Returns: Number of bytes read, or 0 if the connection was closed by
2568  * the peer, or -1 on error
2569  *
2570  * Since: 2.26
2571  */
2572 gssize
2573 g_socket_receive_with_blocking (GSocket       *socket,
2574                                 gchar         *buffer,
2575                                 gsize          size,
2576                                 gboolean       blocking,
2577                                 GCancellable  *cancellable,
2578                                 GError       **error)
2579 {
2580   gssize ret;
2581
2582   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2583
2584   if (!check_socket (socket, error))
2585     return -1;
2586
2587   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2588     return -1;
2589
2590   while (1)
2591     {
2592       if (blocking &&
2593           !g_socket_condition_wait (socket,
2594                                     G_IO_IN, cancellable, error))
2595         return -1;
2596
2597       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2598         {
2599           int errsv = get_socket_errno ();
2600
2601           if (errsv == EINTR)
2602             continue;
2603
2604           if (blocking)
2605             {
2606 #ifdef WSAEWOULDBLOCK
2607               if (errsv == WSAEWOULDBLOCK)
2608                 continue;
2609 #else
2610               if (errsv == EWOULDBLOCK ||
2611                   errsv == EAGAIN)
2612                 continue;
2613 #endif
2614             }
2615
2616           win32_unset_event_mask (socket, FD_READ);
2617
2618           g_set_error (error, G_IO_ERROR,
2619                        socket_io_error_from_errno (errsv),
2620                        _("Error receiving data: %s"), socket_strerror (errsv));
2621           return -1;
2622         }
2623
2624       win32_unset_event_mask (socket, FD_READ);
2625
2626       break;
2627     }
2628
2629   return ret;
2630 }
2631
2632 /**
2633  * g_socket_receive_from:
2634  * @socket: a #GSocket
2635  * @address: (out) (allow-none): a pointer to a #GSocketAddress
2636  *     pointer, or %NULL
2637  * @buffer: (array length=size) (element-type guint8): a buffer to
2638  *     read data into (which should be at least @size bytes long).
2639  * @size: the number of bytes you want to read from the socket
2640  * @cancellable: (allow-none): a %GCancellable or %NULL
2641  * @error: #GError for error reporting, or %NULL to ignore.
2642  *
2643  * Receive data (up to @size bytes) from a socket.
2644  *
2645  * If @address is non-%NULL then @address will be set equal to the
2646  * source address of the received packet.
2647  * @address is owned by the caller.
2648  *
2649  * See g_socket_receive() for additional information.
2650  *
2651  * Returns: Number of bytes read, or 0 if the connection was closed by
2652  * the peer, or -1 on error
2653  *
2654  * Since: 2.22
2655  */
2656 gssize
2657 g_socket_receive_from (GSocket         *socket,
2658                        GSocketAddress **address,
2659                        gchar           *buffer,
2660                        gsize            size,
2661                        GCancellable    *cancellable,
2662                        GError         **error)
2663 {
2664   GInputVector v;
2665
2666   v.buffer = buffer;
2667   v.size = size;
2668
2669   return g_socket_receive_message (socket,
2670                                    address,
2671                                    &v, 1,
2672                                    NULL, 0, NULL,
2673                                    cancellable,
2674                                    error);
2675 }
2676
2677 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2678  * one, which can be confusing and annoying. So if possible, we want
2679  * to suppress the signal entirely.
2680  */
2681 #ifdef MSG_NOSIGNAL
2682 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2683 #else
2684 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2685 #endif
2686
2687 /**
2688  * g_socket_send:
2689  * @socket: a #GSocket
2690  * @buffer: (array length=size) (element-type guint8): the buffer
2691  *     containing the data to send.
2692  * @size: the number of bytes to send
2693  * @cancellable: (allow-none): a %GCancellable or %NULL
2694  * @error: #GError for error reporting, or %NULL to ignore.
2695  *
2696  * Tries to send @size bytes from @buffer on the socket. This is
2697  * mainly used by connection-oriented sockets; it is identical to
2698  * g_socket_send_to() with @address set to %NULL.
2699  *
2700  * If the socket is in blocking mode the call will block until there is
2701  * space for the data in the socket queue. If there is no space available
2702  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2703  * will be returned. To be notified when space is available, wait for the
2704  * %G_IO_OUT condition. Note though that you may still receive
2705  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2706  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2707  * very common due to the way the underlying APIs work.)
2708  *
2709  * On error -1 is returned and @error is set accordingly.
2710  *
2711  * Returns: Number of bytes written (which may be less than @size), or -1
2712  * on error
2713  *
2714  * Since: 2.22
2715  */
2716 gssize
2717 g_socket_send (GSocket       *socket,
2718                const gchar   *buffer,
2719                gsize          size,
2720                GCancellable  *cancellable,
2721                GError       **error)
2722 {
2723   return g_socket_send_with_blocking (socket, buffer, size,
2724                                       socket->priv->blocking,
2725                                       cancellable, error);
2726 }
2727
2728 /**
2729  * g_socket_send_with_blocking:
2730  * @socket: a #GSocket
2731  * @buffer: (array length=size) (element-type guint8): the buffer
2732  *     containing the data to send.
2733  * @size: the number of bytes to send
2734  * @blocking: whether to do blocking or non-blocking I/O
2735  * @cancellable: (allow-none): a %GCancellable or %NULL
2736  * @error: #GError for error reporting, or %NULL to ignore.
2737  *
2738  * This behaves exactly the same as g_socket_send(), except that
2739  * the choice of blocking or non-blocking behavior is determined by
2740  * the @blocking argument rather than by @socket's properties.
2741  *
2742  * Returns: Number of bytes written (which may be less than @size), or -1
2743  * on error
2744  *
2745  * Since: 2.26
2746  */
2747 gssize
2748 g_socket_send_with_blocking (GSocket       *socket,
2749                              const gchar   *buffer,
2750                              gsize          size,
2751                              gboolean       blocking,
2752                              GCancellable  *cancellable,
2753                              GError       **error)
2754 {
2755   gssize ret;
2756
2757   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2758
2759   if (!check_socket (socket, error))
2760     return -1;
2761
2762   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2763     return -1;
2764
2765   while (1)
2766     {
2767       if (blocking &&
2768           !g_socket_condition_wait (socket,
2769                                     G_IO_OUT, cancellable, error))
2770         return -1;
2771
2772       if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2773         {
2774           int errsv = get_socket_errno ();
2775
2776           if (errsv == EINTR)
2777             continue;
2778
2779 #ifdef WSAEWOULDBLOCK
2780           if (errsv == WSAEWOULDBLOCK)
2781             win32_unset_event_mask (socket, FD_WRITE);
2782 #endif
2783
2784           if (blocking)
2785             {
2786 #ifdef WSAEWOULDBLOCK
2787               if (errsv == WSAEWOULDBLOCK)
2788                 continue;
2789 #else
2790               if (errsv == EWOULDBLOCK ||
2791                   errsv == EAGAIN)
2792                 continue;
2793 #endif
2794             }
2795
2796           g_set_error (error, G_IO_ERROR,
2797                        socket_io_error_from_errno (errsv),
2798                        _("Error sending data: %s"), socket_strerror (errsv));
2799           return -1;
2800         }
2801       break;
2802     }
2803
2804   return ret;
2805 }
2806
2807 /**
2808  * g_socket_send_to:
2809  * @socket: a #GSocket
2810  * @address: (allow-none): a #GSocketAddress, or %NULL
2811  * @buffer: (array length=size) (element-type guint8): the buffer
2812  *     containing the data to send.
2813  * @size: the number of bytes to send
2814  * @cancellable: (allow-none): a %GCancellable or %NULL
2815  * @error: #GError for error reporting, or %NULL to ignore.
2816  *
2817  * Tries to send @size bytes from @buffer to @address. If @address is
2818  * %NULL then the message is sent to the default receiver (set by
2819  * g_socket_connect()).
2820  *
2821  * See g_socket_send() for additional information.
2822  *
2823  * Returns: Number of bytes written (which may be less than @size), or -1
2824  * on error
2825  *
2826  * Since: 2.22
2827  */
2828 gssize
2829 g_socket_send_to (GSocket         *socket,
2830                   GSocketAddress  *address,
2831                   const gchar     *buffer,
2832                   gsize            size,
2833                   GCancellable    *cancellable,
2834                   GError         **error)
2835 {
2836   GOutputVector v;
2837
2838   v.buffer = buffer;
2839   v.size = size;
2840
2841   return g_socket_send_message (socket,
2842                                 address,
2843                                 &v, 1,
2844                                 NULL, 0,
2845                                 0,
2846                                 cancellable,
2847                                 error);
2848 }
2849
2850 /**
2851  * g_socket_shutdown:
2852  * @socket: a #GSocket
2853  * @shutdown_read: whether to shut down the read side
2854  * @shutdown_write: whether to shut down the write side
2855  * @error: #GError for error reporting, or %NULL to ignore.
2856  *
2857  * Shut down part of a full-duplex connection.
2858  *
2859  * If @shutdown_read is %TRUE then the receiving side of the connection
2860  * is shut down, and further reading is disallowed.
2861  *
2862  * If @shutdown_write is %TRUE then the sending side of the connection
2863  * is shut down, and further writing is disallowed.
2864  *
2865  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2866  *
2867  * One example where this is used is graceful disconnect for TCP connections
2868  * where you close the sending side, then wait for the other side to close
2869  * the connection, thus ensuring that the other side saw all sent data.
2870  *
2871  * Returns: %TRUE on success, %FALSE on error
2872  *
2873  * Since: 2.22
2874  */
2875 gboolean
2876 g_socket_shutdown (GSocket   *socket,
2877                    gboolean   shutdown_read,
2878                    gboolean   shutdown_write,
2879                    GError   **error)
2880 {
2881   int how;
2882
2883   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2884
2885   if (!check_socket (socket, error))
2886     return FALSE;
2887
2888   /* Do nothing? */
2889   if (!shutdown_read && !shutdown_write)
2890     return TRUE;
2891
2892 #ifndef G_OS_WIN32
2893   if (shutdown_read && shutdown_write)
2894     how = SHUT_RDWR;
2895   else if (shutdown_read)
2896     how = SHUT_RD;
2897   else
2898     how = SHUT_WR;
2899 #else
2900   if (shutdown_read && shutdown_write)
2901     how = SD_BOTH;
2902   else if (shutdown_read)
2903     how = SD_RECEIVE;
2904   else
2905     how = SD_SEND;
2906 #endif
2907
2908   if (shutdown (socket->priv->fd, how) != 0)
2909     {
2910       int errsv = get_socket_errno ();
2911       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2912                    _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2913       return FALSE;
2914     }
2915
2916   if (shutdown_read && shutdown_write)
2917     socket->priv->connected = FALSE;
2918
2919   return TRUE;
2920 }
2921
2922 /**
2923  * g_socket_close:
2924  * @socket: a #GSocket
2925  * @error: #GError for error reporting, or %NULL to ignore.
2926  *
2927  * Closes the socket, shutting down any active connection.
2928  *
2929  * Closing a socket does not wait for all outstanding I/O operations
2930  * to finish, so the caller should not rely on them to be guaranteed
2931  * to complete even if the close returns with no error.
2932  *
2933  * Once the socket is closed, all other operations will return
2934  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2935  * return an error.
2936  *
2937  * Sockets will be automatically closed when the last reference
2938  * is dropped, but you might want to call this function to make sure
2939  * resources are released as early as possible.
2940  *
2941  * Beware that due to the way that TCP works, it is possible for
2942  * recently-sent data to be lost if either you close a socket while the
2943  * %G_IO_IN condition is set, or else if the remote connection tries to
2944  * send something to you after you close the socket but before it has
2945  * finished reading all of the data you sent. There is no easy generic
2946  * way to avoid this problem; the easiest fix is to design the network
2947  * protocol such that the client will never send data "out of turn".
2948  * Another solution is for the server to half-close the connection by
2949  * calling g_socket_shutdown() with only the @shutdown_write flag set,
2950  * and then wait for the client to notice this and close its side of the
2951  * connection, after which the server can safely call g_socket_close().
2952  * (This is what #GTcpConnection does if you call
2953  * g_tcp_connection_set_graceful_disconnect(). But of course, this
2954  * only works if the client will close its connection after the server
2955  * does.)
2956  *
2957  * Returns: %TRUE on success, %FALSE on error
2958  *
2959  * Since: 2.22
2960  */
2961 gboolean
2962 g_socket_close (GSocket  *socket,
2963                 GError  **error)
2964 {
2965   int res;
2966
2967   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2968
2969   if (socket->priv->closed)
2970     return TRUE; /* Multiple close not an error */
2971
2972   if (!check_socket (socket, error))
2973     return FALSE;
2974
2975   while (1)
2976     {
2977 #ifdef G_OS_WIN32
2978       res = closesocket (socket->priv->fd);
2979 #else
2980       res = close (socket->priv->fd);
2981 #endif
2982       if (res == -1)
2983         {
2984           int errsv = get_socket_errno ();
2985
2986           if (errsv == EINTR)
2987             continue;
2988
2989           g_set_error (error, G_IO_ERROR,
2990                        socket_io_error_from_errno (errsv),
2991                        _("Error closing socket: %s"),
2992                        socket_strerror (errsv));
2993           return FALSE;
2994         }
2995       break;
2996     }
2997
2998   socket->priv->connected = FALSE;
2999   socket->priv->closed = TRUE;
3000   if (socket->priv->remote_address)
3001     {
3002       g_object_unref (socket->priv->remote_address);
3003       socket->priv->remote_address = NULL;
3004     }
3005
3006   return TRUE;
3007 }
3008
3009 /**
3010  * g_socket_is_closed:
3011  * @socket: a #GSocket
3012  *
3013  * Checks whether a socket is closed.
3014  *
3015  * Returns: %TRUE if socket is closed, %FALSE otherwise
3016  *
3017  * Since: 2.22
3018  */
3019 gboolean
3020 g_socket_is_closed (GSocket *socket)
3021 {
3022   return socket->priv->closed;
3023 }
3024
3025 #ifdef G_OS_WIN32
3026 /* Broken source, used on errors */
3027 static gboolean
3028 broken_dispatch (GSource     *source,
3029                  GSourceFunc  callback,
3030                  gpointer     user_data)
3031 {
3032   return TRUE;
3033 }
3034
3035 static GSourceFuncs broken_funcs =
3036 {
3037   NULL,
3038   NULL,
3039   broken_dispatch,
3040   NULL
3041 };
3042
3043 static gint
3044 network_events_for_condition (GIOCondition condition)
3045 {
3046   int event_mask = 0;
3047
3048   if (condition & G_IO_IN)
3049     event_mask |= (FD_READ | FD_ACCEPT);
3050   if (condition & G_IO_OUT)
3051     event_mask |= (FD_WRITE | FD_CONNECT);
3052   event_mask |= FD_CLOSE;
3053
3054   return event_mask;
3055 }
3056
3057 static void
3058 ensure_event (GSocket *socket)
3059 {
3060   if (socket->priv->event == WSA_INVALID_EVENT)
3061     socket->priv->event = WSACreateEvent();
3062 }
3063
3064 static void
3065 update_select_events (GSocket *socket)
3066 {
3067   int event_mask;
3068   GIOCondition *ptr;
3069   GList *l;
3070   WSAEVENT event;
3071
3072   ensure_event (socket);
3073
3074   event_mask = 0;
3075   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3076     {
3077       ptr = l->data;
3078       event_mask |= network_events_for_condition (*ptr);
3079     }
3080
3081   if (event_mask != socket->priv->selected_events)
3082     {
3083       /* If no events selected, disable event so we can unset
3084          nonblocking mode */
3085
3086       if (event_mask == 0)
3087         event = NULL;
3088       else
3089         event = socket->priv->event;
3090
3091       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3092         socket->priv->selected_events = event_mask;
3093     }
3094 }
3095
3096 static void
3097 add_condition_watch (GSocket      *socket,
3098                      GIOCondition *condition)
3099 {
3100   g_mutex_lock (&socket->priv->win32_source_lock);
3101   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3102
3103   socket->priv->requested_conditions =
3104     g_list_prepend (socket->priv->requested_conditions, condition);
3105
3106   update_select_events (socket);
3107   g_mutex_unlock (&socket->priv->win32_source_lock);
3108 }
3109
3110 static void
3111 remove_condition_watch (GSocket      *socket,
3112                         GIOCondition *condition)
3113 {
3114   g_mutex_lock (&socket->priv->win32_source_lock);
3115   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3116
3117   socket->priv->requested_conditions =
3118     g_list_remove (socket->priv->requested_conditions, condition);
3119
3120   update_select_events (socket);
3121   g_mutex_unlock (&socket->priv->win32_source_lock);
3122 }
3123
3124 static GIOCondition
3125 update_condition (GSocket *socket)
3126 {
3127   WSANETWORKEVENTS events;
3128   GIOCondition condition;
3129
3130   if (WSAEnumNetworkEvents (socket->priv->fd,
3131                             socket->priv->event,
3132                             &events) == 0)
3133     {
3134       socket->priv->current_events |= events.lNetworkEvents;
3135       if (events.lNetworkEvents & FD_WRITE &&
3136           events.iErrorCode[FD_WRITE_BIT] != 0)
3137         socket->priv->current_errors |= FD_WRITE;
3138       if (events.lNetworkEvents & FD_CONNECT &&
3139           events.iErrorCode[FD_CONNECT_BIT] != 0)
3140         socket->priv->current_errors |= FD_CONNECT;
3141     }
3142
3143   condition = 0;
3144   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3145     condition |= G_IO_IN;
3146
3147   if (socket->priv->current_events & FD_CLOSE)
3148     {
3149       int r, errsv, buffer;
3150
3151       r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3152       if (r < 0)
3153           errsv = get_socket_errno ();
3154
3155       if (r > 0 ||
3156           (r < 0 && errsv == WSAENOTCONN))
3157         condition |= G_IO_IN;
3158       else if (r == 0 ||
3159                (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3160                           errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3161         condition |= G_IO_HUP;
3162       else
3163         condition |= G_IO_ERR;
3164     }
3165
3166   if (socket->priv->closed)
3167     condition |= G_IO_HUP;
3168
3169   /* Never report both G_IO_OUT and HUP, these are
3170      mutually exclusive (can't write to a closed socket) */
3171   if ((condition & G_IO_HUP) == 0 &&
3172       socket->priv->current_events & FD_WRITE)
3173     {
3174       if (socket->priv->current_errors & FD_WRITE)
3175         condition |= G_IO_ERR;
3176       else
3177         condition |= G_IO_OUT;
3178     }
3179   else
3180     {
3181       if (socket->priv->current_events & FD_CONNECT)
3182         {
3183           if (socket->priv->current_errors & FD_CONNECT)
3184             condition |= (G_IO_HUP | G_IO_ERR);
3185           else
3186             condition |= G_IO_OUT;
3187         }
3188     }
3189
3190   return condition;
3191 }
3192 #endif
3193
3194 typedef struct {
3195   GSource       source;
3196   GPollFD       pollfd;
3197   GSocket      *socket;
3198   GIOCondition  condition;
3199   GCancellable *cancellable;
3200   GPollFD       cancel_pollfd;
3201   gint64        timeout_time;
3202 } GSocketSource;
3203
3204 static gboolean
3205 socket_source_prepare (GSource *source,
3206                        gint    *timeout)
3207 {
3208   GSocketSource *socket_source = (GSocketSource *)source;
3209
3210   if (g_cancellable_is_cancelled (socket_source->cancellable))
3211     return TRUE;
3212
3213   if (socket_source->timeout_time)
3214     {
3215       gint64 now;
3216
3217       now = g_source_get_time (source);
3218       /* Round up to ensure that we don't try again too early */
3219       *timeout = (socket_source->timeout_time - now + 999) / 1000;
3220       if (*timeout < 0)
3221         {
3222           socket_source->socket->priv->timed_out = TRUE;
3223           *timeout = 0;
3224           return TRUE;
3225         }
3226     }
3227   else
3228     *timeout = -1;
3229
3230 #ifdef G_OS_WIN32
3231   socket_source->pollfd.revents = update_condition (socket_source->socket);
3232 #endif
3233
3234   if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3235     return TRUE;
3236
3237   return FALSE;
3238 }
3239
3240 static gboolean
3241 socket_source_check (GSource *source)
3242 {
3243   int timeout;
3244
3245   return socket_source_prepare (source, &timeout);
3246 }
3247
3248 static gboolean
3249 socket_source_dispatch (GSource     *source,
3250                         GSourceFunc  callback,
3251                         gpointer     user_data)
3252 {
3253   GSocketSourceFunc func = (GSocketSourceFunc)callback;
3254   GSocketSource *socket_source = (GSocketSource *)source;
3255   GSocket *socket = socket_source->socket;
3256   gboolean ret;
3257
3258 #ifdef G_OS_WIN32
3259   socket_source->pollfd.revents = update_condition (socket_source->socket);
3260 #endif
3261   if (socket_source->socket->priv->timed_out)
3262     socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3263
3264   ret = (*func) (socket,
3265                  socket_source->pollfd.revents & socket_source->condition,
3266                  user_data);
3267
3268   if (socket->priv->timeout)
3269     socket_source->timeout_time = g_get_monotonic_time () +
3270                                   socket->priv->timeout * 1000000;
3271
3272   else
3273     socket_source->timeout_time = 0;
3274
3275   return ret;
3276 }
3277
3278 static void
3279 socket_source_finalize (GSource *source)
3280 {
3281   GSocketSource *socket_source = (GSocketSource *)source;
3282   GSocket *socket;
3283
3284   socket = socket_source->socket;
3285
3286 #ifdef G_OS_WIN32
3287   remove_condition_watch (socket, &socket_source->condition);
3288 #endif
3289
3290   g_object_unref (socket);
3291
3292   if (socket_source->cancellable)
3293     {
3294       g_cancellable_release_fd (socket_source->cancellable);
3295       g_object_unref (socket_source->cancellable);
3296     }
3297 }
3298
3299 static gboolean
3300 socket_source_closure_callback (GSocket      *socket,
3301                                 GIOCondition  condition,
3302                                 gpointer      data)
3303 {
3304   GClosure *closure = data;
3305
3306   GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3307   GValue result_value = G_VALUE_INIT;
3308   gboolean result;
3309
3310   g_value_init (&result_value, G_TYPE_BOOLEAN);
3311
3312   g_value_init (&params[0], G_TYPE_SOCKET);
3313   g_value_set_object (&params[0], socket);
3314   g_value_init (&params[1], G_TYPE_IO_CONDITION);
3315   g_value_set_flags (&params[1], condition);
3316
3317   g_closure_invoke (closure, &result_value, 2, params, NULL);
3318
3319   result = g_value_get_boolean (&result_value);
3320   g_value_unset (&result_value);
3321   g_value_unset (&params[0]);
3322   g_value_unset (&params[1]);
3323
3324   return result;
3325 }
3326
3327 static GSourceFuncs socket_source_funcs =
3328 {
3329   socket_source_prepare,
3330   socket_source_check,
3331   socket_source_dispatch,
3332   socket_source_finalize,
3333   (GSourceFunc)socket_source_closure_callback,
3334 };
3335
3336 static GSource *
3337 socket_source_new (GSocket      *socket,
3338                    GIOCondition  condition,
3339                    GCancellable *cancellable)
3340 {
3341   GSource *source;
3342   GSocketSource *socket_source;
3343
3344 #ifdef G_OS_WIN32
3345   ensure_event (socket);
3346
3347   if (socket->priv->event == WSA_INVALID_EVENT)
3348     {
3349       g_warning ("Failed to create WSAEvent");
3350       return g_source_new (&broken_funcs, sizeof (GSource));
3351     }
3352 #endif
3353
3354   condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3355
3356   source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3357   g_source_set_name (source, "GSocket");
3358   socket_source = (GSocketSource *)source;
3359
3360   socket_source->socket = g_object_ref (socket);
3361   socket_source->condition = condition;
3362
3363   if (g_cancellable_make_pollfd (cancellable,
3364                                  &socket_source->cancel_pollfd))
3365     {
3366       socket_source->cancellable = g_object_ref (cancellable);
3367       g_source_add_poll (source, &socket_source->cancel_pollfd);
3368     }
3369
3370 #ifdef G_OS_WIN32
3371   add_condition_watch (socket, &socket_source->condition);
3372   socket_source->pollfd.fd = (gintptr) socket->priv->event;
3373 #else
3374   socket_source->pollfd.fd = socket->priv->fd;
3375 #endif
3376
3377   socket_source->pollfd.events = condition;
3378   socket_source->pollfd.revents = 0;
3379   g_source_add_poll (source, &socket_source->pollfd);
3380
3381   if (socket->priv->timeout)
3382     socket_source->timeout_time = g_get_monotonic_time () +
3383                                   socket->priv->timeout * 1000000;
3384
3385   else
3386     socket_source->timeout_time = 0;
3387
3388   return source;
3389 }
3390
3391 /**
3392  * g_socket_create_source: (skip)
3393  * @socket: a #GSocket
3394  * @condition: a #GIOCondition mask to monitor
3395  * @cancellable: (allow-none): a %GCancellable or %NULL
3396  *
3397  * Creates a %GSource that can be attached to a %GMainContext to monitor
3398  * for the availibility of the specified @condition on the socket.
3399  *
3400  * The callback on the source is of the #GSocketSourceFunc type.
3401  *
3402  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3403  * these conditions will always be reported output if they are true.
3404  *
3405  * @cancellable if not %NULL can be used to cancel the source, which will
3406  * cause the source to trigger, reporting the current condition (which
3407  * is likely 0 unless cancellation happened at the same time as a
3408  * condition change). You can check for this in the callback using
3409  * g_cancellable_is_cancelled().
3410  *
3411  * If @socket has a timeout set, and it is reached before @condition
3412  * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3413  * %G_IO_OUT depending on @condition. However, @socket will have been
3414  * marked as having had a timeout, and so the next #GSocket I/O method
3415  * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3416  *
3417  * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3418  *
3419  * Since: 2.22
3420  */
3421 GSource *
3422 g_socket_create_source (GSocket      *socket,
3423                         GIOCondition  condition,
3424                         GCancellable *cancellable)
3425 {
3426   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3427
3428   return socket_source_new (socket, condition, cancellable);
3429 }
3430
3431 /**
3432  * g_socket_condition_check:
3433  * @socket: a #GSocket
3434  * @condition: a #GIOCondition mask to check
3435  *
3436  * Checks on the readiness of @socket to perform operations.
3437  * The operations specified in @condition are checked for and masked
3438  * against the currently-satisfied conditions on @socket. The result
3439  * is returned.
3440  *
3441  * Note that on Windows, it is possible for an operation to return
3442  * %G_IO_ERROR_WOULD_BLOCK even immediately after
3443  * g_socket_condition_check() has claimed that the socket is ready for
3444  * writing. Rather than calling g_socket_condition_check() and then
3445  * writing to the socket if it succeeds, it is generally better to
3446  * simply try writing to the socket right away, and try again later if
3447  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3448  *
3449  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3450  * these conditions will always be set in the output if they are true.
3451  *
3452  * This call never blocks.
3453  *
3454  * Returns: the @GIOCondition mask of the current state
3455  *
3456  * Since: 2.22
3457  */
3458 GIOCondition
3459 g_socket_condition_check (GSocket      *socket,
3460                           GIOCondition  condition)
3461 {
3462   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3463
3464   if (!check_socket (socket, NULL))
3465     return 0;
3466
3467 #ifdef G_OS_WIN32
3468   {
3469     GIOCondition current_condition;
3470
3471     condition |= G_IO_ERR | G_IO_HUP;
3472
3473     add_condition_watch (socket, &condition);
3474     current_condition = update_condition (socket);
3475     remove_condition_watch (socket, &condition);
3476     return condition & current_condition;
3477   }
3478 #else
3479   {
3480     GPollFD poll_fd;
3481     gint result;
3482     poll_fd.fd = socket->priv->fd;
3483     poll_fd.events = condition;
3484     poll_fd.revents = 0;
3485
3486     do
3487       result = g_poll (&poll_fd, 1, 0);
3488     while (result == -1 && get_socket_errno () == EINTR);
3489
3490     return poll_fd.revents;
3491   }
3492 #endif
3493 }
3494
3495 /**
3496  * g_socket_condition_wait:
3497  * @socket: a #GSocket
3498  * @condition: a #GIOCondition mask to wait for
3499  * @cancellable: (allow-none): a #GCancellable, or %NULL
3500  * @error: a #GError pointer, or %NULL
3501  *
3502  * Waits for @condition to become true on @socket. When the condition
3503  * is met, %TRUE is returned.
3504  *
3505  * If @cancellable is cancelled before the condition is met, or if the
3506  * socket has a timeout set and it is reached before the condition is
3507  * met, then %FALSE is returned and @error, if non-%NULL, is set to
3508  * the appropriate value (%G_IO_ERROR_CANCELLED or
3509  * %G_IO_ERROR_TIMED_OUT).
3510  *
3511  * See also g_socket_condition_timed_wait().
3512  *
3513  * Returns: %TRUE if the condition was met, %FALSE otherwise
3514  *
3515  * Since: 2.22
3516  */
3517 gboolean
3518 g_socket_condition_wait (GSocket       *socket,
3519                          GIOCondition   condition,
3520                          GCancellable  *cancellable,
3521                          GError       **error)
3522 {
3523   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3524
3525   return g_socket_condition_timed_wait (socket, condition, -1,
3526                                         cancellable, error);
3527 }
3528
3529 /**
3530  * g_socket_condition_timed_wait:
3531  * @socket: a #GSocket
3532  * @condition: a #GIOCondition mask to wait for
3533  * @timeout: the maximum time (in microseconds) to wait, or -1
3534  * @cancellable: (allow-none): a #GCancellable, or %NULL
3535  * @error: a #GError pointer, or %NULL
3536  *
3537  * Waits for up to @timeout microseconds for @condition to become true
3538  * on @socket. If the condition is met, %TRUE is returned.
3539  *
3540  * If @cancellable is cancelled before the condition is met, or if
3541  * @timeout (or the socket's #GSocket:timeout) is reached before the
3542  * condition is met, then %FALSE is returned and @error, if non-%NULL,
3543  * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3544  * %G_IO_ERROR_TIMED_OUT).
3545  *
3546  * If you don't want a timeout, use g_socket_condition_wait().
3547  * (Alternatively, you can pass -1 for @timeout.)
3548  *
3549  * Note that although @timeout is in microseconds for consistency with
3550  * other GLib APIs, this function actually only has millisecond
3551  * resolution, and the behavior is undefined if @timeout is not an
3552  * exact number of milliseconds.
3553  *
3554  * Returns: %TRUE if the condition was met, %FALSE otherwise
3555  *
3556  * Since: 2.32
3557  */
3558 gboolean
3559 g_socket_condition_timed_wait (GSocket       *socket,
3560                                GIOCondition   condition,
3561                                gint64         timeout,
3562                                GCancellable  *cancellable,
3563                                GError       **error)
3564 {
3565   gint64 start_time;
3566
3567   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3568
3569   if (!check_socket (socket, error))
3570     return FALSE;
3571
3572   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3573     return FALSE;
3574
3575   if (socket->priv->timeout &&
3576       (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3577     timeout = socket->priv->timeout * 1000;
3578   else if (timeout != -1)
3579     timeout = timeout / 1000;
3580
3581   start_time = g_get_monotonic_time ();
3582
3583 #ifdef G_OS_WIN32
3584   {
3585     GIOCondition current_condition;
3586     WSAEVENT events[2];
3587     DWORD res;
3588     GPollFD cancel_fd;
3589     int num_events;
3590
3591     /* Always check these */
3592     condition |=  G_IO_ERR | G_IO_HUP;
3593
3594     add_condition_watch (socket, &condition);
3595
3596     num_events = 0;
3597     events[num_events++] = socket->priv->event;
3598
3599     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3600       events[num_events++] = (WSAEVENT)cancel_fd.fd;
3601
3602     if (timeout == -1)
3603       timeout = WSA_INFINITE;
3604
3605     current_condition = update_condition (socket);
3606     while ((condition & current_condition) == 0)
3607       {
3608         res = WSAWaitForMultipleEvents (num_events, events,
3609                                         FALSE, timeout, FALSE);
3610         if (res == WSA_WAIT_FAILED)
3611           {
3612             int errsv = get_socket_errno ();
3613
3614             g_set_error (error, G_IO_ERROR,
3615                          socket_io_error_from_errno (errsv),
3616                          _("Waiting for socket condition: %s"),
3617                          socket_strerror (errsv));
3618             break;
3619           }
3620         else if (res == WSA_WAIT_TIMEOUT)
3621           {
3622             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3623                                  _("Socket I/O timed out"));
3624             break;
3625           }
3626
3627         if (g_cancellable_set_error_if_cancelled (cancellable, error))
3628           break;
3629
3630         current_condition = update_condition (socket);
3631
3632         if (timeout != WSA_INFINITE)
3633           {
3634             timeout -= (g_get_monotonic_time () - start_time) * 1000;
3635             if (timeout < 0)
3636               timeout = 0;
3637           }
3638       }
3639     remove_condition_watch (socket, &condition);
3640     if (num_events > 1)
3641       g_cancellable_release_fd (cancellable);
3642
3643     return (condition & current_condition) != 0;
3644   }
3645 #else
3646   {
3647     GPollFD poll_fd[2];
3648     gint result;
3649     gint num;
3650
3651     poll_fd[0].fd = socket->priv->fd;
3652     poll_fd[0].events = condition;
3653     num = 1;
3654
3655     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3656       num++;
3657
3658     while (TRUE)
3659       {
3660         result = g_poll (poll_fd, num, timeout);
3661         if (result != -1 || errno != EINTR)
3662           break;
3663
3664         if (timeout != -1)
3665           {
3666             timeout -= (g_get_monotonic_time () - start_time) * 1000;
3667             if (timeout < 0)
3668               timeout = 0;
3669           }
3670       }
3671     
3672     if (num > 1)
3673       g_cancellable_release_fd (cancellable);
3674
3675     if (result == 0)
3676       {
3677         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3678                              _("Socket I/O timed out"));
3679         return FALSE;
3680       }
3681
3682     return !g_cancellable_set_error_if_cancelled (cancellable, error);
3683   }
3684   #endif
3685 }
3686
3687 /**
3688  * g_socket_send_message:
3689  * @socket: a #GSocket
3690  * @address: (allow-none): a #GSocketAddress, or %NULL
3691  * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3692  * @num_vectors: the number of elements in @vectors, or -1
3693  * @messages: (array length=num_messages) (allow-none): a pointer to an
3694  *   array of #GSocketControlMessages, or %NULL.
3695  * @num_messages: number of elements in @messages, or -1.
3696  * @flags: an int containing #GSocketMsgFlags flags
3697  * @cancellable: (allow-none): a %GCancellable or %NULL
3698  * @error: #GError for error reporting, or %NULL to ignore.
3699  *
3700  * Send data to @address on @socket.  This is the most complicated and
3701  * fully-featured version of this call. For easier use, see
3702  * g_socket_send() and g_socket_send_to().
3703  *
3704  * If @address is %NULL then the message is sent to the default receiver
3705  * (set by g_socket_connect()).
3706  *
3707  * @vectors must point to an array of #GOutputVector structs and
3708  * @num_vectors must be the length of this array. (If @num_vectors is -1,
3709  * then @vectors is assumed to be terminated by a #GOutputVector with a
3710  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3711  * that the sent data will be gathered from. Using multiple
3712  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3713  * data from multiple sources into a single buffer, and more
3714  * network-efficient than making multiple calls to g_socket_send().
3715  *
3716  * @messages, if non-%NULL, is taken to point to an array of @num_messages
3717  * #GSocketControlMessage instances. These correspond to the control
3718  * messages to be sent on the socket.
3719  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3720  * array.
3721  *
3722  * @flags modify how the message is sent. The commonly available arguments
3723  * for this are available in the #GSocketMsgFlags enum, but the
3724  * values there are the same as the system values, and the flags
3725  * are passed in as-is, so you can pass in system-specific flags too.
3726  *
3727  * If the socket is in blocking mode the call will block until there is
3728  * space for the data in the socket queue. If there is no space available
3729  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3730  * will be returned. To be notified when space is available, wait for the
3731  * %G_IO_OUT condition. Note though that you may still receive
3732  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3733  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3734  * very common due to the way the underlying APIs work.)
3735  *
3736  * On error -1 is returned and @error is set accordingly.
3737  *
3738  * Returns: Number of bytes written (which may be less than @size), or -1
3739  * on error
3740  *
3741  * Since: 2.22
3742  */
3743 gssize
3744 g_socket_send_message (GSocket                *socket,
3745                        GSocketAddress         *address,
3746                        GOutputVector          *vectors,
3747                        gint                    num_vectors,
3748                        GSocketControlMessage **messages,
3749                        gint                    num_messages,
3750                        gint                    flags,
3751                        GCancellable           *cancellable,
3752                        GError                **error)
3753 {
3754   GOutputVector one_vector;
3755   char zero;
3756
3757   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3758
3759   if (!check_socket (socket, error))
3760     return -1;
3761
3762   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3763     return -1;
3764
3765   if (num_vectors == -1)
3766     {
3767       for (num_vectors = 0;
3768            vectors[num_vectors].buffer != NULL;
3769            num_vectors++)
3770         ;
3771     }
3772
3773   if (num_messages == -1)
3774     {
3775       for (num_messages = 0;
3776            messages != NULL && messages[num_messages] != NULL;
3777            num_messages++)
3778         ;
3779     }
3780
3781   if (num_vectors == 0)
3782     {
3783       zero = '\0';
3784
3785       one_vector.buffer = &zero;
3786       one_vector.size = 1;
3787       num_vectors = 1;
3788       vectors = &one_vector;
3789     }
3790
3791 #ifndef G_OS_WIN32
3792   {
3793     struct msghdr msg;
3794     gssize result;
3795
3796    msg.msg_flags = 0;
3797
3798     /* name */
3799     if (address)
3800       {
3801         msg.msg_namelen = g_socket_address_get_native_size (address);
3802         msg.msg_name = g_alloca (msg.msg_namelen);
3803         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3804           return -1;
3805       }
3806     else
3807       {
3808         msg.msg_name = NULL;
3809         msg.msg_namelen = 0;
3810       }
3811
3812     /* iov */
3813     {
3814       /* this entire expression will be evaluated at compile time */
3815       if (sizeof *msg.msg_iov == sizeof *vectors &&
3816           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3817           G_STRUCT_OFFSET (struct iovec, iov_base) ==
3818           G_STRUCT_OFFSET (GOutputVector, buffer) &&
3819           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3820           G_STRUCT_OFFSET (struct iovec, iov_len) ==
3821           G_STRUCT_OFFSET (GOutputVector, size))
3822         /* ABI is compatible */
3823         {
3824           msg.msg_iov = (struct iovec *) vectors;
3825           msg.msg_iovlen = num_vectors;
3826         }
3827       else
3828         /* ABI is incompatible */
3829         {
3830           gint i;
3831
3832           msg.msg_iov = g_newa (struct iovec, num_vectors);
3833           for (i = 0; i < num_vectors; i++)
3834             {
3835               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3836               msg.msg_iov[i].iov_len = vectors[i].size;
3837             }
3838           msg.msg_iovlen = num_vectors;
3839         }
3840     }
3841
3842     /* control */
3843     {
3844       struct cmsghdr *cmsg;
3845       gint i;
3846
3847       msg.msg_controllen = 0;
3848       for (i = 0; i < num_messages; i++)
3849         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3850
3851       if (msg.msg_controllen == 0)
3852         msg.msg_control = NULL;
3853       else
3854         {
3855           msg.msg_control = g_alloca (msg.msg_controllen);
3856           memset (msg.msg_control, '\0', msg.msg_controllen);
3857         }
3858
3859       cmsg = CMSG_FIRSTHDR (&msg);
3860       for (i = 0; i < num_messages; i++)
3861         {
3862           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3863           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3864           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3865           g_socket_control_message_serialize (messages[i],
3866                                               CMSG_DATA (cmsg));
3867           cmsg = CMSG_NXTHDR (&msg, cmsg);
3868         }
3869       g_assert (cmsg == NULL);
3870     }
3871
3872     while (1)
3873       {
3874         if (socket->priv->blocking &&
3875             !g_socket_condition_wait (socket,
3876                                       G_IO_OUT, cancellable, error))
3877           return -1;
3878
3879         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3880         if (result < 0)
3881           {
3882             int errsv = get_socket_errno ();
3883
3884             if (errsv == EINTR)
3885               continue;
3886
3887             if (socket->priv->blocking &&
3888                 (errsv == EWOULDBLOCK ||
3889                  errsv == EAGAIN))
3890               continue;
3891
3892             g_set_error (error, G_IO_ERROR,
3893                          socket_io_error_from_errno (errsv),
3894                          _("Error sending message: %s"), socket_strerror (errsv));
3895
3896             return -1;
3897           }
3898         break;
3899       }
3900
3901     return result;
3902   }
3903 #else
3904   {
3905     struct sockaddr_storage addr;
3906     guint addrlen;
3907     DWORD bytes_sent;
3908     int result;
3909     WSABUF *bufs;
3910     gint i;
3911
3912     /* Win32 doesn't support control messages.
3913        Actually this is possible for raw and datagram sockets
3914        via WSASendMessage on Vista or later, but that doesn't
3915        seem very useful */
3916     if (num_messages != 0)
3917       {
3918         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3919                              _("GSocketControlMessage not supported on Windows"));
3920         return -1;
3921       }
3922
3923     /* iov */
3924     bufs = g_newa (WSABUF, num_vectors);
3925     for (i = 0; i < num_vectors; i++)
3926       {
3927         bufs[i].buf = (char *)vectors[i].buffer;
3928         bufs[i].len = (gulong)vectors[i].size;
3929       }
3930
3931     /* name */
3932     addrlen = 0; /* Avoid warning */
3933     if (address)
3934       {
3935         addrlen = g_socket_address_get_native_size (address);
3936         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3937           return -1;
3938       }
3939
3940     while (1)
3941       {
3942         if (socket->priv->blocking &&
3943             !g_socket_condition_wait (socket,
3944                                       G_IO_OUT, cancellable, error))
3945           return -1;
3946
3947         if (address)
3948           result = WSASendTo (socket->priv->fd,
3949                               bufs, num_vectors,
3950                               &bytes_sent, flags,
3951                               (const struct sockaddr *)&addr, addrlen,
3952                               NULL, NULL);
3953         else
3954           result = WSASend (socket->priv->fd,
3955                             bufs, num_vectors,
3956                             &bytes_sent, flags,
3957                             NULL, NULL);
3958
3959         if (result != 0)
3960           {
3961             int errsv = get_socket_errno ();
3962
3963             if (errsv == WSAEINTR)
3964               continue;
3965
3966             if (errsv == WSAEWOULDBLOCK)
3967               win32_unset_event_mask (socket, FD_WRITE);
3968
3969             if (socket->priv->blocking &&
3970                 errsv == WSAEWOULDBLOCK)
3971               continue;
3972
3973             g_set_error (error, G_IO_ERROR,
3974                          socket_io_error_from_errno (errsv),
3975                          _("Error sending message: %s"), socket_strerror (errsv));
3976
3977             return -1;
3978           }
3979         break;
3980       }
3981
3982     return bytes_sent;
3983   }
3984 #endif
3985 }
3986
3987 static GSocketAddress *
3988 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3989 {
3990   GSocketAddress *saddr;
3991   gint i;
3992   guint64 oldest_time = G_MAXUINT64;
3993   gint oldest_index = 0;
3994
3995   if (native_len <= 0)
3996     return NULL;
3997
3998   saddr = NULL;
3999   for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
4000     {
4001       GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
4002       gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
4003       gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
4004
4005       if (!tmp)
4006         continue;
4007
4008       if (tmp_native_len != native_len)
4009         continue;
4010
4011       if (memcmp (tmp_native, native, native_len) == 0)
4012         {
4013           saddr = g_object_ref (tmp);
4014           socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4015           return saddr;
4016         }
4017
4018       if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4019         {
4020           oldest_time = socket->priv->recv_addr_cache[i].last_used;
4021           oldest_index = i;
4022         }
4023     }
4024
4025   saddr = g_socket_address_new_from_native (native, native_len);
4026
4027   if (socket->priv->recv_addr_cache[oldest_index].addr)
4028     {
4029       g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4030       g_free (socket->priv->recv_addr_cache[oldest_index].native);
4031     }
4032
4033   socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4034   socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4035   socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4036   socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4037
4038   return saddr;
4039 }
4040
4041 /**
4042  * g_socket_receive_message:
4043  * @socket: a #GSocket
4044  * @address: (out) (allow-none): a pointer to a #GSocketAddress
4045  *     pointer, or %NULL
4046  * @vectors: (array length=num_vectors): an array of #GInputVector structs
4047  * @num_vectors: the number of elements in @vectors, or -1
4048  * @messages: (array length=num_messages) (allow-none): a pointer which
4049  *    may be filled with an array of #GSocketControlMessages, or %NULL
4050  * @num_messages: a pointer which will be filled with the number of
4051  *    elements in @messages, or %NULL
4052  * @flags: a pointer to an int containing #GSocketMsgFlags flags
4053  * @cancellable: (allow-none): a %GCancellable or %NULL
4054  * @error: a #GError pointer, or %NULL
4055  *
4056  * Receive data from a socket.  This is the most complicated and
4057  * fully-featured version of this call. For easier use, see
4058  * g_socket_receive() and g_socket_receive_from().
4059  *
4060  * If @address is non-%NULL then @address will be set equal to the
4061  * source address of the received packet.
4062  * @address is owned by the caller.
4063  *
4064  * @vector must point to an array of #GInputVector structs and
4065  * @num_vectors must be the length of this array.  These structs
4066  * describe the buffers that received data will be scattered into.
4067  * If @num_vectors is -1, then @vectors is assumed to be terminated
4068  * by a #GInputVector with a %NULL buffer pointer.
4069  *
4070  * As a special case, if @num_vectors is 0 (in which case, @vectors
4071  * may of course be %NULL), then a single byte is received and
4072  * discarded. This is to facilitate the common practice of sending a
4073  * single '\0' byte for the purposes of transferring ancillary data.
4074  *
4075  * @messages, if non-%NULL, will be set to point to a newly-allocated
4076  * array of #GSocketControlMessage instances or %NULL if no such
4077  * messages was received. These correspond to the control messages
4078  * received from the kernel, one #GSocketControlMessage per message
4079  * from the kernel. This array is %NULL-terminated and must be freed
4080  * by the caller using g_free() after calling g_object_unref() on each
4081  * element. If @messages is %NULL, any control messages received will
4082  * be discarded.
4083  *
4084  * @num_messages, if non-%NULL, will be set to the number of control
4085  * messages received.
4086  *
4087  * If both @messages and @num_messages are non-%NULL, then
4088  * @num_messages gives the number of #GSocketControlMessage instances
4089  * in @messages (ie: not including the %NULL terminator).
4090  *
4091  * @flags is an in/out parameter. The commonly available arguments
4092  * for this are available in the #GSocketMsgFlags enum, but the
4093  * values there are the same as the system values, and the flags
4094  * are passed in as-is, so you can pass in system-specific flags too
4095  * (and g_socket_receive_message() may pass system-specific flags out).
4096  *
4097  * As with g_socket_receive(), data may be discarded if @socket is
4098  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4099  * provide enough buffer space to read a complete message. You can pass
4100  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4101  * removing it from the receive queue, but there is no portable way to find
4102  * out the length of the message other than by reading it into a
4103  * sufficiently-large buffer.
4104  *
4105  * If the socket is in blocking mode the call will block until there
4106  * is some data to receive, the connection is closed, or there is an
4107  * error. If there is no data available and the socket is in
4108  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4109  * returned. To be notified when data is available, wait for the
4110  * %G_IO_IN condition.
4111  *
4112  * On error -1 is returned and @error is set accordingly.
4113  *
4114  * Returns: Number of bytes read, or 0 if the connection was closed by
4115  * the peer, or -1 on error
4116  *
4117  * Since: 2.22
4118  */
4119 gssize
4120 g_socket_receive_message (GSocket                 *socket,
4121                           GSocketAddress         **address,
4122                           GInputVector            *vectors,
4123                           gint                     num_vectors,
4124                           GSocketControlMessage ***messages,
4125                           gint                    *num_messages,
4126                           gint                    *flags,
4127                           GCancellable            *cancellable,
4128                           GError                 **error)
4129 {
4130   GInputVector one_vector;
4131   char one_byte;
4132
4133   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4134
4135   if (!check_socket (socket, error))
4136     return -1;
4137
4138   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4139     return -1;
4140
4141   if (num_vectors == -1)
4142     {
4143       for (num_vectors = 0;
4144            vectors[num_vectors].buffer != NULL;
4145            num_vectors++)
4146         ;
4147     }
4148
4149   if (num_vectors == 0)
4150     {
4151       one_vector.buffer = &one_byte;
4152       one_vector.size = 1;
4153       num_vectors = 1;
4154       vectors = &one_vector;
4155     }
4156
4157 #ifndef G_OS_WIN32
4158   {
4159     struct msghdr msg;
4160     gssize result;
4161     struct sockaddr_storage one_sockaddr;
4162
4163     /* name */
4164     if (address)
4165       {
4166         msg.msg_name = &one_sockaddr;
4167         msg.msg_namelen = sizeof (struct sockaddr_storage);
4168       }
4169     else
4170       {
4171         msg.msg_name = NULL;
4172         msg.msg_namelen = 0;
4173       }
4174
4175     /* iov */
4176     /* this entire expression will be evaluated at compile time */
4177     if (sizeof *msg.msg_iov == sizeof *vectors &&
4178         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4179         G_STRUCT_OFFSET (struct iovec, iov_base) ==
4180         G_STRUCT_OFFSET (GInputVector, buffer) &&
4181         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4182         G_STRUCT_OFFSET (struct iovec, iov_len) ==
4183         G_STRUCT_OFFSET (GInputVector, size))
4184       /* ABI is compatible */
4185       {
4186         msg.msg_iov = (struct iovec *) vectors;
4187         msg.msg_iovlen = num_vectors;
4188       }
4189     else
4190       /* ABI is incompatible */
4191       {
4192         gint i;
4193
4194         msg.msg_iov = g_newa (struct iovec, num_vectors);
4195         for (i = 0; i < num_vectors; i++)
4196           {
4197             msg.msg_iov[i].iov_base = vectors[i].buffer;
4198             msg.msg_iov[i].iov_len = vectors[i].size;
4199           }
4200         msg.msg_iovlen = num_vectors;
4201       }
4202
4203     /* control */
4204     msg.msg_control = g_alloca (2048);
4205     msg.msg_controllen = 2048;
4206
4207     /* flags */
4208     if (flags != NULL)
4209       msg.msg_flags = *flags;
4210     else
4211       msg.msg_flags = 0;
4212
4213     /* We always set the close-on-exec flag so we don't leak file
4214      * descriptors into child processes.  Note that gunixfdmessage.c
4215      * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4216      */
4217 #ifdef MSG_CMSG_CLOEXEC
4218     msg.msg_flags |= MSG_CMSG_CLOEXEC;
4219 #endif
4220
4221     /* do it */
4222     while (1)
4223       {
4224         if (socket->priv->blocking &&
4225             !g_socket_condition_wait (socket,
4226                                       G_IO_IN, cancellable, error))
4227           return -1;
4228
4229         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4230 #ifdef MSG_CMSG_CLOEXEC 
4231         if (result < 0 && get_socket_errno () == EINVAL)
4232           {
4233             /* We must be running on an old kernel.  Call without the flag. */
4234             msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4235             result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4236           }
4237 #endif
4238
4239         if (result < 0)
4240           {
4241             int errsv = get_socket_errno ();
4242
4243             if (errsv == EINTR)
4244               continue;
4245
4246             if (socket->priv->blocking &&
4247                 (errsv == EWOULDBLOCK ||
4248                  errsv == EAGAIN))
4249               continue;
4250
4251             g_set_error (error, G_IO_ERROR,
4252                          socket_io_error_from_errno (errsv),
4253                          _("Error receiving message: %s"), socket_strerror (errsv));
4254
4255             return -1;
4256           }
4257         break;
4258       }
4259
4260     /* decode address */
4261     if (address != NULL)
4262       {
4263         *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4264       }
4265
4266     /* decode control messages */
4267     {
4268       GPtrArray *my_messages = NULL;
4269       struct cmsghdr *cmsg;
4270
4271       if (msg.msg_controllen >= sizeof (struct cmsghdr))
4272         {
4273           for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4274             {
4275               GSocketControlMessage *message;
4276
4277               message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4278                                                               cmsg->cmsg_type,
4279                                                               cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4280                                                               CMSG_DATA (cmsg));
4281               if (message == NULL)
4282                 /* We've already spewed about the problem in the
4283                    deserialization code, so just continue */
4284                 continue;
4285
4286               if (messages == NULL)
4287                 {
4288                   /* we have to do it this way if the user ignores the
4289                    * messages so that we will close any received fds.
4290                    */
4291                   g_object_unref (message);
4292                 }
4293               else
4294                 {
4295                   if (my_messages == NULL)
4296                     my_messages = g_ptr_array_new ();
4297                   g_ptr_array_add (my_messages, message);
4298                 }
4299             }
4300         }
4301
4302       if (num_messages)
4303         *num_messages = my_messages != NULL ? my_messages->len : 0;
4304
4305       if (messages)
4306         {
4307           if (my_messages == NULL)
4308             {
4309               *messages = NULL;
4310             }
4311           else
4312             {
4313               g_ptr_array_add (my_messages, NULL);
4314               *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4315             }
4316         }
4317       else
4318         {
4319           g_assert (my_messages == NULL);
4320         }
4321     }
4322
4323     /* capture the flags */
4324     if (flags != NULL)
4325       *flags = msg.msg_flags;
4326
4327     return result;
4328   }
4329 #else
4330   {
4331     struct sockaddr_storage addr;
4332     int addrlen;
4333     DWORD bytes_received;
4334     DWORD win_flags;
4335     int result;
4336     WSABUF *bufs;
4337     gint i;
4338
4339     /* iov */
4340     bufs = g_newa (WSABUF, num_vectors);
4341     for (i = 0; i < num_vectors; i++)
4342       {
4343         bufs[i].buf = (char *)vectors[i].buffer;
4344         bufs[i].len = (gulong)vectors[i].size;
4345       }
4346
4347     /* flags */
4348     if (flags != NULL)
4349       win_flags = *flags;
4350     else
4351       win_flags = 0;
4352
4353     /* do it */
4354     while (1)
4355       {
4356         if (socket->priv->blocking &&
4357             !g_socket_condition_wait (socket,
4358                                       G_IO_IN, cancellable, error))
4359           return -1;
4360
4361         addrlen = sizeof addr;
4362         if (address)
4363           result = WSARecvFrom (socket->priv->fd,
4364                                 bufs, num_vectors,
4365                                 &bytes_received, &win_flags,
4366                                 (struct sockaddr *)&addr, &addrlen,
4367                                 NULL, NULL);
4368         else
4369           result = WSARecv (socket->priv->fd,
4370                             bufs, num_vectors,
4371                             &bytes_received, &win_flags,
4372                             NULL, NULL);
4373         if (result != 0)
4374           {
4375             int errsv = get_socket_errno ();
4376
4377             if (errsv == WSAEINTR)
4378               continue;
4379
4380             win32_unset_event_mask (socket, FD_READ);
4381
4382             if (socket->priv->blocking &&
4383                 errsv == WSAEWOULDBLOCK)
4384               continue;
4385
4386             g_set_error (error, G_IO_ERROR,
4387                          socket_io_error_from_errno (errsv),
4388                          _("Error receiving message: %s"), socket_strerror (errsv));
4389
4390             return -1;
4391           }
4392         win32_unset_event_mask (socket, FD_READ);
4393         break;
4394       }
4395
4396     /* decode address */
4397     if (address != NULL)
4398       {
4399         *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4400       }
4401
4402     /* capture the flags */
4403     if (flags != NULL)
4404       *flags = win_flags;
4405
4406     if (messages != NULL)
4407       *messages = NULL;
4408     if (num_messages != NULL)
4409       *num_messages = 0;
4410
4411     return bytes_received;
4412   }
4413 #endif
4414 }
4415
4416 /**
4417  * g_socket_get_credentials:
4418  * @socket: a #GSocket.
4419  * @error: #GError for error reporting, or %NULL to ignore.
4420  *
4421  * Returns the credentials of the foreign process connected to this
4422  * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4423  * sockets).
4424  *
4425  * If this operation isn't supported on the OS, the method fails with
4426  * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4427  * by reading the %SO_PEERCRED option on the underlying socket.
4428  *
4429  * Other ways to obtain credentials from a foreign peer includes the
4430  * #GUnixCredentialsMessage type and
4431  * g_unix_connection_send_credentials() /
4432  * g_unix_connection_receive_credentials() functions.
4433  *
4434  * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4435  * that must be freed with g_object_unref().
4436  *
4437  * Since: 2.26
4438  */
4439 GCredentials *
4440 g_socket_get_credentials (GSocket   *socket,
4441                           GError   **error)
4442 {
4443   GCredentials *ret;
4444
4445   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4446   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4447
4448   ret = NULL;
4449
4450 #if defined(__linux__) || defined(__OpenBSD__)
4451   {
4452     socklen_t optlen;
4453 #if defined(__linux__)
4454     struct ucred native_creds;
4455     optlen = sizeof (struct ucred);
4456 #elif defined(__OpenBSD__)
4457     struct sockpeercred native_creds;
4458     optlen = sizeof (struct sockpeercred);
4459 #endif
4460     if (getsockopt (socket->priv->fd,
4461                     SOL_SOCKET,
4462                     SO_PEERCRED,
4463                     (void *)&native_creds,
4464                     &optlen) != 0)
4465       {
4466         int errsv = get_socket_errno ();
4467         g_set_error (error,
4468                      G_IO_ERROR,
4469                      socket_io_error_from_errno (errsv),
4470                      _("Unable to read socket credentials: %s"),
4471                      socket_strerror (errsv));
4472       }
4473     else
4474       {
4475         ret = g_credentials_new ();
4476         g_credentials_set_native (ret,
4477 #if defined(__linux__)
4478                                   G_CREDENTIALS_TYPE_LINUX_UCRED,
4479 #elif defined(__OpenBSD__)
4480                                   G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4481 #endif
4482                                   &native_creds);
4483       }
4484   }
4485 #else
4486   g_set_error_literal (error,
4487                        G_IO_ERROR,
4488                        G_IO_ERROR_NOT_SUPPORTED,
4489                        _("g_socket_get_credentials not implemented for this OS"));
4490 #endif
4491
4492   return ret;
4493 }
4494
4495 /**
4496  * g_socket_get_option:
4497  * @socket: a #GSocket
4498  * @level: the "API level" of the option (eg, <literal>SOL_SOCKET</literal>)
4499  * @optname: the "name" of the option (eg, <literal>SO_BROADCAST</literal>)
4500  * @value: (out): return location for the option value
4501  * @error: #GError for error reporting, or %NULL to ignore.
4502  *
4503  * Gets the value of an integer-valued option on @socket, as with
4504  * <literal>getsockopt ()</literal>. (If you need to fetch a
4505  * non-integer-valued option, you will need to call
4506  * <literal>getsockopt ()</literal> directly.)
4507  *
4508  * The <link linkend="gio-gnetworking.h"><literal>&lt;gio/gnetworking.h&gt;</literal></link>
4509  * header pulls in system headers that will define most of the
4510  * standard/portable socket options. For unusual socket protocols or
4511  * platform-dependent options, you may need to include additional
4512  * headers.
4513  *
4514  * Note that even for socket options that are a single byte in size,
4515  * @value is still a pointer to a #gint variable, not a #guchar;
4516  * g_socket_get_option() will handle the conversion internally.
4517  *
4518  * Returns: success or failure. On failure, @error will be set, and
4519  *   the system error value (<literal>errno</literal> or
4520  *   <literal>WSAGetLastError ()</literal>) will still be set to the
4521  *   result of the <literal>getsockopt ()</literal> call.
4522  *
4523  * Since: 2.36
4524  */
4525 gboolean
4526 g_socket_get_option (GSocket  *socket,
4527                      gint      level,
4528                      gint      optname,
4529                      gint     *value,
4530                      GError  **error)
4531 {
4532   guint size;
4533
4534   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4535
4536   *value = 0;
4537   size = sizeof (gint);
4538   if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
4539     {
4540       int errsv = get_socket_errno ();
4541
4542       g_set_error_literal (error,
4543                            G_IO_ERROR,
4544                            socket_io_error_from_errno (errsv),
4545                            socket_strerror (errsv));
4546 #ifndef G_OS_WIN32
4547       /* Reset errno in case the caller wants to look at it */
4548       errno = errsv;
4549 #endif
4550       return FALSE;
4551     }
4552
4553 #if G_BYTE_ORDER == G_BIG_ENDIAN
4554   /* If the returned value is smaller than an int then we need to
4555    * slide it over into the low-order bytes of *value.
4556    */
4557   if (size != sizeof (gint))
4558     *value = *value >> (8 * (sizeof (gint) - size));
4559 #endif
4560
4561   return TRUE;
4562 }
4563
4564 /**
4565  * g_socket_set_option:
4566  * @socket: a #GSocket
4567  * @level: the "API level" of the option (eg, <literal>SOL_SOCKET</literal>)
4568  * @optname: the "name" of the option (eg, <literal>SO_BROADCAST</literal>)
4569  * @value: the value to set the option to
4570  * @error: #GError for error reporting, or %NULL to ignore.
4571  *
4572  * Sets the value of an integer-valued option on @socket, as with
4573  * <literal>setsockopt ()</literal>. (If you need to set a
4574  * non-integer-valued option, you will need to call
4575  * <literal>setsockopt ()</literal> directly.)
4576  *
4577  * The <link linkend="gio-gnetworking.h"><literal>&lt;gio/gnetworking.h&gt;</literal></link>
4578  * header pulls in system headers that will define most of the
4579  * standard/portable socket options. For unusual socket protocols or
4580  * platform-dependent options, you may need to include additional
4581  * headers.
4582  *
4583  * Returns: success or failure. On failure, @error will be set, and
4584  *   the system error value (<literal>errno</literal> or
4585  *   <literal>WSAGetLastError ()</literal>) will still be set to the
4586  *   result of the <literal>setsockopt ()</literal> call.
4587  *
4588  * Since: 2.36
4589  */
4590 gboolean
4591 g_socket_set_option (GSocket  *socket,
4592                      gint      level,
4593                      gint      optname,
4594                      gint      value,
4595                      GError  **error)
4596 {
4597   gint errsv;
4598
4599   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4600
4601   if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
4602     return TRUE;
4603
4604 #if !defined (__linux__) && !defined (G_OS_WIN32)
4605   /* Linux and Windows let you set a single-byte value from an int,
4606    * but most other platforms don't.
4607    */
4608   if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
4609     {
4610 #if G_BYTE_ORDER == G_BIG_ENDIAN
4611       value = value << (8 * (sizeof (gint) - 1));
4612 #endif
4613       if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
4614         return TRUE;
4615     }
4616 #endif
4617
4618   errsv = get_socket_errno ();
4619
4620   g_set_error_literal (error,
4621                        G_IO_ERROR,
4622                        socket_io_error_from_errno (errsv),
4623                        socket_strerror (errsv));
4624 #ifndef G_OS_WIN32
4625   errno = errsv;
4626 #endif
4627   return FALSE;
4628 }
4629