Imported Upstream version 2.66.6
[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  * Copyright © 2015 Collabora, Ltd.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General
19  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20  *
21  * Authors: Christian Kellner <gicmo@gnome.org>
22  *          Samuel Cormier-Iijima <sciyoshi@gmail.com>
23  *          Ryan Lortie <desrt@desrt.ca>
24  *          Alexander Larsson <alexl@redhat.com>
25  *          Philip Withnall <philip.withnall@collabora.co.uk>
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_SIOCGIFADDR
48 #include <net/if.h>
49 #endif
50
51 #ifdef HAVE_SYS_FILIO_H
52 # include <sys/filio.h>
53 #endif
54
55 #ifdef G_OS_UNIX
56 #include <sys/uio.h>
57 #endif
58
59 #define GOBJECT_COMPILATION
60 #include "gobject/gtype-private.h" /* For _PRELUDE type define */
61 #undef GOBJECT_COMPILATION
62 #include "gcancellable.h"
63 #include "gdatagrambased.h"
64 #include "gioenumtypes.h"
65 #include "ginetaddress.h"
66 #include "ginetsocketaddress.h"
67 #include "ginitable.h"
68 #include "gioerror.h"
69 #include "gioenums.h"
70 #include "gioerror.h"
71 #include "gnetworkingprivate.h"
72 #include "gsocketaddress.h"
73 #include "gsocketcontrolmessage.h"
74 #include "gcredentials.h"
75 #include "gcredentialsprivate.h"
76 #include "glibintl.h"
77 #include "gioprivate.h"
78 #include "gstrfuncsprivate.h"
79
80 /**
81  * SECTION:gsocket
82  * @short_description: Low-level socket object
83  * @include: gio/gio.h
84  * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
85  *
86  * A #GSocket is a low-level networking primitive. It is a more or less
87  * direct mapping of the BSD socket API in a portable GObject based API.
88  * It supports both the UNIX socket implementations and winsock2 on Windows.
89  *
90  * #GSocket is the platform independent base upon which the higher level
91  * network primitives are based. Applications are not typically meant to
92  * use it directly, but rather through classes like #GSocketClient,
93  * #GSocketService and #GSocketConnection. However there may be cases where
94  * direct use of #GSocket is useful.
95  *
96  * #GSocket implements the #GInitable interface, so if it is manually constructed
97  * by e.g. g_object_new() you must call g_initable_init() and check the
98  * results before using the object. This is done automatically in
99  * g_socket_new() and g_socket_new_from_fd(), so these functions can return
100  * %NULL.
101  *
102  * Sockets operate in two general modes, blocking or non-blocking. When
103  * in blocking mode all operations (which don’t take an explicit blocking
104  * parameter) block until the requested operation
105  * is finished or there is an error. In non-blocking mode all calls that
106  * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
107  * To know when a call would successfully run you can call g_socket_condition_check(),
108  * or g_socket_condition_wait(). You can also use g_socket_create_source() and
109  * attach it to a #GMainContext to get callbacks when I/O is possible.
110  * Note that all sockets are always set to non blocking mode in the system, and
111  * blocking mode is emulated in GSocket.
112  *
113  * When working in non-blocking mode applications should always be able to
114  * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
115  * function said that I/O was possible. This can easily happen in case
116  * of a race condition in the application, but it can also happen for other
117  * reasons. For instance, on Windows a socket is always seen as writable
118  * until a write returns %G_IO_ERROR_WOULD_BLOCK.
119  *
120  * #GSockets can be either connection oriented or datagram based.
121  * For connection oriented types you must first establish a connection by
122  * either connecting to an address or accepting a connection from another
123  * address. For connectionless socket types the target/source address is
124  * specified or received in each I/O operation.
125  *
126  * All socket file descriptors are set to be close-on-exec.
127  *
128  * Note that creating a #GSocket causes the signal %SIGPIPE to be
129  * ignored for the remainder of the program. If you are writing a
130  * command-line utility that uses #GSocket, you may need to take into
131  * account the fact that your program will not automatically be killed
132  * if it tries to write to %stdout after it has been closed.
133  *
134  * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
135  * a #GSocket concurrently from multiple threads, you must implement your own
136  * locking.
137  *
138  * Since: 2.22
139  */
140
141 static void     g_socket_initable_iface_init (GInitableIface  *iface);
142 static gboolean g_socket_initable_init       (GInitable       *initable,
143                                               GCancellable    *cancellable,
144                                               GError         **error);
145
146 static void     g_socket_datagram_based_iface_init       (GDatagramBasedInterface *iface);
147 static gint     g_socket_datagram_based_receive_messages (GDatagramBased  *self,
148                                                           GInputMessage   *messages,
149                                                           guint            num_messages,
150                                                           gint             flags,
151                                                           gint64           timeout_us,
152                                                           GCancellable    *cancellable,
153                                                           GError         **error);
154 static gint     g_socket_datagram_based_send_messages    (GDatagramBased  *self,
155                                                           GOutputMessage  *messages,
156                                                           guint            num_messages,
157                                                           gint             flags,
158                                                           gint64           timeout_us,
159                                                           GCancellable    *cancellable,
160                                                           GError         **error);
161 static GSource *g_socket_datagram_based_create_source    (GDatagramBased           *self,
162                                                           GIOCondition              condition,
163                                                           GCancellable             *cancellable);
164 static GIOCondition g_socket_datagram_based_condition_check      (GDatagramBased   *datagram_based,
165                                                                   GIOCondition      condition);
166 static gboolean     g_socket_datagram_based_condition_wait       (GDatagramBased   *datagram_based,
167                                                                   GIOCondition      condition,
168                                                                   gint64            timeout_us,
169                                                                   GCancellable     *cancellable,
170                                                                   GError          **error);
171
172 static GSocketAddress *
173 cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len);
174
175 static gssize
176 g_socket_receive_message_with_timeout  (GSocket                 *socket,
177                                         GSocketAddress         **address,
178                                         GInputVector            *vectors,
179                                         gint                     num_vectors,
180                                         GSocketControlMessage ***messages,
181                                         gint                    *num_messages,
182                                         gint                    *flags,
183                                         gint64                   timeout_us,
184                                         GCancellable            *cancellable,
185                                         GError                 **error);
186 static gint
187 g_socket_receive_messages_with_timeout (GSocket        *socket,
188                                         GInputMessage  *messages,
189                                         guint           num_messages,
190                                         gint            flags,
191                                         gint64          timeout_us,
192                                         GCancellable   *cancellable,
193                                         GError        **error);
194 static gint
195 g_socket_send_messages_with_timeout    (GSocket        *socket,
196                                         GOutputMessage *messages,
197                                         guint           num_messages,
198                                         gint            flags,
199                                         gint64          timeout_us,
200                                         GCancellable   *cancellable,
201                                         GError        **error);
202
203 enum
204 {
205   PROP_0,
206   PROP_FAMILY,
207   PROP_TYPE,
208   PROP_PROTOCOL,
209   PROP_FD,
210   PROP_BLOCKING,
211   PROP_LISTEN_BACKLOG,
212   PROP_KEEPALIVE,
213   PROP_LOCAL_ADDRESS,
214   PROP_REMOTE_ADDRESS,
215   PROP_TIMEOUT,
216   PROP_TTL,
217   PROP_BROADCAST,
218   PROP_MULTICAST_LOOPBACK,
219   PROP_MULTICAST_TTL
220 };
221
222 /* Size of the receiver cache for g_socket_receive_from() */
223 #define RECV_ADDR_CACHE_SIZE 8
224
225 struct _GSocketPrivate
226 {
227   GSocketFamily   family;
228   GSocketType     type;
229   GSocketProtocol protocol;
230   gint            fd;
231   gint            listen_backlog;
232   guint           timeout;
233   GError         *construct_error;
234   GSocketAddress *remote_address;
235   guint           inited : 1;
236   guint           blocking : 1;
237   guint           keepalive : 1;
238   guint           closed : 1;
239   guint           connected_read : 1;
240   guint           connected_write : 1;
241   guint           listening : 1;
242   guint           timed_out : 1;
243   guint           connect_pending : 1;
244 #ifdef G_OS_WIN32
245   WSAEVENT        event;
246   gboolean        waiting;
247   DWORD           waiting_result;
248   int             current_events;
249   int             current_errors;
250   int             selected_events;
251   GList          *requested_conditions; /* list of requested GIOCondition * */
252   GMutex          win32_source_lock;
253   GCond           win32_source_cond;
254 #endif
255
256   struct {
257     GSocketAddress *addr;
258     struct sockaddr *native;
259     gsize native_len;
260     guint64 last_used;
261   } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
262 };
263
264 _G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket, g_socket, G_TYPE_OBJECT, 0,
265                                       /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
266                                       g_type_ensure (G_TYPE_SOCKET_FAMILY);
267                                       g_type_ensure (G_TYPE_SOCKET_TYPE);
268                                       g_type_ensure (G_TYPE_SOCKET_PROTOCOL);
269                                       g_type_ensure (G_TYPE_SOCKET_ADDRESS);
270                                       /* And networking init is appropriate for the prelude */
271                                       g_networking_init ();
272                                       , /* And now the regular type init code */
273                                       G_ADD_PRIVATE (GSocket)
274                                       G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
275                                                              g_socket_initable_iface_init);
276                                       G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
277                                                              g_socket_datagram_based_iface_init));
278
279 static int
280 get_socket_errno (void)
281 {
282 #ifndef G_OS_WIN32
283   return errno;
284 #else
285   return WSAGetLastError ();
286 #endif
287 }
288
289 static GIOErrorEnum
290 socket_io_error_from_errno (int err)
291 {
292 #ifdef G_OS_WIN32
293   return g_io_error_from_win32_error (err);
294 #else
295   return g_io_error_from_errno (err);
296 #endif
297 }
298
299 static const char *
300 socket_strerror (int err)
301 {
302 #ifndef G_OS_WIN32
303   return g_strerror (err);
304 #else
305   const char *msg_ret;
306   char *msg;
307
308   msg = g_win32_error_message (err);
309
310   msg_ret = g_intern_string (msg);
311   g_free (msg);
312
313   return msg_ret;
314 #endif
315 }
316
317 /* Wrapper around g_set_error() to avoid doing excess work */
318 #define socket_set_error_lazy(err, errsv, fmt)                          \
319   G_STMT_START {                                                        \
320     GError **__err = (err);                                             \
321     int __errsv = (errsv);                                              \
322                                                                         \
323     if (__err)                                                          \
324       {                                                                 \
325         int __code = socket_io_error_from_errno (__errsv);              \
326         const char *__strerr = socket_strerror (__errsv);               \
327                                                                         \
328         if (__code == G_IO_ERROR_WOULD_BLOCK)                           \
329           g_set_error_literal (__err, G_IO_ERROR, __code, __strerr);    \
330         else                                                            \
331           g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr);       \
332       }                                                                 \
333   } G_STMT_END
334
335 #ifdef G_OS_WIN32
336 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
337 static void
338 _win32_unset_event_mask (GSocket *socket, int mask)
339 {
340   g_mutex_lock (&socket->priv->win32_source_lock);
341   socket->priv->current_events &= ~mask;
342   socket->priv->current_errors &= ~mask;
343   g_mutex_unlock (&socket->priv->win32_source_lock);
344 }
345 #else
346 #define win32_unset_event_mask(_socket, _mask)
347 #endif
348
349 /* Windows has broken prototypes... */
350 #ifdef G_OS_WIN32
351 #define getsockopt(sockfd, level, optname, optval, optlen) \
352   getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
353 #define setsockopt(sockfd, level, optname, optval, optlen) \
354   setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
355 #define getsockname(sockfd, addr, addrlen) \
356   getsockname (sockfd, addr, (int *)addrlen)
357 #define getpeername(sockfd, addr, addrlen) \
358   getpeername (sockfd, addr, (int *)addrlen)
359 #define recv(sockfd, buf, len, flags) \
360   recv (sockfd, (gpointer)buf, len, flags)
361 #endif
362
363 static gchar *
364 address_to_string (GSocketAddress *address)
365 {
366   GString *ret = g_string_new ("");
367
368   if (G_IS_INET_SOCKET_ADDRESS (address))
369     {
370       GInetSocketAddress *isa = G_INET_SOCKET_ADDRESS (address);
371       GInetAddress *ia = g_inet_socket_address_get_address (isa);
372       GSocketFamily family = g_inet_address_get_family (ia);
373       gchar *tmp;
374
375       /* Represent IPv6 addresses in URL style:
376        * ::1 port 12345 -> [::1]:12345 */
377       if (family == G_SOCKET_FAMILY_IPV6)
378         g_string_append_c (ret, '[');
379
380       tmp = g_inet_address_to_string (ia);
381       g_string_append (ret, tmp);
382       g_free (tmp);
383
384       if (family == G_SOCKET_FAMILY_IPV6)
385         {
386           guint32 scope = g_inet_socket_address_get_scope_id (isa);
387
388           if (scope != 0)
389             g_string_append_printf (ret, "%%%u", scope);
390
391           g_string_append_c (ret, ']');
392         }
393
394       g_string_append_c (ret, ':');
395
396       g_string_append_printf (ret, "%u", g_inet_socket_address_get_port (isa));
397     }
398   else
399     {
400       /* For unknown address types, just show the type */
401       g_string_append_printf (ret, "(%s)", G_OBJECT_TYPE_NAME (address));
402     }
403
404   return g_string_free (ret, FALSE);
405 }
406
407 static gboolean
408 check_socket (GSocket *socket,
409               GError **error)
410 {
411   if (!socket->priv->inited)
412     {
413       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
414                            _("Invalid socket, not initialized"));
415       return FALSE;
416     }
417
418   if (socket->priv->construct_error)
419     {
420       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
421                    _("Invalid socket, initialization failed due to: %s"),
422                    socket->priv->construct_error->message);
423       return FALSE;
424     }
425
426   if (socket->priv->closed)
427     {
428       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
429                            _("Socket is already closed"));
430       return FALSE;
431     }
432
433   return TRUE;
434 }
435
436 static gboolean
437 check_timeout (GSocket *socket,
438                GError **error)
439 {
440   if (socket->priv->timed_out)
441     {
442       socket->priv->timed_out = FALSE;
443       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
444                            _("Socket I/O timed out"));
445       return FALSE;
446     }
447
448   return TRUE;
449 }
450
451 static void
452 g_socket_details_from_fd (GSocket *socket)
453 {
454   union {
455     struct sockaddr_storage storage;
456     struct sockaddr sa;
457   } address;
458   gint fd;
459   guint addrlen;
460   int value, family;
461   int errsv;
462
463   fd = socket->priv->fd;
464   if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
465     {
466       errsv = get_socket_errno ();
467       goto err;
468     }
469
470   switch (value)
471     {
472      case SOCK_STREAM:
473       socket->priv->type = G_SOCKET_TYPE_STREAM;
474       break;
475
476      case SOCK_DGRAM:
477       socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
478       break;
479
480      case SOCK_SEQPACKET:
481       socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
482       break;
483
484      default:
485       socket->priv->type = G_SOCKET_TYPE_INVALID;
486       break;
487     }
488
489   addrlen = sizeof address;
490   if (getsockname (fd, &address.sa, &addrlen) != 0)
491     {
492       errsv = get_socket_errno ();
493       goto err;
494     }
495
496   if (addrlen > 0)
497     {
498       g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
499                 sizeof address.storage.ss_family <= addrlen);
500       family = address.storage.ss_family;
501     }
502   else
503     {
504       /* On Solaris, this happens if the socket is not yet connected.
505        * But we can use SO_DOMAIN as a workaround there.
506        */
507 #ifdef SO_DOMAIN
508       if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
509         {
510           errsv = get_socket_errno ();
511           goto err;
512         }
513 #else
514       /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
515       errsv = -1;
516       goto err;
517 #endif
518     }
519
520   switch (family)
521     {
522      case G_SOCKET_FAMILY_IPV4:
523      case G_SOCKET_FAMILY_IPV6:
524        socket->priv->family = address.storage.ss_family;
525        switch (socket->priv->type)
526          {
527          case G_SOCKET_TYPE_STREAM:
528            socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
529            break;
530
531          case G_SOCKET_TYPE_DATAGRAM:
532            socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
533            break;
534
535          case G_SOCKET_TYPE_SEQPACKET:
536            socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
537            break;
538
539          default:
540            break;
541          }
542        break;
543
544      case G_SOCKET_FAMILY_UNIX:
545        socket->priv->family = G_SOCKET_FAMILY_UNIX;
546        socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
547        break;
548
549      default:
550        socket->priv->family = G_SOCKET_FAMILY_INVALID;
551        break;
552     }
553
554   if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
555     {
556       addrlen = sizeof address;
557       if (getpeername (fd, &address.sa, &addrlen) >= 0)
558         {
559           socket->priv->connected_read = TRUE;
560           socket->priv->connected_write = TRUE;
561         }
562     }
563
564   if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
565     {
566       socket->priv->keepalive = !!value;
567     }
568   else
569     {
570       /* Can't read, maybe not supported, assume FALSE */
571       socket->priv->keepalive = FALSE;
572     }
573
574   return;
575
576  err:
577   g_set_error (&socket->priv->construct_error, G_IO_ERROR,
578                socket_io_error_from_errno (errsv),
579                _("creating GSocket from fd: %s"),
580                socket_strerror (errsv));
581 }
582
583 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
584 gint
585 g_socket (gint     domain,
586           gint     type,
587           gint     protocol,
588           GError **error)
589 {
590   int fd, errsv;
591
592 #ifdef SOCK_CLOEXEC
593   fd = socket (domain, type | SOCK_CLOEXEC, protocol);
594   errsv = errno;
595   if (fd != -1)
596     return fd;
597
598   /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
599   if (fd < 0 && (errsv == EINVAL || errsv == EPROTOTYPE))
600 #endif
601     fd = socket (domain, type, protocol);
602
603   if (fd < 0)
604     {
605       errsv = get_socket_errno ();
606
607       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
608                    _("Unable to create socket: %s"), socket_strerror (errsv));
609       errno = errsv;
610       return -1;
611     }
612
613 #ifndef G_OS_WIN32
614   {
615     int flags;
616
617     /* We always want to set close-on-exec to protect users. If you
618        need to so some weird inheritance to exec you can re-enable this
619        using lower level hacks with g_socket_get_fd(). */
620     flags = fcntl (fd, F_GETFD, 0);
621     if (flags != -1 &&
622         (flags & FD_CLOEXEC) == 0)
623       {
624         flags |= FD_CLOEXEC;
625         fcntl (fd, F_SETFD, flags);
626       }
627   }
628 #endif
629
630   return fd;
631 }
632
633 static gint
634 g_socket_create_socket (GSocketFamily   family,
635                         GSocketType     type,
636                         int             protocol,
637                         GError        **error)
638 {
639   gint native_type;
640
641   switch (type)
642     {
643      case G_SOCKET_TYPE_STREAM:
644       native_type = SOCK_STREAM;
645       break;
646
647      case G_SOCKET_TYPE_DATAGRAM:
648       native_type = SOCK_DGRAM;
649       break;
650
651      case G_SOCKET_TYPE_SEQPACKET:
652       native_type = SOCK_SEQPACKET;
653       break;
654
655      default:
656       g_assert_not_reached ();
657     }
658
659   if (family <= 0)
660     {
661       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
662                    _("Unable to create socket: %s"), _("Unknown family was specified"));
663       return -1;
664     }
665
666   if (protocol == -1)
667     {
668       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
669                    _("Unable to create socket: %s"), _("Unknown protocol was specified"));
670       return -1;
671     }
672
673   return g_socket (family, native_type, protocol, error);
674 }
675
676 static void
677 g_socket_constructed (GObject *object)
678 {
679   GSocket *socket = G_SOCKET (object);
680
681   if (socket->priv->fd >= 0)
682     /* create socket->priv info from the fd */
683     g_socket_details_from_fd (socket);
684
685   else
686     /* create the fd from socket->priv info */
687     socket->priv->fd = g_socket_create_socket (socket->priv->family,
688                                                socket->priv->type,
689                                                socket->priv->protocol,
690                                                &socket->priv->construct_error);
691
692   if (socket->priv->fd != -1)
693     {
694 #ifndef G_OS_WIN32
695       GError *error = NULL;
696 #else
697       gulong arg;
698 #endif
699
700       /* Always use native nonblocking sockets, as Windows sets sockets to
701        * nonblocking automatically in certain operations. This way we make
702        * things work the same on all platforms.
703        */
704 #ifndef G_OS_WIN32
705       if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
706         {
707           g_warning ("Error setting socket nonblocking: %s", error->message);
708           g_clear_error (&error);
709         }
710 #else
711       arg = TRUE;
712
713       if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
714         {
715           int errsv = get_socket_errno ();
716           g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
717         }
718 #endif
719
720 #ifdef SO_NOSIGPIPE
721       /* See note about SIGPIPE below. */
722       g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
723 #endif
724     }
725 }
726
727 static void
728 g_socket_get_property (GObject    *object,
729                        guint       prop_id,
730                        GValue     *value,
731                        GParamSpec *pspec)
732 {
733   GSocket *socket = G_SOCKET (object);
734   GSocketAddress *address;
735
736   switch (prop_id)
737     {
738       case PROP_FAMILY:
739         g_value_set_enum (value, socket->priv->family);
740         break;
741
742       case PROP_TYPE:
743         g_value_set_enum (value, socket->priv->type);
744         break;
745
746       case PROP_PROTOCOL:
747         g_value_set_enum (value, socket->priv->protocol);
748         break;
749
750       case PROP_FD:
751         g_value_set_int (value, socket->priv->fd);
752         break;
753
754       case PROP_BLOCKING:
755         g_value_set_boolean (value, socket->priv->blocking);
756         break;
757
758       case PROP_LISTEN_BACKLOG:
759         g_value_set_int (value, socket->priv->listen_backlog);
760         break;
761
762       case PROP_KEEPALIVE:
763         g_value_set_boolean (value, socket->priv->keepalive);
764         break;
765
766       case PROP_LOCAL_ADDRESS:
767         address = g_socket_get_local_address (socket, NULL);
768         g_value_take_object (value, address);
769         break;
770
771       case PROP_REMOTE_ADDRESS:
772         address = g_socket_get_remote_address (socket, NULL);
773         g_value_take_object (value, address);
774         break;
775
776       case PROP_TIMEOUT:
777         g_value_set_uint (value, socket->priv->timeout);
778         break;
779
780       case PROP_TTL:
781         g_value_set_uint (value, g_socket_get_ttl (socket));
782         break;
783
784       case PROP_BROADCAST:
785         g_value_set_boolean (value, g_socket_get_broadcast (socket));
786         break;
787
788       case PROP_MULTICAST_LOOPBACK:
789         g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
790         break;
791
792       case PROP_MULTICAST_TTL:
793         g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
794         break;
795
796       default:
797         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
798     }
799 }
800
801 static void
802 g_socket_set_property (GObject      *object,
803                        guint         prop_id,
804                        const GValue *value,
805                        GParamSpec   *pspec)
806 {
807   GSocket *socket = G_SOCKET (object);
808
809   switch (prop_id)
810     {
811       case PROP_FAMILY:
812         socket->priv->family = g_value_get_enum (value);
813         break;
814
815       case PROP_TYPE:
816         socket->priv->type = g_value_get_enum (value);
817         break;
818
819       case PROP_PROTOCOL:
820         socket->priv->protocol = g_value_get_enum (value);
821         break;
822
823       case PROP_FD:
824         socket->priv->fd = g_value_get_int (value);
825         break;
826
827       case PROP_BLOCKING:
828         g_socket_set_blocking (socket, g_value_get_boolean (value));
829         break;
830
831       case PROP_LISTEN_BACKLOG:
832         g_socket_set_listen_backlog (socket, g_value_get_int (value));
833         break;
834
835       case PROP_KEEPALIVE:
836         g_socket_set_keepalive (socket, g_value_get_boolean (value));
837         break;
838
839       case PROP_TIMEOUT:
840         g_socket_set_timeout (socket, g_value_get_uint (value));
841         break;
842
843       case PROP_TTL:
844         g_socket_set_ttl (socket, g_value_get_uint (value));
845         break;
846
847       case PROP_BROADCAST:
848         g_socket_set_broadcast (socket, g_value_get_boolean (value));
849         break;
850
851       case PROP_MULTICAST_LOOPBACK:
852         g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
853         break;
854
855       case PROP_MULTICAST_TTL:
856         g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
857         break;
858
859       default:
860         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
861     }
862 }
863
864 static void
865 g_socket_finalize (GObject *object)
866 {
867   GSocket *socket = G_SOCKET (object);
868   gint i;
869
870   g_clear_error (&socket->priv->construct_error);
871
872   if (socket->priv->fd != -1 &&
873       !socket->priv->closed)
874     g_socket_close (socket, NULL);
875
876   if (socket->priv->remote_address)
877     g_object_unref (socket->priv->remote_address);
878
879 #ifdef G_OS_WIN32
880   if (socket->priv->event != WSA_INVALID_EVENT)
881     {
882       WSACloseEvent (socket->priv->event);
883       socket->priv->event = WSA_INVALID_EVENT;
884     }
885
886   g_assert (socket->priv->requested_conditions == NULL);
887   g_mutex_clear (&socket->priv->win32_source_lock);
888   g_cond_clear (&socket->priv->win32_source_cond);
889 #endif
890
891   for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
892     {
893       if (socket->priv->recv_addr_cache[i].addr)
894         {
895           g_object_unref (socket->priv->recv_addr_cache[i].addr);
896           g_free (socket->priv->recv_addr_cache[i].native);
897         }
898     }
899
900   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
901     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
902 }
903
904 static void
905 g_socket_class_init (GSocketClass *klass)
906 {
907   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
908
909 #ifdef SIGPIPE
910   /* There is no portable, thread-safe way to avoid having the process
911    * be killed by SIGPIPE when calling send() or sendmsg(), so we are
912    * forced to simply ignore the signal process-wide.
913    *
914    * Even if we ignore it though, gdb will still stop if the app
915    * receives a SIGPIPE, which can be confusing and annoying. So when
916    * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
917    * prevent the signal from occurring at all.
918    */
919   signal (SIGPIPE, SIG_IGN);
920 #endif
921
922   gobject_class->finalize = g_socket_finalize;
923   gobject_class->constructed = g_socket_constructed;
924   gobject_class->set_property = g_socket_set_property;
925   gobject_class->get_property = g_socket_get_property;
926
927   g_object_class_install_property (gobject_class, PROP_FAMILY,
928                                    g_param_spec_enum ("family",
929                                                       P_("Socket family"),
930                                                       P_("The sockets address family"),
931                                                       G_TYPE_SOCKET_FAMILY,
932                                                       G_SOCKET_FAMILY_INVALID,
933                                                       G_PARAM_CONSTRUCT_ONLY |
934                                                       G_PARAM_READWRITE |
935                                                       G_PARAM_STATIC_STRINGS));
936
937   g_object_class_install_property (gobject_class, PROP_TYPE,
938                                    g_param_spec_enum ("type",
939                                                       P_("Socket type"),
940                                                       P_("The sockets type"),
941                                                       G_TYPE_SOCKET_TYPE,
942                                                       G_SOCKET_TYPE_STREAM,
943                                                       G_PARAM_CONSTRUCT_ONLY |
944                                                       G_PARAM_READWRITE |
945                                                       G_PARAM_STATIC_STRINGS));
946
947   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
948                                    g_param_spec_enum ("protocol",
949                                                       P_("Socket protocol"),
950                                                       P_("The id of the protocol to use, or -1 for unknown"),
951                                                       G_TYPE_SOCKET_PROTOCOL,
952                                                       G_SOCKET_PROTOCOL_UNKNOWN,
953                                                       G_PARAM_CONSTRUCT_ONLY |
954                                                       G_PARAM_READWRITE |
955                                                       G_PARAM_STATIC_STRINGS));
956
957   g_object_class_install_property (gobject_class, PROP_FD,
958                                    g_param_spec_int ("fd",
959                                                      P_("File descriptor"),
960                                                      P_("The sockets file descriptor"),
961                                                      G_MININT,
962                                                      G_MAXINT,
963                                                      -1,
964                                                      G_PARAM_CONSTRUCT_ONLY |
965                                                      G_PARAM_READWRITE |
966                                                      G_PARAM_STATIC_STRINGS));
967
968   g_object_class_install_property (gobject_class, PROP_BLOCKING,
969                                    g_param_spec_boolean ("blocking",
970                                                          P_("blocking"),
971                                                          P_("Whether or not I/O on this socket is blocking"),
972                                                          TRUE,
973                                                          G_PARAM_READWRITE |
974                                                          G_PARAM_STATIC_STRINGS));
975
976   g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
977                                    g_param_spec_int ("listen-backlog",
978                                                      P_("Listen backlog"),
979                                                      P_("Outstanding connections in the listen queue"),
980                                                      0,
981                                                      SOMAXCONN,
982                                                      10,
983                                                      G_PARAM_READWRITE |
984                                                      G_PARAM_STATIC_STRINGS));
985
986   g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
987                                    g_param_spec_boolean ("keepalive",
988                                                          P_("Keep connection alive"),
989                                                          P_("Keep connection alive by sending periodic pings"),
990                                                          FALSE,
991                                                          G_PARAM_READWRITE |
992                                                          G_PARAM_STATIC_STRINGS));
993
994   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
995                                    g_param_spec_object ("local-address",
996                                                         P_("Local address"),
997                                                         P_("The local address the socket is bound to"),
998                                                         G_TYPE_SOCKET_ADDRESS,
999                                                         G_PARAM_READABLE |
1000                                                         G_PARAM_STATIC_STRINGS));
1001
1002   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
1003                                    g_param_spec_object ("remote-address",
1004                                                         P_("Remote address"),
1005                                                         P_("The remote address the socket is connected to"),
1006                                                         G_TYPE_SOCKET_ADDRESS,
1007                                                         G_PARAM_READABLE |
1008                                                         G_PARAM_STATIC_STRINGS));
1009
1010   /**
1011    * GSocket:timeout:
1012    *
1013    * The timeout in seconds on socket I/O
1014    *
1015    * Since: 2.26
1016    */
1017   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
1018                                    g_param_spec_uint ("timeout",
1019                                                       P_("Timeout"),
1020                                                       P_("The timeout in seconds on socket I/O"),
1021                                                       0,
1022                                                       G_MAXUINT,
1023                                                       0,
1024                                                       G_PARAM_READWRITE |
1025                                                       G_PARAM_STATIC_STRINGS));
1026
1027   /**
1028    * GSocket:broadcast:
1029    *
1030    * Whether the socket should allow sending to broadcast addresses.
1031    *
1032    * Since: 2.32
1033    */
1034   g_object_class_install_property (gobject_class, PROP_BROADCAST,
1035                                    g_param_spec_boolean ("broadcast",
1036                                                          P_("Broadcast"),
1037                                                          P_("Whether to allow sending to broadcast addresses"),
1038                                                          FALSE,
1039                                                          G_PARAM_READWRITE |
1040                                                          G_PARAM_STATIC_STRINGS));
1041
1042   /**
1043    * GSocket:ttl:
1044    *
1045    * Time-to-live for outgoing unicast packets
1046    *
1047    * Since: 2.32
1048    */
1049   g_object_class_install_property (gobject_class, PROP_TTL,
1050                                    g_param_spec_uint ("ttl",
1051                                                       P_("TTL"),
1052                                                       P_("Time-to-live of outgoing unicast packets"),
1053                                                       0, G_MAXUINT, 0,
1054                                                       G_PARAM_READWRITE |
1055                                                       G_PARAM_STATIC_STRINGS));
1056
1057   /**
1058    * GSocket:multicast-loopback:
1059    *
1060    * Whether outgoing multicast packets loop back to the local host.
1061    *
1062    * Since: 2.32
1063    */
1064   g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1065                                    g_param_spec_boolean ("multicast-loopback",
1066                                                          P_("Multicast loopback"),
1067                                                          P_("Whether outgoing multicast packets loop back to the local host"),
1068                                                          TRUE,
1069                                                          G_PARAM_READWRITE |
1070                                                          G_PARAM_STATIC_STRINGS));
1071
1072   /**
1073    * GSocket:multicast-ttl:
1074    *
1075    * Time-to-live out outgoing multicast packets
1076    *
1077    * Since: 2.32
1078    */
1079   g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1080                                    g_param_spec_uint ("multicast-ttl",
1081                                                       P_("Multicast TTL"),
1082                                                       P_("Time-to-live of outgoing multicast packets"),
1083                                                       0, G_MAXUINT, 1,
1084                                                       G_PARAM_READWRITE |
1085                                                       G_PARAM_STATIC_STRINGS));
1086 }
1087
1088 static void
1089 g_socket_initable_iface_init (GInitableIface *iface)
1090 {
1091   iface->init = g_socket_initable_init;
1092 }
1093
1094 static void
1095 g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1096 {
1097   iface->receive_messages = g_socket_datagram_based_receive_messages;
1098   iface->send_messages = g_socket_datagram_based_send_messages;
1099   iface->create_source = g_socket_datagram_based_create_source;
1100   iface->condition_check = g_socket_datagram_based_condition_check;
1101   iface->condition_wait = g_socket_datagram_based_condition_wait;
1102 }
1103
1104 static void
1105 g_socket_init (GSocket *socket)
1106 {
1107   socket->priv = g_socket_get_instance_private (socket);
1108
1109   socket->priv->fd = -1;
1110   socket->priv->blocking = TRUE;
1111   socket->priv->listen_backlog = 10;
1112   socket->priv->construct_error = NULL;
1113 #ifdef G_OS_WIN32
1114   socket->priv->event = WSA_INVALID_EVENT;
1115   g_mutex_init (&socket->priv->win32_source_lock);
1116   g_cond_init (&socket->priv->win32_source_cond);
1117 #endif
1118 }
1119
1120 static gboolean
1121 g_socket_initable_init (GInitable *initable,
1122                         GCancellable *cancellable,
1123                         GError  **error)
1124 {
1125   GSocket  *socket;
1126
1127   g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1128
1129   socket = G_SOCKET (initable);
1130
1131   if (cancellable != NULL)
1132     {
1133       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1134                            _("Cancellable initialization not supported"));
1135       return FALSE;
1136     }
1137
1138   socket->priv->inited = TRUE;
1139
1140   if (socket->priv->construct_error)
1141     {
1142       if (error)
1143         *error = g_error_copy (socket->priv->construct_error);
1144       return FALSE;
1145     }
1146
1147
1148   return TRUE;
1149 }
1150
1151 static gboolean
1152 check_datagram_based (GDatagramBased  *self,
1153                       GError         **error)
1154 {
1155   switch (g_socket_get_socket_type (G_SOCKET (self)))
1156     {
1157     case G_SOCKET_TYPE_INVALID:
1158     case G_SOCKET_TYPE_STREAM:
1159       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1160                    _("Cannot use datagram operations on a non-datagram "
1161                      "socket."));
1162       return FALSE;
1163     case G_SOCKET_TYPE_DATAGRAM:
1164     case G_SOCKET_TYPE_SEQPACKET:
1165       /* Fall through. */
1166       break;
1167     }
1168
1169   /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1170    * pretty tricky to split out #GSocket:timeout so that it does not affect
1171    * #GDatagramBased operations (but still affects #GSocket operations). It is
1172    * not worth that effort — just disallow it and require the user to specify
1173    * timeouts on a per-operation basis. */
1174   if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1175     {
1176       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1177                    _("Cannot use datagram operations on a socket with a "
1178                      "timeout set."));
1179       return FALSE;
1180     }
1181
1182   return TRUE;
1183 }
1184
1185 static gint
1186 g_socket_datagram_based_receive_messages (GDatagramBased  *self,
1187                                           GInputMessage   *messages,
1188                                           guint            num_messages,
1189                                           gint             flags,
1190                                           gint64           timeout_us,
1191                                           GCancellable    *cancellable,
1192                                           GError         **error)
1193 {
1194   if (!check_datagram_based (self, error))
1195     return FALSE;
1196
1197   return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1198                                                  num_messages, flags, timeout_us,
1199                                                  cancellable, error);
1200 }
1201
1202 static gint
1203 g_socket_datagram_based_send_messages (GDatagramBased  *self,
1204                                        GOutputMessage  *messages,
1205                                        guint            num_messages,
1206                                        gint             flags,
1207                                        gint64           timeout_us,
1208                                        GCancellable    *cancellable,
1209                                        GError         **error)
1210 {
1211   if (!check_datagram_based (self, error))
1212     return FALSE;
1213
1214   return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1215                                               num_messages, flags, timeout_us,
1216                                               cancellable, error);
1217 }
1218
1219 static GSource *
1220 g_socket_datagram_based_create_source (GDatagramBased  *self,
1221                                        GIOCondition     condition,
1222                                        GCancellable    *cancellable)
1223 {
1224   if (!check_datagram_based (self, NULL))
1225     return NULL;
1226
1227   return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1228 }
1229
1230 static GIOCondition
1231 g_socket_datagram_based_condition_check (GDatagramBased  *datagram_based,
1232                                          GIOCondition     condition)
1233 {
1234   if (!check_datagram_based (datagram_based, NULL))
1235     return G_IO_ERR;
1236
1237   return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1238 }
1239
1240 static gboolean
1241 g_socket_datagram_based_condition_wait (GDatagramBased  *datagram_based,
1242                                         GIOCondition     condition,
1243                                         gint64           timeout_us,
1244                                         GCancellable    *cancellable,
1245                                         GError         **error)
1246 {
1247   if (!check_datagram_based (datagram_based, error))
1248     return FALSE;
1249
1250   return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1251                                         timeout_us, cancellable, error);
1252 }
1253
1254 /**
1255  * g_socket_new:
1256  * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1257  * @type: the socket type to use.
1258  * @protocol: the id of the protocol to use, or 0 for default.
1259  * @error: #GError for error reporting, or %NULL to ignore.
1260  *
1261  * Creates a new #GSocket with the defined family, type and protocol.
1262  * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1263  * for the family and type is used.
1264  *
1265  * The @protocol is a family and type specific int that specifies what
1266  * kind of protocol to use. #GSocketProtocol lists several common ones.
1267  * Many families only support one protocol, and use 0 for this, others
1268  * support several and using 0 means to use the default protocol for
1269  * the family and type.
1270  *
1271  * The protocol id is passed directly to the operating
1272  * system, so you can use protocols not listed in #GSocketProtocol if you
1273  * know the protocol number used for it.
1274  *
1275  * Returns: a #GSocket or %NULL on error.
1276  *     Free the returned object with g_object_unref().
1277  *
1278  * Since: 2.22
1279  */
1280 GSocket *
1281 g_socket_new (GSocketFamily     family,
1282               GSocketType       type,
1283               GSocketProtocol   protocol,
1284               GError          **error)
1285 {
1286   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1287                                    NULL, error,
1288                                    "family", family,
1289                                    "type", type,
1290                                    "protocol", protocol,
1291                                    NULL));
1292 }
1293
1294 /**
1295  * g_socket_new_from_fd:
1296  * @fd: a native socket file descriptor.
1297  * @error: #GError for error reporting, or %NULL to ignore.
1298  *
1299  * Creates a new #GSocket from a native file descriptor
1300  * or winsock SOCKET handle.
1301  *
1302  * This reads all the settings from the file descriptor so that
1303  * all properties should work. Note that the file descriptor
1304  * will be set to non-blocking mode, independent on the blocking
1305  * mode of the #GSocket.
1306  *
1307  * On success, the returned #GSocket takes ownership of @fd. On failure, the
1308  * caller must close @fd themselves.
1309  *
1310  * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1311  * descriptor.  Instead, a GError will be set with code %G_IO_ERROR_FAILED
1312  *
1313  * Returns: a #GSocket or %NULL on error.
1314  *     Free the returned object with g_object_unref().
1315  *
1316  * Since: 2.22
1317  */
1318 GSocket *
1319 g_socket_new_from_fd (gint     fd,
1320                       GError **error)
1321 {
1322   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1323                                    NULL, error,
1324                                    "fd", fd,
1325                                    NULL));
1326 }
1327
1328 /**
1329  * g_socket_set_blocking:
1330  * @socket: a #GSocket.
1331  * @blocking: Whether to use blocking I/O or not.
1332  *
1333  * Sets the blocking mode of the socket. In blocking mode
1334  * all operations (which don’t take an explicit blocking parameter) block until
1335  * they succeed or there is an error. In
1336  * non-blocking mode all functions return results immediately or
1337  * with a %G_IO_ERROR_WOULD_BLOCK error.
1338  *
1339  * All sockets are created in blocking mode. However, note that the
1340  * platform level socket is always non-blocking, and blocking mode
1341  * is a GSocket level feature.
1342  *
1343  * Since: 2.22
1344  */
1345 void
1346 g_socket_set_blocking (GSocket  *socket,
1347                        gboolean  blocking)
1348 {
1349   g_return_if_fail (G_IS_SOCKET (socket));
1350
1351   blocking = !!blocking;
1352
1353   if (socket->priv->blocking == blocking)
1354     return;
1355
1356   socket->priv->blocking = blocking;
1357   g_object_notify (G_OBJECT (socket), "blocking");
1358 }
1359
1360 /**
1361  * g_socket_get_blocking:
1362  * @socket: a #GSocket.
1363  *
1364  * Gets the blocking mode of the socket. For details on blocking I/O,
1365  * see g_socket_set_blocking().
1366  *
1367  * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1368  *
1369  * Since: 2.22
1370  */
1371 gboolean
1372 g_socket_get_blocking (GSocket *socket)
1373 {
1374   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1375
1376   return socket->priv->blocking;
1377 }
1378
1379 /**
1380  * g_socket_set_keepalive:
1381  * @socket: a #GSocket.
1382  * @keepalive: Value for the keepalive flag
1383  *
1384  * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1385  * this flag is set on a socket, the system will attempt to verify that the
1386  * remote socket endpoint is still present if a sufficiently long period of
1387  * time passes with no data being exchanged. If the system is unable to
1388  * verify the presence of the remote endpoint, it will automatically close
1389  * the connection.
1390  *
1391  * This option is only functional on certain kinds of sockets. (Notably,
1392  * %G_SOCKET_PROTOCOL_TCP sockets.)
1393  *
1394  * The exact time between pings is system- and protocol-dependent, but will
1395  * normally be at least two hours. Most commonly, you would set this flag
1396  * on a server socket if you want to allow clients to remain idle for long
1397  * periods of time, but also want to ensure that connections are eventually
1398  * garbage-collected if clients crash or become unreachable.
1399  *
1400  * Since: 2.22
1401  */
1402 void
1403 g_socket_set_keepalive (GSocket  *socket,
1404                         gboolean  keepalive)
1405 {
1406   GError *error = NULL;
1407
1408   g_return_if_fail (G_IS_SOCKET (socket));
1409
1410   keepalive = !!keepalive;
1411   if (socket->priv->keepalive == keepalive)
1412     return;
1413
1414   if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1415                             keepalive, &error))
1416     {
1417       g_warning ("error setting keepalive: %s", error->message);
1418       g_error_free (error);
1419       return;
1420     }
1421
1422   socket->priv->keepalive = keepalive;
1423   g_object_notify (G_OBJECT (socket), "keepalive");
1424 }
1425
1426 /**
1427  * g_socket_get_keepalive:
1428  * @socket: a #GSocket.
1429  *
1430  * Gets the keepalive mode of the socket. For details on this,
1431  * see g_socket_set_keepalive().
1432  *
1433  * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1434  *
1435  * Since: 2.22
1436  */
1437 gboolean
1438 g_socket_get_keepalive (GSocket *socket)
1439 {
1440   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1441
1442   return socket->priv->keepalive;
1443 }
1444
1445 /**
1446  * g_socket_get_listen_backlog:
1447  * @socket: a #GSocket.
1448  *
1449  * Gets the listen backlog setting of the socket. For details on this,
1450  * see g_socket_set_listen_backlog().
1451  *
1452  * Returns: the maximum number of pending connections.
1453  *
1454  * Since: 2.22
1455  */
1456 gint
1457 g_socket_get_listen_backlog  (GSocket *socket)
1458 {
1459   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1460
1461   return socket->priv->listen_backlog;
1462 }
1463
1464 /**
1465  * g_socket_set_listen_backlog:
1466  * @socket: a #GSocket.
1467  * @backlog: the maximum number of pending connections.
1468  *
1469  * Sets the maximum number of outstanding connections allowed
1470  * when listening on this socket. If more clients than this are
1471  * connecting to the socket and the application is not handling them
1472  * on time then the new connections will be refused.
1473  *
1474  * Note that this must be called before g_socket_listen() and has no
1475  * effect if called after that.
1476  *
1477  * Since: 2.22
1478  */
1479 void
1480 g_socket_set_listen_backlog (GSocket *socket,
1481                              gint     backlog)
1482 {
1483   g_return_if_fail (G_IS_SOCKET (socket));
1484   g_return_if_fail (!socket->priv->listening);
1485
1486   if (backlog != socket->priv->listen_backlog)
1487     {
1488       socket->priv->listen_backlog = backlog;
1489       g_object_notify (G_OBJECT (socket), "listen-backlog");
1490     }
1491 }
1492
1493 /**
1494  * g_socket_get_timeout:
1495  * @socket: a #GSocket.
1496  *
1497  * Gets the timeout setting of the socket. For details on this, see
1498  * g_socket_set_timeout().
1499  *
1500  * Returns: the timeout in seconds
1501  *
1502  * Since: 2.26
1503  */
1504 guint
1505 g_socket_get_timeout (GSocket *socket)
1506 {
1507   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1508
1509   return socket->priv->timeout;
1510 }
1511
1512 /**
1513  * g_socket_set_timeout:
1514  * @socket: a #GSocket.
1515  * @timeout: the timeout for @socket, in seconds, or 0 for none
1516  *
1517  * Sets the time in seconds after which I/O operations on @socket will
1518  * time out if they have not yet completed.
1519  *
1520  * On a blocking socket, this means that any blocking #GSocket
1521  * operation will time out after @timeout seconds of inactivity,
1522  * returning %G_IO_ERROR_TIMED_OUT.
1523  *
1524  * On a non-blocking socket, calls to g_socket_condition_wait() will
1525  * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1526  * created with g_socket_create_source() will trigger after
1527  * @timeout seconds of inactivity, with the requested condition
1528  * set, at which point calling g_socket_receive(), g_socket_send(),
1529  * g_socket_check_connect_result(), etc, will fail with
1530  * %G_IO_ERROR_TIMED_OUT.
1531  *
1532  * If @timeout is 0 (the default), operations will never time out
1533  * on their own.
1534  *
1535  * Note that if an I/O operation is interrupted by a signal, this may
1536  * cause the timeout to be reset.
1537  *
1538  * Since: 2.26
1539  */
1540 void
1541 g_socket_set_timeout (GSocket *socket,
1542                       guint    timeout)
1543 {
1544   g_return_if_fail (G_IS_SOCKET (socket));
1545
1546   if (timeout != socket->priv->timeout)
1547     {
1548       socket->priv->timeout = timeout;
1549       g_object_notify (G_OBJECT (socket), "timeout");
1550     }
1551 }
1552
1553 /**
1554  * g_socket_get_ttl:
1555  * @socket: a #GSocket.
1556  *
1557  * Gets the unicast time-to-live setting on @socket; see
1558  * g_socket_set_ttl() for more details.
1559  *
1560  * Returns: the time-to-live setting on @socket
1561  *
1562  * Since: 2.32
1563  */
1564 guint
1565 g_socket_get_ttl (GSocket *socket)
1566 {
1567   GError *error = NULL;
1568   gint value;
1569
1570   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1571
1572   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1573     {
1574       g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1575                            &value, &error);
1576     }
1577   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1578     {
1579       g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1580                            &value, &error);
1581     }
1582   else
1583     g_return_val_if_reached (0);
1584
1585   if (error)
1586     {
1587       g_warning ("error getting unicast ttl: %s", error->message);
1588       g_error_free (error);
1589       return 0;
1590     }
1591
1592   return value;
1593 }
1594
1595 /**
1596  * g_socket_set_ttl:
1597  * @socket: a #GSocket.
1598  * @ttl: the time-to-live value for all unicast packets on @socket
1599  *
1600  * Sets the time-to-live for outgoing unicast packets on @socket.
1601  * By default the platform-specific default value is used.
1602  *
1603  * Since: 2.32
1604  */
1605 void
1606 g_socket_set_ttl (GSocket  *socket,
1607                   guint     ttl)
1608 {
1609   GError *error = NULL;
1610
1611   g_return_if_fail (G_IS_SOCKET (socket));
1612
1613   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1614     {
1615       g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1616                            ttl, &error);
1617     }
1618   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1619     {
1620       g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1621                            ttl, NULL);
1622       g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1623                            ttl, &error);
1624     }
1625   else
1626     g_return_if_reached ();
1627
1628   if (error)
1629     {
1630       g_warning ("error setting unicast ttl: %s", error->message);
1631       g_error_free (error);
1632       return;
1633     }
1634
1635   g_object_notify (G_OBJECT (socket), "ttl");
1636 }
1637
1638 /**
1639  * g_socket_get_broadcast:
1640  * @socket: a #GSocket.
1641  *
1642  * Gets the broadcast setting on @socket; if %TRUE,
1643  * it is possible to send packets to broadcast
1644  * addresses.
1645  *
1646  * Returns: the broadcast setting on @socket
1647  *
1648  * Since: 2.32
1649  */
1650 gboolean
1651 g_socket_get_broadcast (GSocket *socket)
1652 {
1653   GError *error = NULL;
1654   gint value;
1655
1656   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1657
1658   if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1659                             &value, &error))
1660     {
1661       g_warning ("error getting broadcast: %s", error->message);
1662       g_error_free (error);
1663       return FALSE;
1664     }
1665
1666   return !!value;
1667 }
1668
1669 /**
1670  * g_socket_set_broadcast:
1671  * @socket: a #GSocket.
1672  * @broadcast: whether @socket should allow sending to broadcast
1673  *     addresses
1674  *
1675  * Sets whether @socket should allow sending to broadcast addresses.
1676  * This is %FALSE by default.
1677  *
1678  * Since: 2.32
1679  */
1680 void
1681 g_socket_set_broadcast (GSocket    *socket,
1682                         gboolean    broadcast)
1683 {
1684   GError *error = NULL;
1685
1686   g_return_if_fail (G_IS_SOCKET (socket));
1687
1688   broadcast = !!broadcast;
1689
1690   if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1691                             broadcast, &error))
1692     {
1693       g_warning ("error setting broadcast: %s", error->message);
1694       g_error_free (error);
1695       return;
1696     }
1697
1698   g_object_notify (G_OBJECT (socket), "broadcast");
1699 }
1700
1701 /**
1702  * g_socket_get_multicast_loopback:
1703  * @socket: a #GSocket.
1704  *
1705  * Gets the multicast loopback setting on @socket; if %TRUE (the
1706  * default), outgoing multicast packets will be looped back to
1707  * multicast listeners on the same host.
1708  *
1709  * Returns: the multicast loopback setting on @socket
1710  *
1711  * Since: 2.32
1712  */
1713 gboolean
1714 g_socket_get_multicast_loopback (GSocket *socket)
1715 {
1716   GError *error = NULL;
1717   gint value;
1718
1719   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1720
1721   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1722     {
1723       g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1724                            &value, &error);
1725     }
1726   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1727     {
1728       g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1729                            &value, &error);
1730     }
1731   else
1732     g_return_val_if_reached (FALSE);
1733
1734   if (error)
1735     {
1736       g_warning ("error getting multicast loopback: %s", error->message);
1737       g_error_free (error);
1738       return FALSE;
1739     }
1740
1741   return !!value;
1742 }
1743
1744 /**
1745  * g_socket_set_multicast_loopback:
1746  * @socket: a #GSocket.
1747  * @loopback: whether @socket should receive messages sent to its
1748  *   multicast groups from the local host
1749  *
1750  * Sets whether outgoing multicast packets will be received by sockets
1751  * listening on that multicast address on the same host. This is %TRUE
1752  * by default.
1753  *
1754  * Since: 2.32
1755  */
1756 void
1757 g_socket_set_multicast_loopback (GSocket    *socket,
1758                                  gboolean    loopback)
1759 {
1760   GError *error = NULL;
1761
1762   g_return_if_fail (G_IS_SOCKET (socket));
1763
1764   loopback = !!loopback;
1765
1766   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1767     {
1768       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1769                            loopback, &error);
1770     }
1771   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1772     {
1773       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1774                            loopback, NULL);
1775       g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1776                            loopback, &error);
1777     }
1778   else
1779     g_return_if_reached ();
1780
1781   if (error)
1782     {
1783       g_warning ("error setting multicast loopback: %s", error->message);
1784       g_error_free (error);
1785       return;
1786     }
1787
1788   g_object_notify (G_OBJECT (socket), "multicast-loopback");
1789 }
1790
1791 /**
1792  * g_socket_get_multicast_ttl:
1793  * @socket: a #GSocket.
1794  *
1795  * Gets the multicast time-to-live setting on @socket; see
1796  * g_socket_set_multicast_ttl() for more details.
1797  *
1798  * Returns: the multicast time-to-live setting on @socket
1799  *
1800  * Since: 2.32
1801  */
1802 guint
1803 g_socket_get_multicast_ttl (GSocket *socket)
1804 {
1805   GError *error = NULL;
1806   gint value;
1807
1808   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1809
1810   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1811     {
1812       g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1813                            &value, &error);
1814     }
1815   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1816     {
1817       g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1818                            &value, &error);
1819     }
1820   else
1821     g_return_val_if_reached (FALSE);
1822
1823   if (error)
1824     {
1825       g_warning ("error getting multicast ttl: %s", error->message);
1826       g_error_free (error);
1827       return FALSE;
1828     }
1829
1830   return value;
1831 }
1832
1833 /**
1834  * g_socket_set_multicast_ttl:
1835  * @socket: a #GSocket.
1836  * @ttl: the time-to-live value for all multicast datagrams on @socket
1837  *
1838  * Sets the time-to-live for outgoing multicast datagrams on @socket.
1839  * By default, this is 1, meaning that multicast packets will not leave
1840  * the local network.
1841  *
1842  * Since: 2.32
1843  */
1844 void
1845 g_socket_set_multicast_ttl (GSocket  *socket,
1846                             guint     ttl)
1847 {
1848   GError *error = NULL;
1849
1850   g_return_if_fail (G_IS_SOCKET (socket));
1851
1852   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1853     {
1854       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1855                            ttl, &error);
1856     }
1857   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1858     {
1859       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1860                            ttl, NULL);
1861       g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1862                            ttl, &error);
1863     }
1864   else
1865     g_return_if_reached ();
1866
1867   if (error)
1868     {
1869       g_warning ("error setting multicast ttl: %s", error->message);
1870       g_error_free (error);
1871       return;
1872     }
1873
1874   g_object_notify (G_OBJECT (socket), "multicast-ttl");
1875 }
1876
1877 /**
1878  * g_socket_get_family:
1879  * @socket: a #GSocket.
1880  *
1881  * Gets the socket family of the socket.
1882  *
1883  * Returns: a #GSocketFamily
1884  *
1885  * Since: 2.22
1886  */
1887 GSocketFamily
1888 g_socket_get_family (GSocket *socket)
1889 {
1890   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1891
1892   return socket->priv->family;
1893 }
1894
1895 /**
1896  * g_socket_get_socket_type:
1897  * @socket: a #GSocket.
1898  *
1899  * Gets the socket type of the socket.
1900  *
1901  * Returns: a #GSocketType
1902  *
1903  * Since: 2.22
1904  */
1905 GSocketType
1906 g_socket_get_socket_type (GSocket *socket)
1907 {
1908   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1909
1910   return socket->priv->type;
1911 }
1912
1913 /**
1914  * g_socket_get_protocol:
1915  * @socket: a #GSocket.
1916  *
1917  * Gets the socket protocol id the socket was created with.
1918  * In case the protocol is unknown, -1 is returned.
1919  *
1920  * Returns: a protocol id, or -1 if unknown
1921  *
1922  * Since: 2.22
1923  */
1924 GSocketProtocol
1925 g_socket_get_protocol (GSocket *socket)
1926 {
1927   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1928
1929   return socket->priv->protocol;
1930 }
1931
1932 /**
1933  * g_socket_get_fd:
1934  * @socket: a #GSocket.
1935  *
1936  * Returns the underlying OS socket object. On unix this
1937  * is a socket file descriptor, and on Windows this is
1938  * a Winsock2 SOCKET handle. This may be useful for
1939  * doing platform specific or otherwise unusual operations
1940  * on the socket.
1941  *
1942  * Returns: the file descriptor of the socket.
1943  *
1944  * Since: 2.22
1945  */
1946 int
1947 g_socket_get_fd (GSocket *socket)
1948 {
1949   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1950
1951   return socket->priv->fd;
1952 }
1953
1954 /**
1955  * g_socket_get_local_address:
1956  * @socket: a #GSocket.
1957  * @error: #GError for error reporting, or %NULL to ignore.
1958  *
1959  * Try to get the local address of a bound socket. This is only
1960  * useful if the socket has been bound to a local address,
1961  * either explicitly or implicitly when connecting.
1962  *
1963  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1964  *     Free the returned object with g_object_unref().
1965  *
1966  * Since: 2.22
1967  */
1968 GSocketAddress *
1969 g_socket_get_local_address (GSocket  *socket,
1970                             GError  **error)
1971 {
1972   union {
1973     struct sockaddr_storage storage;
1974     struct sockaddr sa;
1975   } buffer;
1976   guint len = sizeof (buffer);
1977
1978   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1979
1980   if (getsockname (socket->priv->fd, &buffer.sa, &len) < 0)
1981     {
1982       int errsv = get_socket_errno ();
1983       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1984                    _("could not get local address: %s"), socket_strerror (errsv));
1985       return NULL;
1986     }
1987
1988   return g_socket_address_new_from_native (&buffer.storage, len);
1989 }
1990
1991 /**
1992  * g_socket_get_remote_address:
1993  * @socket: a #GSocket.
1994  * @error: #GError for error reporting, or %NULL to ignore.
1995  *
1996  * Try to get the remote address of a connected socket. This is only
1997  * useful for connection oriented sockets that have been connected.
1998  *
1999  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
2000  *     Free the returned object with g_object_unref().
2001  *
2002  * Since: 2.22
2003  */
2004 GSocketAddress *
2005 g_socket_get_remote_address (GSocket  *socket,
2006                              GError  **error)
2007 {
2008   union {
2009     struct sockaddr_storage storage;
2010     struct sockaddr sa;
2011   } buffer;
2012   guint len = sizeof (buffer);
2013
2014   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2015
2016   if (socket->priv->connect_pending)
2017     {
2018       if (!g_socket_check_connect_result (socket, error))
2019         return NULL;
2020       else
2021         socket->priv->connect_pending = FALSE;
2022     }
2023
2024   if (!socket->priv->remote_address)
2025     {
2026       if (getpeername (socket->priv->fd, &buffer.sa, &len) < 0)
2027         {
2028           int errsv = get_socket_errno ();
2029           g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2030                        _("could not get remote address: %s"), socket_strerror (errsv));
2031           return NULL;
2032         }
2033
2034       socket->priv->remote_address = g_socket_address_new_from_native (&buffer.storage, len);
2035     }
2036
2037   return g_object_ref (socket->priv->remote_address);
2038 }
2039
2040 /**
2041  * g_socket_is_connected:
2042  * @socket: a #GSocket.
2043  *
2044  * Check whether the socket is connected. This is only useful for
2045  * connection-oriented sockets.
2046  *
2047  * If using g_socket_shutdown(), this function will return %TRUE until the
2048  * socket has been shut down for reading and writing. If you do a non-blocking
2049  * connect, this function will not return %TRUE until after you call
2050  * g_socket_check_connect_result().
2051  *
2052  * Returns: %TRUE if socket is connected, %FALSE otherwise.
2053  *
2054  * Since: 2.22
2055  */
2056 gboolean
2057 g_socket_is_connected (GSocket *socket)
2058 {
2059   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2060
2061   return (socket->priv->connected_read || socket->priv->connected_write);
2062 }
2063
2064 /**
2065  * g_socket_listen:
2066  * @socket: a #GSocket.
2067  * @error: #GError for error reporting, or %NULL to ignore.
2068  *
2069  * Marks the socket as a server socket, i.e. a socket that is used
2070  * to accept incoming requests using g_socket_accept().
2071  *
2072  * Before calling this the socket must be bound to a local address using
2073  * g_socket_bind().
2074  *
2075  * To set the maximum amount of outstanding clients, use
2076  * g_socket_set_listen_backlog().
2077  *
2078  * Returns: %TRUE on success, %FALSE on error.
2079  *
2080  * Since: 2.22
2081  */
2082 gboolean
2083 g_socket_listen (GSocket  *socket,
2084                  GError  **error)
2085 {
2086   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2087
2088   if (!check_socket (socket, error))
2089     return FALSE;
2090
2091   if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2092     {
2093       int errsv = get_socket_errno ();
2094
2095       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2096                    _("could not listen: %s"), socket_strerror (errsv));
2097       return FALSE;
2098     }
2099
2100   socket->priv->listening = TRUE;
2101
2102   return TRUE;
2103 }
2104
2105 /**
2106  * g_socket_bind:
2107  * @socket: a #GSocket.
2108  * @address: a #GSocketAddress specifying the local address.
2109  * @allow_reuse: whether to allow reusing this address
2110  * @error: #GError for error reporting, or %NULL to ignore.
2111  *
2112  * When a socket is created it is attached to an address family, but it
2113  * doesn't have an address in this family. g_socket_bind() assigns the
2114  * address (sometimes called name) of the socket.
2115  *
2116  * It is generally required to bind to a local address before you can
2117  * receive connections. (See g_socket_listen() and g_socket_accept() ).
2118  * In certain situations, you may also want to bind a socket that will be
2119  * used to initiate connections, though this is not normally required.
2120  *
2121  * If @socket is a TCP socket, then @allow_reuse controls the setting
2122  * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2123  * server sockets (sockets that you will eventually call
2124  * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2125  * set this flag on a server socket may cause g_socket_bind() to return
2126  * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2127  * immediately restarted.)
2128  *
2129  * If @socket is a UDP socket, then @allow_reuse determines whether or
2130  * not other UDP sockets can be bound to the same address at the same
2131  * time. In particular, you can have several UDP sockets bound to the
2132  * same address, and they will all receive all of the multicast and
2133  * broadcast packets sent to that address. (The behavior of unicast
2134  * UDP packets to an address with multiple listeners is not defined.)
2135  *
2136  * Returns: %TRUE on success, %FALSE on error.
2137  *
2138  * Since: 2.22
2139  */
2140 gboolean
2141 g_socket_bind (GSocket         *socket,
2142                GSocketAddress  *address,
2143                gboolean         reuse_address,
2144                GError         **error)
2145 {
2146   union {
2147     struct sockaddr_storage storage;
2148     struct sockaddr sa;
2149   } addr;
2150   gboolean so_reuseaddr;
2151 #ifdef SO_REUSEPORT
2152   gboolean so_reuseport;
2153 #endif
2154
2155   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2156
2157   if (!check_socket (socket, error))
2158     return FALSE;
2159
2160   if (!g_socket_address_to_native (address, &addr.storage, sizeof addr, error))
2161     return FALSE;
2162
2163   /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2164    * sockets, but has nasty side effects we don't want for TCP
2165    * sockets.
2166    *
2167    * On other platforms, we set SO_REUSEPORT, if it exists, for
2168    * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2169    * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2170    * the desired semantics on UDP (as it does on Linux, although
2171    * Linux has SO_REUSEPORT too as of 3.9).
2172    */
2173
2174 #ifdef G_OS_WIN32
2175   so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2176 #else
2177   so_reuseaddr = !!reuse_address;
2178 #endif
2179
2180 #ifdef SO_REUSEPORT
2181   so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2182 #endif
2183
2184   /* Ignore errors here, the only likely error is "not supported", and
2185    * this is a "best effort" thing mainly.
2186    */
2187   g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2188 #ifdef SO_REUSEPORT
2189   g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2190 #endif
2191
2192   if (bind (socket->priv->fd, &addr.sa,
2193             g_socket_address_get_native_size (address)) < 0)
2194     {
2195       int errsv = get_socket_errno ();
2196       gchar *address_string = address_to_string (address);
2197
2198       g_set_error (error,
2199                    G_IO_ERROR, socket_io_error_from_errno (errsv),
2200                    _("Error binding to address %s: %s"),
2201                    address_string, socket_strerror (errsv));
2202       g_free (address_string);
2203       return FALSE;
2204     }
2205
2206   return TRUE;
2207 }
2208
2209 #ifdef G_OS_WIN32
2210 static gulong
2211 g_socket_w32_get_adapter_ipv4_addr (const gchar *name_or_ip)
2212 {
2213   ULONG bufsize = 15000; /* MS-recommended initial bufsize */
2214   DWORD ret = ERROR_BUFFER_OVERFLOW;
2215   unsigned int malloc_iterations = 0;
2216   PIP_ADAPTER_ADDRESSES addr_buf = NULL, eth_adapter;
2217   wchar_t *wchar_name_or_ip = NULL;
2218   gulong ip_result;
2219   NET_IFINDEX if_index;
2220
2221   /*
2222    * For Windows OS only - return adapter IPv4 address in network byte order.
2223    *
2224    * Input string can be either friendly name of adapter, IP address of adapter,
2225    * indextoname, or fullname of adapter.
2226    * Example:
2227    *    192.168.1.109   ===> IP address given directly,
2228    *                         convert directly with inet_addr() function
2229    *    Wi-Fi           ===> Adapter friendly name "Wi-Fi",
2230    *                         scan with GetAdapterAddresses and adapter->FriendlyName
2231    *    ethernet_32774  ===> Adapter name as returned by if_indextoname
2232    *    {33E8F5CD-BAEA-4214-BE13-B79AB8080CAB} ===> Adaptername,
2233    *                         as returned in GetAdapterAddresses and adapter->AdapterName
2234    */
2235
2236   /* Step 1: Check if string is an IP address: */
2237   ip_result = inet_addr (name_or_ip);
2238   if (ip_result != INADDR_NONE)
2239     return ip_result;  /* Success, IP address string was given directly */
2240
2241   /*
2242    *  Step 2: Check if name represents a valid Interface index (e.g. ethernet_75521)
2243    *  function if_nametoindex will return >=1 if a valid index, or 0=no match
2244    *  valid index will be used later in GetAdaptersAddress loop for lookup of adapter IP address
2245    */
2246   if_index = if_nametoindex (name_or_ip);
2247
2248   /* Step 3: Prepare wchar string for friendly name comparison */
2249   if (if_index == 0)
2250     {
2251       size_t if_name_len = strlen (name_or_ip);
2252       if (if_name_len >= MAX_ADAPTER_NAME_LENGTH + 4)
2253         return INADDR_NONE;
2254       /* Name-check only needed if index=0... */
2255       wchar_name_or_ip = (wchar_t *) g_try_malloc ((if_name_len + 1) * sizeof(wchar_t));
2256       if (wchar_name_or_ip)
2257         mbstowcs (wchar_name_or_ip, name_or_ip, if_name_len + 1);
2258       /* NOTE: Even if malloc fails here, some comparisons can still be done later... so no exit here! */
2259     }
2260
2261   /*
2262    *  Step 4: Allocate memory and get adapter addresses.
2263    *  Buffer allocation loop recommended by MS, since size can be dynamic
2264    *  https://docs.microsoft.com/en-us/windows/desktop/api/iphlpapi/nf-iphlpapi-getadaptersaddresses
2265    */
2266   #define MAX_ALLOC_ITERATIONS 3
2267   do
2268     {
2269       malloc_iterations++;
2270       addr_buf = (PIP_ADAPTER_ADDRESSES) g_try_realloc (addr_buf, bufsize);
2271       if (addr_buf)
2272         ret = GetAdaptersAddresses (AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, addr_buf, &bufsize);
2273     }
2274   while (addr_buf &&
2275            ret == ERROR_BUFFER_OVERFLOW &&
2276            malloc_iterations < MAX_ALLOC_ITERATIONS);
2277   #undef MAX_ALLOC_ITERATIONS
2278
2279   if (addr_buf == 0 || ret != NO_ERROR)
2280     {
2281       g_free (addr_buf);
2282       g_free (wchar_name_or_ip);
2283       return INADDR_NONE;
2284     }
2285
2286   /* Step 5: Loop through adapters and check match for index or name */
2287   for (eth_adapter = addr_buf; eth_adapter != NULL; eth_adapter = eth_adapter->Next)
2288     {
2289       /* Check if match for interface index/name: */
2290       gboolean any_match = (if_index > 0) && (eth_adapter->IfIndex == if_index);
2291
2292       /* Check if match for friendly name - but only if NO if_index! */
2293       if (!any_match && if_index == 0 && eth_adapter->FriendlyName &&
2294           eth_adapter->FriendlyName[0] != 0 && wchar_name_or_ip != NULL)
2295         any_match = (_wcsicmp (eth_adapter->FriendlyName, wchar_name_or_ip) == 0);
2296
2297       /* Check if match for adapter low level name - but only if NO if_index: */
2298       if (!any_match && if_index == 0 && eth_adapter->AdapterName &&
2299           eth_adapter->AdapterName[0] != 0)
2300         any_match = (stricmp (eth_adapter->AdapterName, name_or_ip) == 0);
2301
2302       if (any_match)
2303         {
2304           /* We have match for this adapter, lets get its local unicast IP address! */
2305           PIP_ADAPTER_UNICAST_ADDRESS uni_addr;
2306           for (uni_addr = eth_adapter->FirstUnicastAddress;
2307               uni_addr != NULL; uni_addr = uni_addr->Next)
2308             {
2309               if (uni_addr->Address.lpSockaddr->sa_family == AF_INET)
2310                 {
2311                   ip_result = ((PSOCKADDR_IN) uni_addr->Address.lpSockaddr)->sin_addr.S_un.S_addr;
2312                   break; /* finished, exit unicast addr loop */
2313                 }
2314             }
2315         }
2316     }
2317
2318   g_free (addr_buf);
2319   g_free (wchar_name_or_ip);
2320
2321   return ip_result;
2322 }
2323 #endif
2324
2325 static gboolean
2326 g_socket_multicast_group_operation (GSocket       *socket,
2327                                     GInetAddress  *group,
2328                                     gboolean       source_specific,
2329                                     const gchar   *iface,
2330                                     gboolean       join_group,
2331                                     GError       **error)
2332 {
2333   const guint8 *native_addr;
2334   gint optname, result;
2335
2336   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2337   g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2338   g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2339
2340   if (!check_socket (socket, error))
2341     return FALSE;
2342
2343   native_addr = g_inet_address_to_bytes (group);
2344   if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2345     {
2346 #ifdef HAVE_IP_MREQN
2347       struct ip_mreqn mc_req;
2348 #else
2349       struct ip_mreq mc_req;
2350 #endif
2351
2352       memset (&mc_req, 0, sizeof (mc_req));
2353       memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2354
2355 #ifdef HAVE_IP_MREQN
2356       if (iface)
2357         mc_req.imr_ifindex = if_nametoindex (iface);
2358       else
2359         mc_req.imr_ifindex = 0;  /* Pick any.  */
2360 #elif defined(G_OS_WIN32)
2361       if (iface)
2362         mc_req.imr_interface.s_addr = g_socket_w32_get_adapter_ipv4_addr (iface);
2363       else
2364         mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2365 #else
2366       mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2367 #endif
2368
2369       if (source_specific)
2370         {
2371 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2372           optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2373 #else
2374           g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2375                        join_group ?
2376                        _("Error joining multicast group: %s") :
2377                        _("Error leaving multicast group: %s"),
2378                        _("No support for source-specific multicast"));
2379           return FALSE;
2380 #endif
2381         }
2382       else
2383         optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2384       result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2385                            &mc_req, sizeof (mc_req));
2386     }
2387   else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2388     {
2389       struct ipv6_mreq mc_req_ipv6;
2390
2391       memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2392       memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2393 #ifdef HAVE_IF_NAMETOINDEX
2394       if (iface)
2395         mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2396       else
2397 #endif
2398         mc_req_ipv6.ipv6mr_interface = 0;
2399
2400       optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2401       result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2402                            &mc_req_ipv6, sizeof (mc_req_ipv6));
2403     }
2404   else
2405     g_return_val_if_reached (FALSE);
2406
2407   if (result < 0)
2408     {
2409       int errsv = get_socket_errno ();
2410
2411       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2412                    join_group ?
2413                    _("Error joining multicast group: %s") :
2414                    _("Error leaving multicast group: %s"),
2415                    socket_strerror (errsv));
2416       return FALSE;
2417     }
2418
2419   return TRUE;
2420 }
2421
2422 /**
2423  * g_socket_join_multicast_group:
2424  * @socket: a #GSocket.
2425  * @group: a #GInetAddress specifying the group address to join.
2426  * @iface: (nullable): Name of the interface to use, or %NULL
2427  * @source_specific: %TRUE if source-specific multicast should be used
2428  * @error: #GError for error reporting, or %NULL to ignore.
2429  *
2430  * Registers @socket to receive multicast messages sent to @group.
2431  * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2432  * been bound to an appropriate interface and port with
2433  * g_socket_bind().
2434  *
2435  * If @iface is %NULL, the system will automatically pick an interface
2436  * to bind to based on @group.
2437  *
2438  * If @source_specific is %TRUE, source-specific multicast as defined
2439  * in RFC 4604 is used. Note that on older platforms this may fail
2440  * with a %G_IO_ERROR_NOT_SUPPORTED error.
2441  *
2442  * To bind to a given source-specific multicast address, use
2443  * g_socket_join_multicast_group_ssm() instead.
2444  *
2445  * Returns: %TRUE on success, %FALSE on error.
2446  *
2447  * Since: 2.32
2448  */
2449 gboolean
2450 g_socket_join_multicast_group (GSocket       *socket,
2451                                GInetAddress  *group,
2452                                gboolean       source_specific,
2453                                const gchar   *iface,
2454                                GError       **error)
2455 {
2456   return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2457 }
2458
2459 /**
2460  * g_socket_leave_multicast_group:
2461  * @socket: a #GSocket.
2462  * @group: a #GInetAddress specifying the group address to leave.
2463  * @iface: (nullable): Interface used
2464  * @source_specific: %TRUE if source-specific multicast was used
2465  * @error: #GError for error reporting, or %NULL to ignore.
2466  *
2467  * Removes @socket from the multicast group defined by @group, @iface,
2468  * and @source_specific (which must all have the same values they had
2469  * when you joined the group).
2470  *
2471  * @socket remains bound to its address and port, and can still receive
2472  * unicast messages after calling this.
2473  *
2474  * To unbind to a given source-specific multicast address, use
2475  * g_socket_leave_multicast_group_ssm() instead.
2476  *
2477  * Returns: %TRUE on success, %FALSE on error.
2478  *
2479  * Since: 2.32
2480  */
2481 gboolean
2482 g_socket_leave_multicast_group (GSocket       *socket,
2483                                 GInetAddress  *group,
2484                                 gboolean       source_specific,
2485                                 const gchar   *iface,
2486                                 GError       **error)
2487 {
2488   return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2489 }
2490
2491 static gboolean
2492 g_socket_multicast_group_operation_ssm (GSocket       *socket,
2493                                         GInetAddress  *group,
2494                                         GInetAddress  *source_specific,
2495                                         const gchar   *iface,
2496                                         gboolean       join_group,
2497                                         GError       **error)
2498 {
2499   gint result;
2500
2501   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2502   g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2503   g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2504   g_return_val_if_fail (iface == NULL || *iface != '\0', FALSE);
2505   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2506
2507   if (!source_specific)
2508     {
2509       return g_socket_multicast_group_operation (socket, group, FALSE, iface,
2510                                                  join_group, error);
2511     }
2512
2513   if (!check_socket (socket, error))
2514     return FALSE;
2515
2516   switch (g_inet_address_get_family (group))
2517     {
2518     case G_SOCKET_FAMILY_INVALID:
2519     case G_SOCKET_FAMILY_UNIX:
2520       {
2521         g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2522             join_group ?
2523             _("Error joining multicast group: %s") :
2524             _("Error leaving multicast group: %s"),
2525             _("Unsupported socket family"));
2526         return FALSE;
2527       }
2528       break;
2529
2530     case G_SOCKET_FAMILY_IPV4:
2531       {
2532 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2533
2534 #ifdef BROKEN_IP_MREQ_SOURCE_STRUCT
2535 #define S_ADDR_FIELD(src) src.imr_interface
2536 #else
2537 #define S_ADDR_FIELD(src) src.imr_interface.s_addr
2538 #endif
2539
2540         gint optname;
2541         struct ip_mreq_source mc_req_src;
2542
2543         if (g_inet_address_get_family (source_specific) !=
2544             G_SOCKET_FAMILY_IPV4)
2545           {
2546             g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2547                 join_group ?
2548                 _("Error joining multicast group: %s") :
2549                 _("Error leaving multicast group: %s"),
2550                 _("source-specific not an IPv4 address"));
2551             return FALSE;
2552           }
2553
2554         memset (&mc_req_src, 0, sizeof (mc_req_src));
2555
2556         /* By default use the default IPv4 multicast interface. */
2557         S_ADDR_FIELD(mc_req_src) = g_htonl (INADDR_ANY);
2558
2559         if (iface)
2560           {
2561 #if defined(G_OS_WIN32)
2562             S_ADDR_FIELD(mc_req_src) = g_socket_w32_get_adapter_ipv4_addr (iface);
2563 #elif defined (HAVE_SIOCGIFADDR)
2564             int ret;
2565             struct ifreq ifr;
2566             struct sockaddr_in *iface_addr;
2567             size_t if_name_len = strlen (iface);
2568
2569             memset (&ifr, 0, sizeof (ifr));
2570
2571             if (if_name_len >= sizeof (ifr.ifr_name))
2572               {
2573                 g_set_error (error, G_IO_ERROR,  G_IO_ERROR_FILENAME_TOO_LONG,
2574                              _("Interface name too long"));
2575                 return FALSE;
2576               }
2577
2578             memcpy (ifr.ifr_name, iface, if_name_len);
2579
2580             /* Get the IPv4 address of the given network interface name. */
2581             ret = ioctl (socket->priv->fd, SIOCGIFADDR, &ifr);
2582             if (ret < 0)
2583               {
2584                 int errsv = errno;
2585
2586                 g_set_error (error, G_IO_ERROR,  g_io_error_from_errno (errsv),
2587                              _("Interface not found: %s"), g_strerror (errsv));
2588                 return FALSE;
2589               }
2590
2591             iface_addr = (struct sockaddr_in *) &ifr.ifr_addr;
2592             S_ADDR_FIELD(mc_req_src) = iface_addr->sin_addr.s_addr;
2593 #endif  /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2594           }
2595         memcpy (&mc_req_src.imr_multiaddr, g_inet_address_to_bytes (group),
2596                 g_inet_address_get_native_size (group));
2597         memcpy (&mc_req_src.imr_sourceaddr,
2598                 g_inet_address_to_bytes (source_specific),
2599                 g_inet_address_get_native_size (source_specific));
2600
2601         optname =
2602             join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2603         result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2604                              &mc_req_src, sizeof (mc_req_src));
2605
2606 #undef S_ADDR_FIELD
2607
2608 #else
2609         g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2610             join_group ?
2611             _("Error joining multicast group: %s") :
2612             _("Error leaving multicast group: %s"),
2613             _("No support for IPv4 source-specific multicast"));
2614         return FALSE;
2615 #endif  /* IP_ADD_SOURCE_MEMBERSHIP */
2616       }
2617       break;
2618
2619     case G_SOCKET_FAMILY_IPV6:
2620       {
2621 #ifdef MCAST_JOIN_SOURCE_GROUP
2622         gboolean res;
2623         gint optname;
2624         struct group_source_req mc_req_src;
2625         GSocketAddress *saddr_group, *saddr_source_specific;
2626         guint iface_index = 0;
2627
2628 #if defined (HAVE_IF_NAMETOINDEX)
2629         if (iface)
2630           {
2631             iface_index = if_nametoindex (iface);
2632             if (iface_index == 0)
2633               {
2634                 int errsv = errno;
2635
2636                 g_set_error (error, G_IO_ERROR,  g_io_error_from_errno (errsv),
2637                              _("Interface not found: %s"), g_strerror (errsv));
2638                 return FALSE;
2639               }
2640           }
2641 #endif  /* defined (HAVE_IF_NAMETOINDEX) */
2642         mc_req_src.gsr_interface = iface_index;
2643
2644         saddr_group = g_inet_socket_address_new (group, 0);
2645         res = g_socket_address_to_native (saddr_group, &mc_req_src.gsr_group,
2646                                           sizeof (mc_req_src.gsr_group),
2647                                           error);
2648         g_object_unref (saddr_group);
2649         if (!res)
2650           return FALSE;
2651
2652         saddr_source_specific = g_inet_socket_address_new (source_specific, 0);
2653         res = g_socket_address_to_native (saddr_source_specific,
2654                                           &mc_req_src.gsr_source,
2655                                           sizeof (mc_req_src.gsr_source),
2656                                           error);
2657         g_object_unref (saddr_source_specific);
2658
2659         if (!res)
2660           return FALSE;
2661
2662         optname =
2663             join_group ? MCAST_JOIN_SOURCE_GROUP : MCAST_LEAVE_SOURCE_GROUP;
2664         result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2665                              &mc_req_src, sizeof (mc_req_src));
2666 #else
2667         g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2668             join_group ?
2669             _("Error joining multicast group: %s") :
2670             _("Error leaving multicast group: %s"),
2671             _("No support for IPv6 source-specific multicast"));
2672         return FALSE;
2673 #endif  /* MCAST_JOIN_SOURCE_GROUP */
2674       }
2675       break;
2676
2677     default:
2678       g_return_val_if_reached (FALSE);
2679     }
2680
2681   if (result < 0)
2682     {
2683       int errsv = get_socket_errno ();
2684
2685       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2686           join_group ?
2687           _("Error joining multicast group: %s") :
2688           _("Error leaving multicast group: %s"),
2689            socket_strerror (errsv));
2690       return FALSE;
2691     }
2692
2693   return TRUE;
2694 }
2695
2696 /**
2697  * g_socket_join_multicast_group_ssm:
2698  * @socket: a #GSocket.
2699  * @group: a #GInetAddress specifying the group address to join.
2700  * @source_specific: (nullable): a #GInetAddress specifying the
2701  * source-specific multicast address or %NULL to ignore.
2702  * @iface: (nullable): Name of the interface to use, or %NULL
2703  * @error: #GError for error reporting, or %NULL to ignore.
2704  *
2705  * Registers @socket to receive multicast messages sent to @group.
2706  * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2707  * been bound to an appropriate interface and port with
2708  * g_socket_bind().
2709  *
2710  * If @iface is %NULL, the system will automatically pick an interface
2711  * to bind to based on @group.
2712  *
2713  * If @source_specific is not %NULL, use source-specific multicast as
2714  * defined in RFC 4604. Note that on older platforms this may fail
2715  * with a %G_IO_ERROR_NOT_SUPPORTED error.
2716  *
2717  * Note that this function can be called multiple times for the same
2718  * @group with different @source_specific in order to receive multicast
2719  * packets from more than one source.
2720  *
2721  * Returns: %TRUE on success, %FALSE on error.
2722  *
2723  * Since: 2.56
2724  */
2725 gboolean
2726 g_socket_join_multicast_group_ssm (GSocket       *socket,
2727                                    GInetAddress  *group,
2728                                    GInetAddress  *source_specific,
2729                                    const gchar   *iface,
2730                                    GError       **error)
2731 {
2732   return g_socket_multicast_group_operation_ssm (socket, group,
2733       source_specific, iface, TRUE, error);
2734 }
2735
2736 /**
2737  * g_socket_leave_multicast_group_ssm:
2738  * @socket: a #GSocket.
2739  * @group: a #GInetAddress specifying the group address to leave.
2740  * @source_specific: (nullable): a #GInetAddress specifying the
2741  * source-specific multicast address or %NULL to ignore.
2742  * @iface: (nullable): Name of the interface to use, or %NULL
2743  * @error: #GError for error reporting, or %NULL to ignore.
2744  *
2745  * Removes @socket from the multicast group defined by @group, @iface,
2746  * and @source_specific (which must all have the same values they had
2747  * when you joined the group).
2748  *
2749  * @socket remains bound to its address and port, and can still receive
2750  * unicast messages after calling this.
2751  *
2752  * Returns: %TRUE on success, %FALSE on error.
2753  *
2754  * Since: 2.56
2755  */
2756 gboolean
2757 g_socket_leave_multicast_group_ssm (GSocket       *socket,
2758                                     GInetAddress  *group,
2759                                     GInetAddress  *source_specific,
2760                                     const gchar   *iface,
2761                                     GError       **error)
2762 {
2763   return g_socket_multicast_group_operation_ssm (socket, group,
2764       source_specific, iface, FALSE, error);
2765 }
2766
2767 /**
2768  * g_socket_speaks_ipv4:
2769  * @socket: a #GSocket
2770  *
2771  * Checks if a socket is capable of speaking IPv4.
2772  *
2773  * IPv4 sockets are capable of speaking IPv4.  On some operating systems
2774  * and under some combinations of circumstances IPv6 sockets are also
2775  * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
2776  * information.
2777  *
2778  * No other types of sockets are currently considered as being capable
2779  * of speaking IPv4.
2780  *
2781  * Returns: %TRUE if this socket can be used with IPv4.
2782  *
2783  * Since: 2.22
2784  **/
2785 gboolean
2786 g_socket_speaks_ipv4 (GSocket *socket)
2787 {
2788   switch (socket->priv->family)
2789     {
2790     case G_SOCKET_FAMILY_IPV4:
2791       return TRUE;
2792
2793     case G_SOCKET_FAMILY_IPV6:
2794 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2795       {
2796         gint v6_only;
2797
2798         if (!g_socket_get_option (socket,
2799                                   IPPROTO_IPV6, IPV6_V6ONLY,
2800                                   &v6_only, NULL))
2801           return FALSE;
2802
2803         return !v6_only;
2804       }
2805 #else
2806       return FALSE;
2807 #endif
2808
2809     default:
2810       return FALSE;
2811     }
2812 }
2813
2814 /**
2815  * g_socket_accept:
2816  * @socket: a #GSocket.
2817  * @cancellable: (nullable): a %GCancellable or %NULL
2818  * @error: #GError for error reporting, or %NULL to ignore.
2819  *
2820  * Accept incoming connections on a connection-based socket. This removes
2821  * the first outstanding connection request from the listening socket and
2822  * creates a #GSocket object for it.
2823  *
2824  * The @socket must be bound to a local address with g_socket_bind() and
2825  * must be listening for incoming connections (g_socket_listen()).
2826  *
2827  * If there are no outstanding connections then the operation will block
2828  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2829  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2830  *
2831  * Returns: (transfer full): a new #GSocket, or %NULL on error.
2832  *     Free the returned object with g_object_unref().
2833  *
2834  * Since: 2.22
2835  */
2836 GSocket *
2837 g_socket_accept (GSocket       *socket,
2838                  GCancellable  *cancellable,
2839                  GError       **error)
2840 {
2841   GSocket *new_socket;
2842   gint ret;
2843
2844   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2845
2846   if (!check_socket (socket, error))
2847     return NULL;
2848
2849   if (!check_timeout (socket, error))
2850     return NULL;
2851
2852   while (TRUE)
2853     {
2854       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2855         {
2856           int errsv = get_socket_errno ();
2857
2858           if (errsv == EINTR)
2859             continue;
2860
2861 #ifdef WSAEWOULDBLOCK
2862           if (errsv == WSAEWOULDBLOCK)
2863 #else
2864           if (errsv == EWOULDBLOCK ||
2865               errsv == EAGAIN)
2866 #endif
2867             {
2868               win32_unset_event_mask (socket, FD_ACCEPT);
2869
2870               if (socket->priv->blocking)
2871                 {
2872                   if (!g_socket_condition_wait (socket,
2873                                                 G_IO_IN, cancellable, error))
2874                     return NULL;
2875
2876                   continue;
2877                 }
2878             }
2879
2880           socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2881           return NULL;
2882         }
2883       break;
2884     }
2885
2886   win32_unset_event_mask (socket, FD_ACCEPT);
2887
2888 #ifdef G_OS_WIN32
2889   {
2890     /* The socket inherits the accepting sockets event mask and even object,
2891        we need to remove that */
2892     WSAEventSelect (ret, NULL, 0);
2893   }
2894 #else
2895   {
2896     int flags;
2897
2898     /* We always want to set close-on-exec to protect users. If you
2899        need to so some weird inheritance to exec you can re-enable this
2900        using lower level hacks with g_socket_get_fd(). */
2901     flags = fcntl (ret, F_GETFD, 0);
2902     if (flags != -1 &&
2903         (flags & FD_CLOEXEC) == 0)
2904       {
2905         flags |= FD_CLOEXEC;
2906         fcntl (ret, F_SETFD, flags);
2907       }
2908   }
2909 #endif
2910
2911   new_socket = g_socket_new_from_fd (ret, error);
2912   if (new_socket == NULL)
2913     {
2914 #ifdef G_OS_WIN32
2915       closesocket (ret);
2916 #else
2917       close (ret);
2918 #endif
2919     }
2920   else
2921     new_socket->priv->protocol = socket->priv->protocol;
2922
2923   return new_socket;
2924 }
2925
2926 /**
2927  * g_socket_connect:
2928  * @socket: a #GSocket.
2929  * @address: a #GSocketAddress specifying the remote address.
2930  * @cancellable: (nullable): a %GCancellable or %NULL
2931  * @error: #GError for error reporting, or %NULL to ignore.
2932  *
2933  * Connect the socket to the specified remote address.
2934  *
2935  * For connection oriented socket this generally means we attempt to make
2936  * a connection to the @address. For a connection-less socket it sets
2937  * the default address for g_socket_send() and discards all incoming datagrams
2938  * from other sources.
2939  *
2940  * Generally connection oriented sockets can only connect once, but
2941  * connection-less sockets can connect multiple times to change the
2942  * default address.
2943  *
2944  * If the connect call needs to do network I/O it will block, unless
2945  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2946  * and the user can be notified of the connection finishing by waiting
2947  * for the G_IO_OUT condition. The result of the connection must then be
2948  * checked with g_socket_check_connect_result().
2949  *
2950  * Returns: %TRUE if connected, %FALSE on error.
2951  *
2952  * Since: 2.22
2953  */
2954 gboolean
2955 g_socket_connect (GSocket         *socket,
2956                   GSocketAddress  *address,
2957                   GCancellable    *cancellable,
2958                   GError         **error)
2959 {
2960   union {
2961     struct sockaddr_storage storage;
2962     struct sockaddr sa;
2963   } buffer;
2964
2965   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2966
2967   if (!check_socket (socket, error))
2968     return FALSE;
2969
2970   if (!g_socket_address_to_native (address, &buffer.storage, sizeof buffer, error))
2971     return FALSE;
2972
2973   if (socket->priv->remote_address)
2974     g_object_unref (socket->priv->remote_address);
2975   socket->priv->remote_address = g_object_ref (address);
2976
2977   while (1)
2978     {
2979       if (connect (socket->priv->fd, &buffer.sa,
2980                    g_socket_address_get_native_size (address)) < 0)
2981         {
2982           int errsv = get_socket_errno ();
2983
2984           if (errsv == EINTR)
2985             continue;
2986
2987 #ifndef G_OS_WIN32
2988           if (errsv == EINPROGRESS)
2989 #else
2990           if (errsv == WSAEWOULDBLOCK)
2991 #endif
2992             {
2993               win32_unset_event_mask (socket, FD_CONNECT);
2994
2995               if (socket->priv->blocking)
2996                 {
2997                   if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2998                     {
2999                       if (g_socket_check_connect_result (socket, error))
3000                         break;
3001                     }
3002                 }
3003               else
3004                 {
3005                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
3006                                        _("Connection in progress"));
3007                   socket->priv->connect_pending = TRUE;
3008                 }
3009             }
3010           else
3011             g_set_error_literal (error, G_IO_ERROR,
3012                                  socket_io_error_from_errno (errsv),
3013                                  socket_strerror (errsv));
3014
3015           return FALSE;
3016         }
3017       break;
3018     }
3019
3020   win32_unset_event_mask (socket, FD_CONNECT);
3021
3022   socket->priv->connected_read = TRUE;
3023   socket->priv->connected_write = TRUE;
3024
3025   return TRUE;
3026 }
3027
3028 /**
3029  * g_socket_check_connect_result:
3030  * @socket: a #GSocket
3031  * @error: #GError for error reporting, or %NULL to ignore.
3032  *
3033  * Checks and resets the pending connect error for the socket.
3034  * This is used to check for errors when g_socket_connect() is
3035  * used in non-blocking mode.
3036  *
3037  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
3038  *
3039  * Since: 2.22
3040  */
3041 gboolean
3042 g_socket_check_connect_result (GSocket  *socket,
3043                                GError  **error)
3044 {
3045   int value;
3046
3047   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3048
3049   if (!check_socket (socket, error))
3050     return FALSE;
3051
3052   if (!check_timeout (socket, error))
3053     return FALSE;
3054
3055   if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
3056     {
3057       g_prefix_error (error, _("Unable to get pending error: "));
3058       return FALSE;
3059     }
3060
3061   if (value != 0)
3062     {
3063       g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
3064                            socket_strerror (value));
3065       if (socket->priv->remote_address)
3066         {
3067           g_object_unref (socket->priv->remote_address);
3068           socket->priv->remote_address = NULL;
3069         }
3070       return FALSE;
3071     }
3072
3073   socket->priv->connected_read = TRUE;
3074   socket->priv->connected_write = TRUE;
3075
3076   return TRUE;
3077 }
3078
3079 /**
3080  * g_socket_get_available_bytes:
3081  * @socket: a #GSocket
3082  *
3083  * Get the amount of data pending in the OS input buffer, without blocking.
3084  *
3085  * If @socket is a UDP or SCTP socket, this will return the size of
3086  * just the next packet, even if additional packets are buffered after
3087  * that one.
3088  *
3089  * Note that on Windows, this function is rather inefficient in the
3090  * UDP case, and so if you know any plausible upper bound on the size
3091  * of the incoming packet, it is better to just do a
3092  * g_socket_receive() with a buffer of that size, rather than calling
3093  * g_socket_get_available_bytes() first and then doing a receive of
3094  * exactly the right size.
3095  *
3096  * Returns: the number of bytes that can be read from the socket
3097  * without blocking or truncating, or -1 on error.
3098  *
3099  * Since: 2.32
3100  */
3101 gssize
3102 g_socket_get_available_bytes (GSocket *socket)
3103 {
3104 #ifndef SO_NREAD
3105   const gint bufsize = 64 * 1024;
3106   static guchar *buf = NULL;
3107 #endif
3108 #ifdef G_OS_WIN32
3109   u_long avail;
3110 #else
3111   gint avail;
3112 #endif
3113
3114   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3115
3116   if (!check_socket (socket, NULL))
3117     return -1;
3118
3119 #ifdef SO_NREAD
3120   if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
3121       return -1;
3122 #else
3123   if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
3124     {
3125       if (G_UNLIKELY (g_once_init_enter (&buf)))
3126         g_once_init_leave (&buf, g_malloc (bufsize));
3127
3128       /* On datagram sockets, FIONREAD ioctl is not reliable because many
3129        * systems add internal header size to the reported size, making it
3130        * unusable for this function. */
3131       avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
3132       if (avail == -1)
3133         {
3134           int errsv = get_socket_errno ();
3135 #ifdef G_OS_WIN32
3136           if (errsv == WSAEWOULDBLOCK)
3137 #else
3138           if (errsv == EWOULDBLOCK || errsv == EAGAIN)
3139 #endif
3140             avail = 0;
3141         }
3142     }
3143   else
3144     {
3145 #ifdef G_OS_WIN32
3146       if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
3147 #else
3148       if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
3149 #endif
3150         avail = -1;
3151     }
3152 #endif
3153
3154   return avail;
3155 }
3156
3157 /* Block on a timed wait for @condition until (@start_time + @timeout).
3158  * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
3159  */
3160 static gboolean
3161 block_on_timeout (GSocket       *socket,
3162                   GIOCondition   condition,
3163                   gint64         timeout_us,
3164                   gint64         start_time,
3165                   GCancellable  *cancellable,
3166                   GError       **error)
3167 {
3168   gint64 wait_timeout = -1;
3169
3170   g_return_val_if_fail (timeout_us != 0, TRUE);
3171
3172   /* check if we've timed out or how much time to wait at most */
3173   if (timeout_us >= 0)
3174     {
3175       gint64 elapsed = g_get_monotonic_time () - start_time;
3176
3177       if (elapsed >= timeout_us)
3178         {
3179           g_set_error_literal (error,
3180                                G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3181                                _("Socket I/O timed out"));
3182           return FALSE;
3183         }
3184
3185       wait_timeout = timeout_us - elapsed;
3186     }
3187
3188   return g_socket_condition_timed_wait (socket, condition, wait_timeout,
3189                                         cancellable, error);
3190 }
3191
3192 static gssize
3193 g_socket_receive_with_timeout (GSocket       *socket,
3194                                guint8        *buffer,
3195                                gsize          size,
3196                                gint64         timeout_us,
3197                                GCancellable  *cancellable,
3198                                GError       **error)
3199 {
3200   gssize ret;
3201   gint64 start_time;
3202
3203   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3204
3205   start_time = g_get_monotonic_time ();
3206
3207   if (!check_socket (socket, error))
3208     return -1;
3209
3210   if (!check_timeout (socket, error))
3211     return -1;
3212
3213   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3214     return -1;
3215
3216   while (1)
3217     {
3218       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
3219         {
3220           int errsv = get_socket_errno ();
3221
3222           if (errsv == EINTR)
3223             continue;
3224
3225 #ifdef WSAEWOULDBLOCK
3226           if (errsv == WSAEWOULDBLOCK)
3227 #else
3228           if (errsv == EWOULDBLOCK ||
3229               errsv == EAGAIN)
3230 #endif
3231             {
3232               win32_unset_event_mask (socket, FD_READ);
3233
3234               if (timeout_us != 0)
3235                 {
3236                   if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
3237                                          cancellable, error))
3238                     return -1;
3239
3240                   continue;
3241                 }
3242             }
3243
3244           win32_unset_event_mask (socket, FD_READ);
3245
3246           socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
3247           return -1;
3248         }
3249
3250       win32_unset_event_mask (socket, FD_READ);
3251
3252       break;
3253     }
3254
3255   return ret;
3256 }
3257
3258 /**
3259  * g_socket_receive:
3260  * @socket: a #GSocket
3261  * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3262  *     a buffer to read data into (which should be at least @size bytes long).
3263  * @size: the number of bytes you want to read from the socket
3264  * @cancellable: (nullable): a %GCancellable or %NULL
3265  * @error: #GError for error reporting, or %NULL to ignore.
3266  *
3267  * Receive data (up to @size bytes) from a socket. This is mainly used by
3268  * connection-oriented sockets; it is identical to g_socket_receive_from()
3269  * with @address set to %NULL.
3270  *
3271  * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3272  * g_socket_receive() will always read either 0 or 1 complete messages from
3273  * the socket. If the received message is too large to fit in @buffer, then
3274  * the data beyond @size bytes will be discarded, without any explicit
3275  * indication that this has occurred.
3276  *
3277  * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3278  * number of bytes, up to @size. If more than @size bytes have been
3279  * received, the additional data will be returned in future calls to
3280  * g_socket_receive().
3281  *
3282  * If the socket is in blocking mode the call will block until there
3283  * is some data to receive, the connection is closed, or there is an
3284  * error. If there is no data available and the socket is in
3285  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3286  * returned. To be notified when data is available, wait for the
3287  * %G_IO_IN condition.
3288  *
3289  * On error -1 is returned and @error is set accordingly.
3290  *
3291  * Returns: Number of bytes read, or 0 if the connection was closed by
3292  * the peer, or -1 on error
3293  *
3294  * Since: 2.22
3295  */
3296 gssize
3297 g_socket_receive (GSocket       *socket,
3298                   gchar         *buffer,
3299                   gsize          size,
3300                   GCancellable  *cancellable,
3301                   GError       **error)
3302 {
3303   return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3304                                         socket->priv->blocking ? -1 : 0,
3305                                         cancellable, error);
3306 }
3307
3308 /**
3309  * g_socket_receive_with_blocking:
3310  * @socket: a #GSocket
3311  * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3312  *     a buffer to read data into (which should be at least @size bytes long).
3313  * @size: the number of bytes you want to read from the socket
3314  * @blocking: whether to do blocking or non-blocking I/O
3315  * @cancellable: (nullable): a %GCancellable or %NULL
3316  * @error: #GError for error reporting, or %NULL to ignore.
3317  *
3318  * This behaves exactly the same as g_socket_receive(), except that
3319  * the choice of blocking or non-blocking behavior is determined by
3320  * the @blocking argument rather than by @socket's properties.
3321  *
3322  * Returns: Number of bytes read, or 0 if the connection was closed by
3323  * the peer, or -1 on error
3324  *
3325  * Since: 2.26
3326  */
3327 gssize
3328 g_socket_receive_with_blocking (GSocket       *socket,
3329                                 gchar         *buffer,
3330                                 gsize          size,
3331                                 gboolean       blocking,
3332                                 GCancellable  *cancellable,
3333                                 GError       **error)
3334 {
3335   return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3336                                         blocking ? -1 : 0, cancellable, error);
3337 }
3338
3339 /**
3340  * g_socket_receive_from:
3341  * @socket: a #GSocket
3342  * @address: (out) (optional): a pointer to a #GSocketAddress
3343  *     pointer, or %NULL
3344  * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3345  *     a buffer to read data into (which should be at least @size bytes long).
3346  * @size: the number of bytes you want to read from the socket
3347  * @cancellable: (nullable): a %GCancellable or %NULL
3348  * @error: #GError for error reporting, or %NULL to ignore.
3349  *
3350  * Receive data (up to @size bytes) from a socket.
3351  *
3352  * If @address is non-%NULL then @address will be set equal to the
3353  * source address of the received packet.
3354  * @address is owned by the caller.
3355  *
3356  * See g_socket_receive() for additional information.
3357  *
3358  * Returns: Number of bytes read, or 0 if the connection was closed by
3359  * the peer, or -1 on error
3360  *
3361  * Since: 2.22
3362  */
3363 gssize
3364 g_socket_receive_from (GSocket         *socket,
3365                        GSocketAddress **address,
3366                        gchar           *buffer,
3367                        gsize            size,
3368                        GCancellable    *cancellable,
3369                        GError         **error)
3370 {
3371   GInputVector v;
3372
3373   v.buffer = buffer;
3374   v.size = size;
3375
3376   return g_socket_receive_message (socket,
3377                                    address,
3378                                    &v, 1,
3379                                    NULL, 0, NULL,
3380                                    cancellable,
3381                                    error);
3382 }
3383
3384 /* See the comment about SIGPIPE above. */
3385 #ifdef MSG_NOSIGNAL
3386 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3387 #else
3388 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
3389 #endif
3390
3391 static gssize
3392 g_socket_send_with_timeout (GSocket       *socket,
3393                             const guint8  *buffer,
3394                             gsize          size,
3395                             gint64         timeout_us,
3396                             GCancellable  *cancellable,
3397                             GError       **error)
3398 {
3399   gssize ret;
3400   gint64 start_time;
3401
3402   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3403
3404   start_time = g_get_monotonic_time ();
3405
3406   if (!check_socket (socket, error))
3407     return -1;
3408
3409   if (!check_timeout (socket, error))
3410     return -1;
3411
3412   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3413     return -1;
3414
3415   while (1)
3416     {
3417       if ((ret = send (socket->priv->fd, (const char *)buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
3418         {
3419           int errsv = get_socket_errno ();
3420
3421           if (errsv == EINTR)
3422             continue;
3423
3424 #ifdef WSAEWOULDBLOCK
3425           if (errsv == WSAEWOULDBLOCK)
3426 #else
3427           if (errsv == EWOULDBLOCK ||
3428               errsv == EAGAIN)
3429 #endif
3430             {
3431               win32_unset_event_mask (socket, FD_WRITE);
3432
3433               if (timeout_us != 0)
3434                 {
3435                   if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
3436                                          cancellable, error))
3437                     return -1;
3438
3439                   continue;
3440                 }
3441             }
3442
3443           socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3444           return -1;
3445         }
3446       break;
3447     }
3448
3449   return ret;
3450 }
3451
3452 /**
3453  * g_socket_send:
3454  * @socket: a #GSocket
3455  * @buffer: (array length=size) (element-type guint8): the buffer
3456  *     containing the data to send.
3457  * @size: the number of bytes to send
3458  * @cancellable: (nullable): a %GCancellable or %NULL
3459  * @error: #GError for error reporting, or %NULL to ignore.
3460  *
3461  * Tries to send @size bytes from @buffer on the socket. This is
3462  * mainly used by connection-oriented sockets; it is identical to
3463  * g_socket_send_to() with @address set to %NULL.
3464  *
3465  * If the socket is in blocking mode the call will block until there is
3466  * space for the data in the socket queue. If there is no space available
3467  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3468  * will be returned. To be notified when space is available, wait for the
3469  * %G_IO_OUT condition. Note though that you may still receive
3470  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3471  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3472  * very common due to the way the underlying APIs work.)
3473  *
3474  * On error -1 is returned and @error is set accordingly.
3475  *
3476  * Returns: Number of bytes written (which may be less than @size), or -1
3477  * on error
3478  *
3479  * Since: 2.22
3480  */
3481 gssize
3482 g_socket_send (GSocket       *socket,
3483                const gchar   *buffer,
3484                gsize          size,
3485                GCancellable  *cancellable,
3486                GError       **error)
3487 {
3488   return g_socket_send_with_blocking (socket, buffer, size,
3489                                       socket->priv->blocking,
3490                                       cancellable, error);
3491 }
3492
3493 /**
3494  * g_socket_send_with_blocking:
3495  * @socket: a #GSocket
3496  * @buffer: (array length=size) (element-type guint8): the buffer
3497  *     containing the data to send.
3498  * @size: the number of bytes to send
3499  * @blocking: whether to do blocking or non-blocking I/O
3500  * @cancellable: (nullable): a %GCancellable or %NULL
3501  * @error: #GError for error reporting, or %NULL to ignore.
3502  *
3503  * This behaves exactly the same as g_socket_send(), except that
3504  * the choice of blocking or non-blocking behavior is determined by
3505  * the @blocking argument rather than by @socket's properties.
3506  *
3507  * Returns: Number of bytes written (which may be less than @size), or -1
3508  * on error
3509  *
3510  * Since: 2.26
3511  */
3512 gssize
3513 g_socket_send_with_blocking (GSocket       *socket,
3514                              const gchar   *buffer,
3515                              gsize          size,
3516                              gboolean       blocking,
3517                              GCancellable  *cancellable,
3518                              GError       **error)
3519 {
3520   return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3521                                      blocking ? -1 : 0, cancellable, error);
3522 }
3523
3524 /**
3525  * g_socket_send_to:
3526  * @socket: a #GSocket
3527  * @address: (nullable): a #GSocketAddress, or %NULL
3528  * @buffer: (array length=size) (element-type guint8): the buffer
3529  *     containing the data to send.
3530  * @size: the number of bytes to send
3531  * @cancellable: (nullable): a %GCancellable or %NULL
3532  * @error: #GError for error reporting, or %NULL to ignore.
3533  *
3534  * Tries to send @size bytes from @buffer to @address. If @address is
3535  * %NULL then the message is sent to the default receiver (set by
3536  * g_socket_connect()).
3537  *
3538  * See g_socket_send() for additional information.
3539  *
3540  * Returns: Number of bytes written (which may be less than @size), or -1
3541  * on error
3542  *
3543  * Since: 2.22
3544  */
3545 gssize
3546 g_socket_send_to (GSocket         *socket,
3547                   GSocketAddress  *address,
3548                   const gchar     *buffer,
3549                   gsize            size,
3550                   GCancellable    *cancellable,
3551                   GError         **error)
3552 {
3553   GOutputVector v;
3554
3555   v.buffer = buffer;
3556   v.size = size;
3557
3558   return g_socket_send_message (socket,
3559                                 address,
3560                                 &v, 1,
3561                                 NULL, 0,
3562                                 0,
3563                                 cancellable,
3564                                 error);
3565 }
3566
3567 /**
3568  * g_socket_shutdown:
3569  * @socket: a #GSocket
3570  * @shutdown_read: whether to shut down the read side
3571  * @shutdown_write: whether to shut down the write side
3572  * @error: #GError for error reporting, or %NULL to ignore.
3573  *
3574  * Shut down part or all of a full-duplex connection.
3575  *
3576  * If @shutdown_read is %TRUE then the receiving side of the connection
3577  * is shut down, and further reading is disallowed.
3578  *
3579  * If @shutdown_write is %TRUE then the sending side of the connection
3580  * is shut down, and further writing is disallowed.
3581  *
3582  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3583  *
3584  * One example where it is useful to shut down only one side of a connection is
3585  * graceful disconnect for TCP connections where you close the sending side,
3586  * then wait for the other side to close the connection, thus ensuring that the
3587  * other side saw all sent data.
3588  *
3589  * Returns: %TRUE on success, %FALSE on error
3590  *
3591  * Since: 2.22
3592  */
3593 gboolean
3594 g_socket_shutdown (GSocket   *socket,
3595                    gboolean   shutdown_read,
3596                    gboolean   shutdown_write,
3597                    GError   **error)
3598 {
3599   int how;
3600
3601   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3602
3603   if (!check_socket (socket, error))
3604     return FALSE;
3605
3606   /* Do nothing? */
3607   if (!shutdown_read && !shutdown_write)
3608     return TRUE;
3609
3610 #ifndef G_OS_WIN32
3611   if (shutdown_read && shutdown_write)
3612     how = SHUT_RDWR;
3613   else if (shutdown_read)
3614     how = SHUT_RD;
3615   else
3616     how = SHUT_WR;
3617 #else
3618   if (shutdown_read && shutdown_write)
3619     how = SD_BOTH;
3620   else if (shutdown_read)
3621     how = SD_RECEIVE;
3622   else
3623     how = SD_SEND;
3624 #endif
3625
3626   if (shutdown (socket->priv->fd, how) != 0)
3627     {
3628       int errsv = get_socket_errno ();
3629       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3630                    _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3631       return FALSE;
3632     }
3633
3634   if (shutdown_read)
3635     socket->priv->connected_read = FALSE;
3636   if (shutdown_write)
3637     socket->priv->connected_write = FALSE;
3638
3639   return TRUE;
3640 }
3641
3642 /**
3643  * g_socket_close:
3644  * @socket: a #GSocket
3645  * @error: #GError for error reporting, or %NULL to ignore.
3646  *
3647  * Closes the socket, shutting down any active connection.
3648  *
3649  * Closing a socket does not wait for all outstanding I/O operations
3650  * to finish, so the caller should not rely on them to be guaranteed
3651  * to complete even if the close returns with no error.
3652  *
3653  * Once the socket is closed, all other operations will return
3654  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3655  * return an error.
3656  *
3657  * Sockets will be automatically closed when the last reference
3658  * is dropped, but you might want to call this function to make sure
3659  * resources are released as early as possible.
3660  *
3661  * Beware that due to the way that TCP works, it is possible for
3662  * recently-sent data to be lost if either you close a socket while the
3663  * %G_IO_IN condition is set, or else if the remote connection tries to
3664  * send something to you after you close the socket but before it has
3665  * finished reading all of the data you sent. There is no easy generic
3666  * way to avoid this problem; the easiest fix is to design the network
3667  * protocol such that the client will never send data "out of turn".
3668  * Another solution is for the server to half-close the connection by
3669  * calling g_socket_shutdown() with only the @shutdown_write flag set,
3670  * and then wait for the client to notice this and close its side of the
3671  * connection, after which the server can safely call g_socket_close().
3672  * (This is what #GTcpConnection does if you call
3673  * g_tcp_connection_set_graceful_disconnect(). But of course, this
3674  * only works if the client will close its connection after the server
3675  * does.)
3676  *
3677  * Returns: %TRUE on success, %FALSE on error
3678  *
3679  * Since: 2.22
3680  */
3681 gboolean
3682 g_socket_close (GSocket  *socket,
3683                 GError  **error)
3684 {
3685   int res;
3686
3687   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3688
3689   if (socket->priv->closed)
3690     return TRUE; /* Multiple close not an error */
3691
3692   if (!check_socket (socket, error))
3693     return FALSE;
3694
3695   while (1)
3696     {
3697 #ifdef G_OS_WIN32
3698       res = closesocket (socket->priv->fd);
3699 #else
3700       res = close (socket->priv->fd);
3701 #endif
3702       if (res == -1)
3703         {
3704           int errsv = get_socket_errno ();
3705
3706           if (errsv == EINTR)
3707             continue;
3708
3709           g_set_error (error, G_IO_ERROR,
3710                        socket_io_error_from_errno (errsv),
3711                        _("Error closing socket: %s"),
3712                        socket_strerror (errsv));
3713           return FALSE;
3714         }
3715       break;
3716     }
3717
3718   socket->priv->fd = -1;
3719   socket->priv->connected_read = FALSE;
3720   socket->priv->connected_write = FALSE;
3721   socket->priv->closed = TRUE;
3722   if (socket->priv->remote_address)
3723     {
3724       g_object_unref (socket->priv->remote_address);
3725       socket->priv->remote_address = NULL;
3726     }
3727
3728   return TRUE;
3729 }
3730
3731 /**
3732  * g_socket_is_closed:
3733  * @socket: a #GSocket
3734  *
3735  * Checks whether a socket is closed.
3736  *
3737  * Returns: %TRUE if socket is closed, %FALSE otherwise
3738  *
3739  * Since: 2.22
3740  */
3741 gboolean
3742 g_socket_is_closed (GSocket *socket)
3743 {
3744   return socket->priv->closed;
3745 }
3746
3747 /* Broken source, used on errors */
3748 static gboolean
3749 broken_dispatch (GSource     *source,
3750                  GSourceFunc  callback,
3751                  gpointer     user_data)
3752 {
3753   return TRUE;
3754 }
3755
3756 static GSourceFuncs broken_funcs =
3757 {
3758   NULL,
3759   NULL,
3760   broken_dispatch,
3761   NULL
3762 };
3763
3764 #ifdef G_OS_WIN32
3765 static gint
3766 network_events_for_condition (GIOCondition condition)
3767 {
3768   int event_mask = 0;
3769
3770   if (condition & G_IO_IN)
3771     event_mask |= (FD_READ | FD_ACCEPT);
3772   if (condition & G_IO_OUT)
3773     event_mask |= (FD_WRITE | FD_CONNECT);
3774   event_mask |= FD_CLOSE;
3775
3776   return event_mask;
3777 }
3778
3779 static void
3780 ensure_event (GSocket *socket)
3781 {
3782   if (socket->priv->event == WSA_INVALID_EVENT)
3783     socket->priv->event = WSACreateEvent();
3784 }
3785
3786 static void
3787 update_select_events (GSocket *socket)
3788 {
3789   int event_mask;
3790   GIOCondition *ptr;
3791   GList *l;
3792   WSAEVENT event;
3793
3794   ensure_event (socket);
3795
3796   event_mask = 0;
3797   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3798     {
3799       ptr = l->data;
3800       event_mask |= network_events_for_condition (*ptr);
3801     }
3802
3803   if (event_mask != socket->priv->selected_events)
3804     {
3805       /* If no events selected, disable event so we can unset
3806          nonblocking mode */
3807
3808       if (event_mask == 0)
3809         event = NULL;
3810       else
3811         event = socket->priv->event;
3812
3813       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3814         socket->priv->selected_events = event_mask;
3815     }
3816 }
3817
3818 static void
3819 add_condition_watch (GSocket      *socket,
3820                      GIOCondition *condition)
3821 {
3822   g_mutex_lock (&socket->priv->win32_source_lock);
3823   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3824
3825   socket->priv->requested_conditions =
3826     g_list_prepend (socket->priv->requested_conditions, condition);
3827
3828   update_select_events (socket);
3829   g_mutex_unlock (&socket->priv->win32_source_lock);
3830 }
3831
3832 static void
3833 remove_condition_watch (GSocket      *socket,
3834                         GIOCondition *condition)
3835 {
3836   g_mutex_lock (&socket->priv->win32_source_lock);
3837   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3838
3839   socket->priv->requested_conditions =
3840     g_list_remove (socket->priv->requested_conditions, condition);
3841
3842   update_select_events (socket);
3843   g_mutex_unlock (&socket->priv->win32_source_lock);
3844 }
3845
3846 static GIOCondition
3847 update_condition_unlocked (GSocket *socket)
3848 {
3849   WSANETWORKEVENTS events;
3850   GIOCondition condition;
3851
3852   if (WSAEnumNetworkEvents (socket->priv->fd,
3853                             socket->priv->event,
3854                             &events) == 0)
3855     {
3856       socket->priv->current_events |= events.lNetworkEvents;
3857       if (events.lNetworkEvents & FD_WRITE &&
3858           events.iErrorCode[FD_WRITE_BIT] != 0)
3859         socket->priv->current_errors |= FD_WRITE;
3860       if (events.lNetworkEvents & FD_CONNECT &&
3861           events.iErrorCode[FD_CONNECT_BIT] != 0)
3862         socket->priv->current_errors |= FD_CONNECT;
3863     }
3864
3865   condition = 0;
3866   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3867     condition |= G_IO_IN;
3868
3869   if (socket->priv->current_events & FD_CLOSE)
3870     {
3871       int r, errsv, buffer;
3872
3873       r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3874       if (r < 0)
3875           errsv = get_socket_errno ();
3876
3877       if (r > 0 ||
3878           (r < 0 && errsv == WSAENOTCONN))
3879         condition |= G_IO_IN;
3880       else if (r == 0 ||
3881                (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3882                           errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3883         condition |= G_IO_HUP;
3884       else
3885         condition |= G_IO_ERR;
3886     }
3887
3888   if (socket->priv->closed)
3889     condition |= G_IO_HUP;
3890
3891   /* Never report both G_IO_OUT and HUP, these are
3892      mutually exclusive (can't write to a closed socket) */
3893   if ((condition & G_IO_HUP) == 0 &&
3894       socket->priv->current_events & FD_WRITE)
3895     {
3896       if (socket->priv->current_errors & FD_WRITE)
3897         condition |= G_IO_ERR;
3898       else
3899         condition |= G_IO_OUT;
3900     }
3901   else
3902     {
3903       if (socket->priv->current_events & FD_CONNECT)
3904         {
3905           if (socket->priv->current_errors & FD_CONNECT)
3906             condition |= (G_IO_HUP | G_IO_ERR);
3907           else
3908             condition |= G_IO_OUT;
3909         }
3910     }
3911
3912   return condition;
3913 }
3914
3915 static GIOCondition
3916 update_condition (GSocket *socket)
3917 {
3918   GIOCondition res;
3919   g_mutex_lock (&socket->priv->win32_source_lock);
3920   res = update_condition_unlocked (socket);
3921   g_mutex_unlock (&socket->priv->win32_source_lock);
3922   return res;
3923 }
3924 #endif
3925
3926 typedef struct {
3927   GSource       source;
3928 #ifdef G_OS_WIN32
3929   GPollFD       pollfd;
3930 #else
3931   gpointer      fd_tag;
3932 #endif
3933   GSocket      *socket;
3934   GIOCondition  condition;
3935 } GSocketSource;
3936
3937 static gboolean
3938 socket_source_prepare (GSource *source,
3939                        gint    *timeout)
3940 {
3941   GSocketSource *socket_source = (GSocketSource *)source;
3942
3943   *timeout = -1;
3944
3945 #ifdef G_OS_WIN32
3946   if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
3947     return TRUE;
3948
3949   if (g_socket_is_closed (socket_source->socket))
3950     {
3951       g_source_remove_poll (source, &socket_source->pollfd);
3952       socket_source->pollfd.revents = G_IO_NVAL;
3953       return TRUE;
3954     }
3955
3956   return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3957 #else
3958   return g_socket_is_closed (socket_source->socket) && socket_source->fd_tag != NULL;
3959 #endif
3960 }
3961
3962 #ifdef G_OS_WIN32
3963 static gboolean
3964 socket_source_check_win32 (GSource *source)
3965 {
3966   int timeout;
3967
3968   return socket_source_prepare (source, &timeout);
3969 }
3970 #endif
3971
3972 static gboolean
3973 socket_source_dispatch (GSource     *source,
3974                         GSourceFunc  callback,
3975                         gpointer     user_data)
3976 {
3977   GSocketSourceFunc func = (GSocketSourceFunc)callback;
3978   GSocketSource *socket_source = (GSocketSource *)source;
3979   GSocket *socket = socket_source->socket;
3980   gint64 timeout;
3981   guint events;
3982   gboolean ret;
3983
3984 #ifdef G_OS_WIN32
3985   events = update_condition (socket_source->socket);
3986 #else
3987   if (g_socket_is_closed (socket_source->socket))
3988     {
3989       if (socket_source->fd_tag)
3990         g_source_remove_unix_fd (source, socket_source->fd_tag);
3991       socket_source->fd_tag = NULL;
3992       events = G_IO_NVAL;
3993     }
3994   else
3995     {
3996       events = g_source_query_unix_fd (source, socket_source->fd_tag);
3997     }
3998 #endif
3999
4000   timeout = g_source_get_ready_time (source);
4001   if (timeout >= 0 && timeout < g_source_get_time (source) &&
4002       !g_socket_is_closed (socket_source->socket))
4003     {
4004       socket->priv->timed_out = TRUE;
4005       events |= (G_IO_IN | G_IO_OUT);
4006     }
4007
4008   ret = (*func) (socket, events & socket_source->condition, user_data);
4009
4010   if (socket->priv->timeout && !g_socket_is_closed (socket_source->socket))
4011     g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4012   else
4013     g_source_set_ready_time (source, -1);
4014
4015   return ret;
4016 }
4017
4018 static void
4019 socket_source_finalize (GSource *source)
4020 {
4021   GSocketSource *socket_source = (GSocketSource *)source;
4022   GSocket *socket;
4023
4024   socket = socket_source->socket;
4025
4026 #ifdef G_OS_WIN32
4027   remove_condition_watch (socket, &socket_source->condition);
4028 #endif
4029
4030   g_object_unref (socket);
4031 }
4032
4033 static gboolean
4034 socket_source_closure_callback (GSocket      *socket,
4035                                 GIOCondition  condition,
4036                                 gpointer      data)
4037 {
4038   GClosure *closure = data;
4039
4040   GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
4041   GValue result_value = G_VALUE_INIT;
4042   gboolean result;
4043
4044   g_value_init (&result_value, G_TYPE_BOOLEAN);
4045
4046   g_value_init (&params[0], G_TYPE_SOCKET);
4047   g_value_set_object (&params[0], socket);
4048   g_value_init (&params[1], G_TYPE_IO_CONDITION);
4049   g_value_set_flags (&params[1], condition);
4050
4051   g_closure_invoke (closure, &result_value, 2, params, NULL);
4052
4053   result = g_value_get_boolean (&result_value);
4054   g_value_unset (&result_value);
4055   g_value_unset (&params[0]);
4056   g_value_unset (&params[1]);
4057
4058   return result;
4059 }
4060
4061 static GSourceFuncs socket_source_funcs =
4062 {
4063   socket_source_prepare,
4064 #ifdef G_OS_WIN32
4065   socket_source_check_win32,
4066 #else
4067   NULL,
4068 #endif
4069   socket_source_dispatch,
4070   socket_source_finalize,
4071   (GSourceFunc)socket_source_closure_callback,
4072 };
4073
4074 static GSource *
4075 socket_source_new (GSocket      *socket,
4076                    GIOCondition  condition,
4077                    GCancellable *cancellable)
4078 {
4079   GSource *source;
4080   GSocketSource *socket_source;
4081
4082 #ifdef G_OS_WIN32
4083   ensure_event (socket);
4084
4085   if (socket->priv->event == WSA_INVALID_EVENT)
4086     {
4087       g_warning ("Failed to create WSAEvent");
4088       return g_source_new (&broken_funcs, sizeof (GSource));
4089     }
4090 #endif
4091
4092   if (!check_socket (socket, NULL))
4093     {
4094       g_warning ("Socket check failed");
4095       return g_source_new (&broken_funcs, sizeof (GSource));
4096     }
4097
4098   condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
4099
4100   source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
4101   g_source_set_name (source, "GSocket");
4102   socket_source = (GSocketSource *)source;
4103
4104   socket_source->socket = g_object_ref (socket);
4105   socket_source->condition = condition;
4106
4107   if (cancellable)
4108     {
4109       GSource *cancellable_source;
4110
4111       cancellable_source = g_cancellable_source_new (cancellable);
4112       g_source_add_child_source (source, cancellable_source);
4113       g_source_set_dummy_callback (cancellable_source);
4114       g_source_unref (cancellable_source);
4115     }
4116
4117 #ifdef G_OS_WIN32
4118   add_condition_watch (socket, &socket_source->condition);
4119   socket_source->pollfd.fd = (gintptr) socket->priv->event;
4120   socket_source->pollfd.events = condition;
4121   socket_source->pollfd.revents = 0;
4122   g_source_add_poll (source, &socket_source->pollfd);
4123 #else
4124   socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
4125 #endif
4126
4127   if (socket->priv->timeout)
4128     g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4129   else
4130     g_source_set_ready_time (source, -1);
4131
4132   return source;
4133 }
4134
4135 /**
4136  * g_socket_create_source: (skip)
4137  * @socket: a #GSocket
4138  * @condition: a #GIOCondition mask to monitor
4139  * @cancellable: (nullable): a %GCancellable or %NULL
4140  *
4141  * Creates a #GSource that can be attached to a %GMainContext to monitor
4142  * for the availability of the specified @condition on the socket. The #GSource
4143  * keeps a reference to the @socket.
4144  *
4145  * The callback on the source is of the #GSocketSourceFunc type.
4146  *
4147  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
4148  * these conditions will always be reported output if they are true.
4149  *
4150  * @cancellable if not %NULL can be used to cancel the source, which will
4151  * cause the source to trigger, reporting the current condition (which
4152  * is likely 0 unless cancellation happened at the same time as a
4153  * condition change). You can check for this in the callback using
4154  * g_cancellable_is_cancelled().
4155  *
4156  * If @socket has a timeout set, and it is reached before @condition
4157  * occurs, the source will then trigger anyway, reporting %G_IO_IN or
4158  * %G_IO_OUT depending on @condition. However, @socket will have been
4159  * marked as having had a timeout, and so the next #GSocket I/O method
4160  * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
4161  *
4162  * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
4163  *
4164  * Since: 2.22
4165  */
4166 GSource *
4167 g_socket_create_source (GSocket      *socket,
4168                         GIOCondition  condition,
4169                         GCancellable *cancellable)
4170 {
4171   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
4172
4173   return socket_source_new (socket, condition, cancellable);
4174 }
4175
4176 /**
4177  * g_socket_condition_check:
4178  * @socket: a #GSocket
4179  * @condition: a #GIOCondition mask to check
4180  *
4181  * Checks on the readiness of @socket to perform operations.
4182  * The operations specified in @condition are checked for and masked
4183  * against the currently-satisfied conditions on @socket. The result
4184  * is returned.
4185  *
4186  * Note that on Windows, it is possible for an operation to return
4187  * %G_IO_ERROR_WOULD_BLOCK even immediately after
4188  * g_socket_condition_check() has claimed that the socket is ready for
4189  * writing. Rather than calling g_socket_condition_check() and then
4190  * writing to the socket if it succeeds, it is generally better to
4191  * simply try writing to the socket right away, and try again later if
4192  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
4193  *
4194  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
4195  * these conditions will always be set in the output if they are true.
4196  *
4197  * This call never blocks.
4198  *
4199  * Returns: the @GIOCondition mask of the current state
4200  *
4201  * Since: 2.22
4202  */
4203 GIOCondition
4204 g_socket_condition_check (GSocket      *socket,
4205                           GIOCondition  condition)
4206 {
4207   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
4208
4209   if (!check_socket (socket, NULL))
4210     return 0;
4211
4212 #ifdef G_OS_WIN32
4213   {
4214     GIOCondition current_condition;
4215
4216     condition |= G_IO_ERR | G_IO_HUP;
4217
4218     add_condition_watch (socket, &condition);
4219     current_condition = update_condition (socket);
4220     remove_condition_watch (socket, &condition);
4221     return condition & current_condition;
4222   }
4223 #else
4224   {
4225     GPollFD poll_fd;
4226     gint result;
4227     poll_fd.fd = socket->priv->fd;
4228     poll_fd.events = condition;
4229     poll_fd.revents = 0;
4230
4231     do
4232       result = g_poll (&poll_fd, 1, 0);
4233     while (result == -1 && get_socket_errno () == EINTR);
4234
4235     return poll_fd.revents;
4236   }
4237 #endif
4238 }
4239
4240 /**
4241  * g_socket_condition_wait:
4242  * @socket: a #GSocket
4243  * @condition: a #GIOCondition mask to wait for
4244  * @cancellable: (nullable): a #GCancellable, or %NULL
4245  * @error: a #GError pointer, or %NULL
4246  *
4247  * Waits for @condition to become true on @socket. When the condition
4248  * is met, %TRUE is returned.
4249  *
4250  * If @cancellable is cancelled before the condition is met, or if the
4251  * socket has a timeout set and it is reached before the condition is
4252  * met, then %FALSE is returned and @error, if non-%NULL, is set to
4253  * the appropriate value (%G_IO_ERROR_CANCELLED or
4254  * %G_IO_ERROR_TIMED_OUT).
4255  *
4256  * See also g_socket_condition_timed_wait().
4257  *
4258  * Returns: %TRUE if the condition was met, %FALSE otherwise
4259  *
4260  * Since: 2.22
4261  */
4262 gboolean
4263 g_socket_condition_wait (GSocket       *socket,
4264                          GIOCondition   condition,
4265                          GCancellable  *cancellable,
4266                          GError       **error)
4267 {
4268   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4269
4270   return g_socket_condition_timed_wait (socket, condition, -1,
4271                                         cancellable, error);
4272 }
4273
4274 /**
4275  * g_socket_condition_timed_wait:
4276  * @socket: a #GSocket
4277  * @condition: a #GIOCondition mask to wait for
4278  * @timeout_us: the maximum time (in microseconds) to wait, or -1
4279  * @cancellable: (nullable): a #GCancellable, or %NULL
4280  * @error: a #GError pointer, or %NULL
4281  *
4282  * Waits for up to @timeout_us microseconds for @condition to become true
4283  * on @socket. If the condition is met, %TRUE is returned.
4284  *
4285  * If @cancellable is cancelled before the condition is met, or if
4286  * @timeout_us (or the socket's #GSocket:timeout) is reached before the
4287  * condition is met, then %FALSE is returned and @error, if non-%NULL,
4288  * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4289  * %G_IO_ERROR_TIMED_OUT).
4290  *
4291  * If you don't want a timeout, use g_socket_condition_wait().
4292  * (Alternatively, you can pass -1 for @timeout_us.)
4293  *
4294  * Note that although @timeout_us is in microseconds for consistency with
4295  * other GLib APIs, this function actually only has millisecond
4296  * resolution, and the behavior is undefined if @timeout_us is not an
4297  * exact number of milliseconds.
4298  *
4299  * Returns: %TRUE if the condition was met, %FALSE otherwise
4300  *
4301  * Since: 2.32
4302  */
4303 gboolean
4304 g_socket_condition_timed_wait (GSocket       *socket,
4305                                GIOCondition   condition,
4306                                gint64         timeout_us,
4307                                GCancellable  *cancellable,
4308                                GError       **error)
4309 {
4310   gint64 start_time;
4311   gint64 timeout_ms;
4312
4313   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4314
4315   if (!check_socket (socket, error))
4316     return FALSE;
4317
4318   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4319     return FALSE;
4320
4321   if (socket->priv->timeout &&
4322       (timeout_us < 0 || socket->priv->timeout < timeout_us / G_USEC_PER_SEC))
4323     timeout_ms = (gint64) socket->priv->timeout * 1000;
4324   else if (timeout_us != -1)
4325     timeout_ms = timeout_us / 1000;
4326   else
4327     timeout_ms = -1;
4328
4329   start_time = g_get_monotonic_time ();
4330
4331 #ifdef G_OS_WIN32
4332   {
4333     GIOCondition current_condition;
4334     WSAEVENT events[2];
4335     DWORD res;
4336     GPollFD cancel_fd;
4337     int num_events;
4338
4339     /* Always check these */
4340     condition |=  G_IO_ERR | G_IO_HUP;
4341
4342     add_condition_watch (socket, &condition);
4343
4344     num_events = 0;
4345     events[num_events++] = socket->priv->event;
4346
4347     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
4348       events[num_events++] = (WSAEVENT)cancel_fd.fd;
4349
4350     if (timeout_ms == -1)
4351       timeout_ms = WSA_INFINITE;
4352
4353     g_mutex_lock (&socket->priv->win32_source_lock);
4354     current_condition = update_condition_unlocked (socket);
4355     while ((condition & current_condition) == 0)
4356       {
4357         if (!socket->priv->waiting)
4358           {
4359             socket->priv->waiting = TRUE;
4360             socket->priv->waiting_result = 0;
4361             g_mutex_unlock (&socket->priv->win32_source_lock);
4362
4363             res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout_ms, FALSE);
4364
4365             g_mutex_lock (&socket->priv->win32_source_lock);
4366             socket->priv->waiting = FALSE;
4367             socket->priv->waiting_result = res;
4368             g_cond_broadcast (&socket->priv->win32_source_cond);
4369           }
4370         else
4371           {
4372             if (timeout_ms != WSA_INFINITE)
4373               {
4374                 if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout_ms))
4375                   {
4376                     res = WSA_WAIT_TIMEOUT;
4377                     break;
4378                   }
4379                 else
4380                   {
4381                     res = socket->priv->waiting_result;
4382                   }
4383               }
4384             else
4385               {
4386                 g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
4387                 res = socket->priv->waiting_result;
4388               }
4389           }
4390
4391         if (res == WSA_WAIT_FAILED)
4392           {
4393             int errsv = get_socket_errno ();
4394
4395             g_set_error (error, G_IO_ERROR,
4396                          socket_io_error_from_errno (errsv),
4397                          _("Waiting for socket condition: %s"),
4398                          socket_strerror (errsv));
4399             break;
4400           }
4401         else if (res == WSA_WAIT_TIMEOUT)
4402           {
4403             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4404                                  _("Socket I/O timed out"));
4405             break;
4406           }
4407
4408         if (g_cancellable_set_error_if_cancelled (cancellable, error))
4409           break;
4410
4411         current_condition = update_condition_unlocked (socket);
4412
4413         if (timeout_ms != WSA_INFINITE)
4414           {
4415             timeout_ms -= (g_get_monotonic_time () - start_time) * 1000;
4416             if (timeout_ms < 0)
4417               timeout_ms = 0;
4418           }
4419       }
4420     g_mutex_unlock (&socket->priv->win32_source_lock);
4421     remove_condition_watch (socket, &condition);
4422     if (num_events > 1)
4423       g_cancellable_release_fd (cancellable);
4424
4425     return (condition & current_condition) != 0;
4426   }
4427 #else
4428   {
4429     GPollFD poll_fd[2];
4430     gint result;
4431     gint num;
4432
4433     poll_fd[0].fd = socket->priv->fd;
4434     poll_fd[0].events = condition;
4435     num = 1;
4436
4437     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
4438       num++;
4439
4440     while (TRUE)
4441       {
4442         int errsv;
4443         result = g_poll (poll_fd, num, timeout_ms);
4444         errsv = errno;
4445         if (result != -1 || errsv != EINTR)
4446           break;
4447
4448         if (timeout_ms != -1)
4449           {
4450             timeout_ms -= (g_get_monotonic_time () - start_time) / 1000;
4451             if (timeout_ms < 0)
4452               timeout_ms = 0;
4453           }
4454       }
4455     
4456     if (num > 1)
4457       g_cancellable_release_fd (cancellable);
4458
4459     if (result == 0)
4460       {
4461         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4462                              _("Socket I/O timed out"));
4463         return FALSE;
4464       }
4465
4466     return !g_cancellable_set_error_if_cancelled (cancellable, error);
4467   }
4468   #endif
4469 }
4470
4471 #ifndef G_OS_WIN32
4472
4473 /* Unfortunately these have to be macros rather than inline functions due to
4474  * using alloca(). */
4475 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4476 G_STMT_START { \
4477   const GOutputMessage  *_message = (message); \
4478   const GOutputMessage *_prev_message = (prev_message); \
4479   struct msghdr *_msg = (msg); \
4480   const struct msghdr *_prev_msg = (prev_msg); \
4481   GError **_error = (error); \
4482  \
4483   _msg->msg_flags = 0; \
4484  \
4485   /* name */ \
4486   if (_prev_message != NULL && _prev_message->address == _message->address) \
4487     { \
4488       _msg->msg_name = _prev_msg->msg_name; \
4489       _msg->msg_namelen = _prev_msg->msg_namelen; \
4490     } \
4491   else if (_message->address != NULL) \
4492     { \
4493       _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4494       _msg->msg_name = g_alloca (_msg->msg_namelen); \
4495       if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4496                                        _msg->msg_namelen, _error)) \
4497         break; \
4498     } \
4499   else \
4500     { \
4501       _msg->msg_name = NULL; \
4502       _msg->msg_namelen = 0; \
4503     } \
4504  \
4505   /* iov */ \
4506   { \
4507     /* this entire expression will be evaluated at compile time */ \
4508     if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4509         sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4510         G_STRUCT_OFFSET (struct iovec, iov_base) == \
4511         G_STRUCT_OFFSET (GOutputVector, buffer) && \
4512         sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4513         G_STRUCT_OFFSET (struct iovec, iov_len) == \
4514         G_STRUCT_OFFSET (GOutputVector, size)) \
4515       /* ABI is compatible */ \
4516       { \
4517         _msg->msg_iov = (struct iovec *) _message->vectors; \
4518         _msg->msg_iovlen = _message->num_vectors; \
4519       } \
4520     else \
4521       /* ABI is incompatible */ \
4522       { \
4523         gint i; \
4524  \
4525         _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4526         for (i = 0; i < _message->num_vectors; i++) \
4527           { \
4528             _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4529             _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4530           } \
4531         _msg->msg_iovlen = _message->num_vectors; \
4532       } \
4533   } \
4534  \
4535   /* control */ \
4536   { \
4537     struct cmsghdr *cmsg; \
4538     gint i; \
4539  \
4540     _msg->msg_controllen = 0; \
4541     for (i = 0; i < _message->num_control_messages; i++) \
4542       _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4543  \
4544     if (_msg->msg_controllen == 0) \
4545       _msg->msg_control = NULL; \
4546     else \
4547       { \
4548         _msg->msg_control = g_alloca (_msg->msg_controllen); \
4549         memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4550       } \
4551  \
4552     cmsg = CMSG_FIRSTHDR (_msg); \
4553     for (i = 0; i < _message->num_control_messages; i++) \
4554       { \
4555         cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4556         cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4557         cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4558         g_socket_control_message_serialize (_message->control_messages[i], \
4559                                             CMSG_DATA (cmsg)); \
4560         cmsg = CMSG_NXTHDR (_msg, cmsg); \
4561       } \
4562     g_assert (cmsg == NULL); \
4563   } \
4564 } G_STMT_END
4565
4566 #define input_message_to_msghdr(message, msg) \
4567 G_STMT_START { \
4568   const GInputMessage  *_message = (message); \
4569   struct msghdr *_msg = (msg); \
4570  \
4571   /* name */ \
4572   if (_message->address) \
4573     { \
4574       _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4575       _msg->msg_name = g_alloca (_msg->msg_namelen); \
4576     } \
4577   else \
4578     { \
4579       _msg->msg_name = NULL; \
4580       _msg->msg_namelen = 0; \
4581     } \
4582  \
4583   /* iov */ \
4584   /* this entire expression will be evaluated at compile time */ \
4585   if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4586       sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4587       G_STRUCT_OFFSET (struct iovec, iov_base) == \
4588       G_STRUCT_OFFSET (GInputVector, buffer) && \
4589       sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4590       G_STRUCT_OFFSET (struct iovec, iov_len) == \
4591       G_STRUCT_OFFSET (GInputVector, size)) \
4592     /* ABI is compatible */ \
4593     { \
4594       _msg->msg_iov = (struct iovec *) _message->vectors; \
4595       _msg->msg_iovlen = _message->num_vectors; \
4596     } \
4597   else \
4598     /* ABI is incompatible */ \
4599     { \
4600       guint i; \
4601  \
4602       _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4603       for (i = 0; i < _message->num_vectors; i++) \
4604         { \
4605           _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4606           _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4607         } \
4608       _msg->msg_iovlen = _message->num_vectors; \
4609     } \
4610  \
4611   /* control */ \
4612   if (_message->control_messages == NULL) \
4613     { \
4614           _msg->msg_controllen = 0; \
4615           _msg->msg_control = NULL; \
4616     } \
4617   else \
4618     { \
4619       _msg->msg_controllen = 2048; \
4620       _msg->msg_control = g_alloca (_msg->msg_controllen); \
4621     } \
4622  \
4623   /* flags */ \
4624   _msg->msg_flags = _message->flags; \
4625 } G_STMT_END
4626
4627 static void
4628 input_message_from_msghdr (const struct msghdr  *msg,
4629                            GInputMessage        *message,
4630                            GSocket              *socket)
4631 {
4632   /* decode address */
4633   if (message->address != NULL)
4634     {
4635       *message->address = cache_recv_address (socket, msg->msg_name,
4636                                               msg->msg_namelen);
4637     }
4638
4639   /* decode control messages */
4640   {
4641     GPtrArray *my_messages = NULL;
4642     struct cmsghdr *cmsg;
4643
4644     if (msg->msg_controllen >= sizeof (struct cmsghdr))
4645       {
4646         g_assert (message->control_messages != NULL);
4647         for (cmsg = CMSG_FIRSTHDR (msg);
4648              cmsg != NULL;
4649              cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4650           {
4651             GSocketControlMessage *control_message;
4652
4653             control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4654                                                                     cmsg->cmsg_type,
4655                                                                     cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4656                                                                     CMSG_DATA (cmsg));
4657             if (control_message == NULL)
4658               /* We've already spewed about the problem in the
4659                  deserialization code, so just continue */
4660               continue;
4661
4662             if (my_messages == NULL)
4663               my_messages = g_ptr_array_new ();
4664             g_ptr_array_add (my_messages, control_message);
4665            }
4666       }
4667
4668     if (message->num_control_messages)
4669       *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4670
4671     if (message->control_messages)
4672       {
4673         if (my_messages == NULL)
4674           {
4675             *message->control_messages = NULL;
4676           }
4677         else
4678           {
4679             g_ptr_array_add (my_messages, NULL);
4680             *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4681           }
4682       }
4683     else
4684       {
4685         g_assert (my_messages == NULL);
4686       }
4687   }
4688
4689   /* capture the flags */
4690   message->flags = msg->msg_flags;
4691 }
4692 #endif
4693
4694 /**
4695  * g_socket_send_message:
4696  * @socket: a #GSocket
4697  * @address: (nullable): a #GSocketAddress, or %NULL
4698  * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4699  * @num_vectors: the number of elements in @vectors, or -1
4700  * @messages: (array length=num_messages) (nullable): a pointer to an
4701  *   array of #GSocketControlMessages, or %NULL.
4702  * @num_messages: number of elements in @messages, or -1.
4703  * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4704  *    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4705  * @cancellable: (nullable): a %GCancellable or %NULL
4706  * @error: #GError for error reporting, or %NULL to ignore.
4707  *
4708  * Send data to @address on @socket.  For sending multiple messages see
4709  * g_socket_send_messages(); for easier use, see
4710  * g_socket_send() and g_socket_send_to().
4711  *
4712  * If @address is %NULL then the message is sent to the default receiver
4713  * (set by g_socket_connect()).
4714  *
4715  * @vectors must point to an array of #GOutputVector structs and
4716  * @num_vectors must be the length of this array. (If @num_vectors is -1,
4717  * then @vectors is assumed to be terminated by a #GOutputVector with a
4718  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4719  * that the sent data will be gathered from. Using multiple
4720  * #GOutputVectors is more memory-efficient than manually copying
4721  * data from multiple sources into a single buffer, and more
4722  * network-efficient than making multiple calls to g_socket_send().
4723  *
4724  * @messages, if non-%NULL, is taken to point to an array of @num_messages
4725  * #GSocketControlMessage instances. These correspond to the control
4726  * messages to be sent on the socket.
4727  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4728  * array.
4729  *
4730  * @flags modify how the message is sent. The commonly available arguments
4731  * for this are available in the #GSocketMsgFlags enum, but the
4732  * values there are the same as the system values, and the flags
4733  * are passed in as-is, so you can pass in system-specific flags too.
4734  *
4735  * If the socket is in blocking mode the call will block until there is
4736  * space for the data in the socket queue. If there is no space available
4737  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4738  * will be returned. To be notified when space is available, wait for the
4739  * %G_IO_OUT condition. Note though that you may still receive
4740  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4741  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4742  * very common due to the way the underlying APIs work.)
4743  *
4744  * On error -1 is returned and @error is set accordingly.
4745  *
4746  * Returns: Number of bytes written (which may be less than @size), or -1
4747  * on error
4748  *
4749  * Since: 2.22
4750  */
4751 gssize
4752 g_socket_send_message (GSocket                *socket,
4753                        GSocketAddress         *address,
4754                        GOutputVector          *vectors,
4755                        gint                    num_vectors,
4756                        GSocketControlMessage **messages,
4757                        gint                    num_messages,
4758                        gint                    flags,
4759                        GCancellable           *cancellable,
4760                        GError                **error)
4761 {
4762   GPollableReturn res;
4763   gsize bytes_written = 0;
4764
4765   res = g_socket_send_message_with_timeout (socket, address,
4766                                             vectors, num_vectors,
4767                                             messages, num_messages, flags,
4768                                             socket->priv->blocking ? -1 : 0,
4769                                             &bytes_written,
4770                                             cancellable, error);
4771
4772   if (res == G_POLLABLE_RETURN_WOULD_BLOCK)
4773     {
4774 #ifndef G_OS_WIN32
4775       socket_set_error_lazy (error, EWOULDBLOCK, _("Error sending message: %s"));
4776 #else
4777       socket_set_error_lazy (error, WSAEWOULDBLOCK, _("Error sending message: %s"));
4778 #endif
4779     }
4780
4781   return res == G_POLLABLE_RETURN_OK ? bytes_written : -1;
4782 }
4783
4784 /**
4785  * g_socket_send_message_with_timeout:
4786  * @socket: a #GSocket
4787  * @address: (nullable): a #GSocketAddress, or %NULL
4788  * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4789  * @num_vectors: the number of elements in @vectors, or -1
4790  * @messages: (array length=num_messages) (nullable): a pointer to an
4791  *   array of #GSocketControlMessages, or %NULL.
4792  * @num_messages: number of elements in @messages, or -1.
4793  * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4794  *    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4795  * @timeout_us: the maximum time (in microseconds) to wait, or -1
4796  * @bytes_written: (out) (optional): location to store the number of bytes that were written to the socket
4797  * @cancellable: (nullable): a %GCancellable or %NULL
4798  * @error: #GError for error reporting, or %NULL to ignore.
4799  *
4800  * This behaves exactly the same as g_socket_send_message(), except that
4801  * the choice of timeout behavior is determined by the @timeout_us argument
4802  * rather than by @socket's properties.
4803  *
4804  * On error %G_POLLABLE_RETURN_FAILED is returned and @error is set accordingly, or
4805  * if the socket is currently not writable %G_POLLABLE_RETURN_WOULD_BLOCK is
4806  * returned. @bytes_written will contain 0 in both cases.
4807  *
4808  * Returns: %G_POLLABLE_RETURN_OK if all data was successfully written,
4809  * %G_POLLABLE_RETURN_WOULD_BLOCK if the socket is currently not writable, or
4810  * %G_POLLABLE_RETURN_FAILED if an error happened and @error is set.
4811  *
4812  * Since: 2.60
4813  */
4814 GPollableReturn
4815 g_socket_send_message_with_timeout (GSocket                *socket,
4816                                     GSocketAddress         *address,
4817                                     const GOutputVector    *vectors,
4818                                     gint                    num_vectors,
4819                                     GSocketControlMessage **messages,
4820                                     gint                    num_messages,
4821                                     gint                    flags,
4822                                     gint64                  timeout_us,
4823                                     gsize                  *bytes_written,
4824                                     GCancellable           *cancellable,
4825                                     GError                **error)
4826 {
4827   GOutputVector one_vector;
4828   char zero;
4829   gint64 start_time;
4830
4831   if (bytes_written)
4832     *bytes_written = 0;
4833
4834   g_return_val_if_fail (G_IS_SOCKET (socket), G_POLLABLE_RETURN_FAILED);
4835   g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), G_POLLABLE_RETURN_FAILED);
4836   g_return_val_if_fail (num_vectors == 0 || vectors != NULL, G_POLLABLE_RETURN_FAILED);
4837   g_return_val_if_fail (num_messages == 0 || messages != NULL, G_POLLABLE_RETURN_FAILED);
4838   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), G_POLLABLE_RETURN_FAILED);
4839   g_return_val_if_fail (error == NULL || *error == NULL, G_POLLABLE_RETURN_FAILED);
4840
4841   start_time = g_get_monotonic_time ();
4842
4843   if (!check_socket (socket, error))
4844     return G_POLLABLE_RETURN_FAILED;
4845
4846   if (!check_timeout (socket, error))
4847     return G_POLLABLE_RETURN_FAILED;
4848
4849   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4850     return G_POLLABLE_RETURN_FAILED;
4851
4852   if (num_vectors == -1)
4853     {
4854       for (num_vectors = 0;
4855            vectors[num_vectors].buffer != NULL;
4856            num_vectors++)
4857         ;
4858     }
4859
4860   if (num_messages == -1)
4861     {
4862       for (num_messages = 0;
4863            messages != NULL && messages[num_messages] != NULL;
4864            num_messages++)
4865         ;
4866     }
4867
4868   if (num_vectors == 0)
4869     {
4870       zero = '\0';
4871
4872       one_vector.buffer = &zero;
4873       one_vector.size = 1;
4874       num_vectors = 1;
4875       vectors = &one_vector;
4876     }
4877
4878 #ifndef G_OS_WIN32
4879   {
4880     GOutputMessage output_message;
4881     struct msghdr msg;
4882     gssize result;
4883     GError *child_error = NULL;
4884
4885     output_message.address = address;
4886     output_message.vectors = (GOutputVector *) vectors;
4887     output_message.num_vectors = num_vectors;
4888     output_message.bytes_sent = 0;
4889     output_message.control_messages = messages;
4890     output_message.num_control_messages = num_messages;
4891
4892     output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4893
4894     if (child_error != NULL)
4895       {
4896         g_propagate_error (error, child_error);
4897         return G_POLLABLE_RETURN_FAILED;
4898       }
4899
4900     while (1)
4901       {
4902         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4903         if (result < 0)
4904           {
4905             int errsv = get_socket_errno ();
4906
4907             if (errsv == EINTR)
4908               continue;
4909
4910             if (errsv == EWOULDBLOCK || errsv == EAGAIN)
4911               {
4912                 if (timeout_us != 0)
4913                   {
4914                     if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
4915                                            cancellable, error))
4916                       return G_POLLABLE_RETURN_FAILED;
4917
4918                     continue;
4919                   }
4920
4921                 return G_POLLABLE_RETURN_WOULD_BLOCK;
4922               }
4923
4924             socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4925             return G_POLLABLE_RETURN_FAILED;
4926           }
4927         break;
4928       }
4929
4930     if (bytes_written)
4931       *bytes_written = result;
4932
4933     return G_POLLABLE_RETURN_OK;
4934   }
4935 #else
4936   {
4937     struct sockaddr_storage addr;
4938     guint addrlen;
4939     DWORD bytes_sent;
4940     int result;
4941     WSABUF *bufs;
4942     gint i;
4943
4944     /* Win32 doesn't support control messages.
4945        Actually this is possible for raw and datagram sockets
4946        via WSASendMessage on Vista or later, but that doesn't
4947        seem very useful */
4948     if (num_messages != 0)
4949       {
4950         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4951                              _("GSocketControlMessage not supported on Windows"));
4952         return G_POLLABLE_RETURN_FAILED;
4953       }
4954
4955     /* iov */
4956     bufs = g_newa (WSABUF, num_vectors);
4957     for (i = 0; i < num_vectors; i++)
4958       {
4959         bufs[i].buf = (char *)vectors[i].buffer;
4960         bufs[i].len = (gulong)vectors[i].size;
4961       }
4962
4963     /* name */
4964     addrlen = 0; /* Avoid warning */
4965     if (address)
4966       {
4967         addrlen = g_socket_address_get_native_size (address);
4968         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
4969           return G_POLLABLE_RETURN_FAILED;
4970       }
4971
4972     while (1)
4973       {
4974         if (address)
4975           result = WSASendTo (socket->priv->fd,
4976                               bufs, num_vectors,
4977                               &bytes_sent, flags,
4978                               (const struct sockaddr *)&addr, addrlen,
4979                               NULL, NULL);
4980         else
4981           result = WSASend (socket->priv->fd,
4982                             bufs, num_vectors,
4983                             &bytes_sent, flags,
4984                             NULL, NULL);
4985
4986         if (result != 0)
4987           {
4988             int errsv = get_socket_errno ();
4989
4990             if (errsv == WSAEINTR)
4991               continue;
4992
4993             if (errsv == WSAEWOULDBLOCK)
4994               {
4995                 win32_unset_event_mask (socket, FD_WRITE);
4996
4997                 if (timeout_us != 0)
4998                   {
4999                     if (!block_on_timeout (socket, G_IO_OUT, timeout_us,
5000                                            start_time, cancellable, error))
5001                       return G_POLLABLE_RETURN_FAILED;
5002
5003                     continue;
5004                   }
5005
5006                 return G_POLLABLE_RETURN_WOULD_BLOCK;
5007               }
5008
5009             socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5010             return G_POLLABLE_RETURN_FAILED;
5011           }
5012         break;
5013       }
5014
5015     if (bytes_written)
5016       *bytes_written = bytes_sent;
5017     return G_POLLABLE_RETURN_OK;
5018   }
5019 #endif
5020 }
5021
5022 /**
5023  * g_socket_send_messages:
5024  * @socket: a #GSocket
5025  * @messages: (array length=num_messages): an array of #GOutputMessage structs
5026  * @num_messages: the number of elements in @messages
5027  * @flags: an int containing #GSocketMsgFlags flags, which may additionally
5028  *    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5029  * @cancellable: (nullable): a %GCancellable or %NULL
5030  * @error: #GError for error reporting, or %NULL to ignore.
5031  *
5032  * Send multiple data messages from @socket in one go.  This is the most
5033  * complicated and fully-featured version of this call. For easier use, see
5034  * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
5035  *
5036  * @messages must point to an array of #GOutputMessage structs and
5037  * @num_messages must be the length of this array. Each #GOutputMessage
5038  * contains an address to send the data to, and a pointer to an array of
5039  * #GOutputVector structs to describe the buffers that the data to be sent
5040  * for each message will be gathered from. Using multiple #GOutputVectors is
5041  * more memory-efficient than manually copying data from multiple sources
5042  * into a single buffer, and more network-efficient than making multiple
5043  * calls to g_socket_send(). Sending multiple messages in one go avoids the
5044  * overhead of making a lot of syscalls in scenarios where a lot of data
5045  * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
5046  * or where the same data needs to be sent to multiple recipients.
5047  *
5048  * @flags modify how the message is sent. The commonly available arguments
5049  * for this are available in the #GSocketMsgFlags enum, but the
5050  * values there are the same as the system values, and the flags
5051  * are passed in as-is, so you can pass in system-specific flags too.
5052  *
5053  * If the socket is in blocking mode the call will block until there is
5054  * space for all the data in the socket queue. If there is no space available
5055  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
5056  * will be returned if no data was written at all, otherwise the number of
5057  * messages sent will be returned. To be notified when space is available,
5058  * wait for the %G_IO_OUT condition. Note though that you may still receive
5059  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
5060  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
5061  * very common due to the way the underlying APIs work.)
5062  *
5063  * On error -1 is returned and @error is set accordingly. An error will only
5064  * be returned if zero messages could be sent; otherwise the number of messages
5065  * successfully sent before the error will be returned.
5066  *
5067  * Returns: number of messages sent, or -1 on error. Note that the number of
5068  *     messages sent may be smaller than @num_messages if the socket is
5069  *     non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
5070  *     in which case the caller may re-try to send the remaining messages.
5071  *
5072  * Since: 2.44
5073  */
5074 gint
5075 g_socket_send_messages (GSocket        *socket,
5076                         GOutputMessage *messages,
5077                         guint           num_messages,
5078                         gint            flags,
5079                         GCancellable   *cancellable,
5080                         GError        **error)
5081 {
5082   return g_socket_send_messages_with_timeout (socket, messages, num_messages,
5083                                               flags,
5084                                               socket->priv->blocking ? -1 : 0,
5085                                               cancellable, error);
5086 }
5087
5088 static gint
5089 g_socket_send_messages_with_timeout (GSocket        *socket,
5090                                      GOutputMessage *messages,
5091                                      guint           num_messages,
5092                                      gint            flags,
5093                                      gint64          timeout_us,
5094                                      GCancellable   *cancellable,
5095                                      GError        **error)
5096 {
5097   gint64 start_time;
5098
5099   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5100   g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5101   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
5102   g_return_val_if_fail (error == NULL || *error == NULL, -1);
5103
5104   start_time = g_get_monotonic_time ();
5105
5106   if (!check_socket (socket, error))
5107     return -1;
5108
5109   if (!check_timeout (socket, error))
5110     return -1;
5111
5112   if (g_cancellable_set_error_if_cancelled (cancellable, error))
5113     return -1;
5114
5115   if (num_messages == 0)
5116     return 0;
5117
5118 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
5119   {
5120     struct mmsghdr *msgvec;
5121     gint i, num_sent;
5122
5123     /* Clamp the number of vectors if more given than we can write in one go.
5124      * The caller has to handle short writes anyway.
5125      */
5126     if (num_messages > G_IOV_MAX)
5127       num_messages = G_IOV_MAX;
5128
5129     msgvec = g_newa (struct mmsghdr, num_messages);
5130
5131     for (i = 0; i < num_messages; ++i)
5132       {
5133         GOutputMessage *msg = &messages[i];
5134         struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5135         GError *child_error = NULL;
5136
5137         msgvec[i].msg_len = 0;
5138
5139         output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
5140                                   msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
5141                                   &child_error);
5142
5143         if (child_error != NULL)
5144           {
5145             g_propagate_error (error, child_error);
5146             return -1;
5147           }
5148       }
5149
5150     for (num_sent = 0; num_sent < num_messages;)
5151       {
5152         gint ret;
5153
5154         ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
5155                         flags | G_SOCKET_DEFAULT_SEND_FLAGS);
5156
5157         if (ret < 0)
5158           {
5159             int errsv = get_socket_errno ();
5160
5161             if (errsv == EINTR)
5162               continue;
5163
5164             if (timeout_us != 0 &&
5165                 (errsv == EWOULDBLOCK ||
5166                  errsv == EAGAIN))
5167               {
5168                 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
5169                                        cancellable, error))
5170                   {
5171                     if (num_sent > 0)
5172                       {
5173                         g_clear_error (error);
5174                         break;
5175                       }
5176
5177                     return -1;
5178                   }
5179
5180                 continue;
5181               }
5182
5183             /* If any messages were successfully sent, do not error. */
5184             if (num_sent > 0)
5185               break;
5186
5187             socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5188
5189             return -1;
5190           }
5191
5192         num_sent += ret;
5193       }
5194
5195     for (i = 0; i < num_sent; ++i)
5196       messages[i].bytes_sent = msgvec[i].msg_len;
5197
5198     return num_sent;
5199   }
5200 #else
5201   {
5202     gssize result;
5203     gint i;
5204     gint64 wait_timeout;
5205
5206     wait_timeout = timeout_us;
5207
5208     for (i = 0; i < num_messages; ++i)
5209       {
5210         GOutputMessage *msg = &messages[i];
5211         GError *msg_error = NULL;
5212         GPollableReturn pollable_result;
5213         gsize bytes_written = 0;
5214
5215         pollable_result = g_socket_send_message_with_timeout (socket, msg->address,
5216                                                               msg->vectors,
5217                                                               msg->num_vectors,
5218                                                               msg->control_messages,
5219                                                               msg->num_control_messages,
5220                                                               flags, wait_timeout,
5221                                                               &bytes_written,
5222                                                               cancellable, &msg_error);
5223
5224         if (pollable_result == G_POLLABLE_RETURN_WOULD_BLOCK)
5225           {
5226 #ifndef G_OS_WIN32
5227             socket_set_error_lazy (&msg_error, EWOULDBLOCK, _("Error sending message: %s"));
5228 #else
5229             socket_set_error_lazy (&msg_error, WSAEWOULDBLOCK, _("Error sending message: %s"));
5230 #endif
5231           }
5232
5233         result = pollable_result == G_POLLABLE_RETURN_OK ? bytes_written : -1;
5234
5235         /* check if we've timed out or how much time to wait at most */
5236         if (timeout_us > 0)
5237           {
5238             gint64 elapsed = g_get_monotonic_time () - start_time;
5239             wait_timeout = MAX (timeout_us - elapsed, 1);
5240           }
5241
5242         if (result < 0)
5243           {
5244             /* if we couldn't send all messages, just return how many we did
5245              * manage to send, provided we managed to send at least one */
5246             if (i > 0)
5247               {
5248                 g_error_free (msg_error);
5249                 return i;
5250               }
5251             else
5252               {
5253                 g_propagate_error (error, msg_error);
5254                 return -1;
5255               }
5256           }
5257
5258         msg->bytes_sent = result;
5259       }
5260
5261     return i;
5262   }
5263 #endif
5264 }
5265
5266 static GSocketAddress *
5267 cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len)
5268 {
5269   GSocketAddress *saddr;
5270   gint i;
5271   guint64 oldest_time = G_MAXUINT64;
5272   gint oldest_index = 0;
5273
5274   if (native_len == 0)
5275     return NULL;
5276
5277   saddr = NULL;
5278   for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
5279     {
5280       GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
5281       gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
5282       gsize tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
5283
5284       if (!tmp)
5285         continue;
5286
5287       if (tmp_native_len != native_len)
5288         continue;
5289
5290       if (memcmp (tmp_native, native, native_len) == 0)
5291         {
5292           saddr = g_object_ref (tmp);
5293           socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
5294           return saddr;
5295         }
5296
5297       if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
5298         {
5299           oldest_time = socket->priv->recv_addr_cache[i].last_used;
5300           oldest_index = i;
5301         }
5302     }
5303
5304   saddr = g_socket_address_new_from_native (native, native_len);
5305
5306   if (socket->priv->recv_addr_cache[oldest_index].addr)
5307     {
5308       g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
5309       g_free (socket->priv->recv_addr_cache[oldest_index].native);
5310     }
5311
5312   socket->priv->recv_addr_cache[oldest_index].native = g_memdup2 (native, native_len);
5313   socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
5314   socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
5315   socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
5316
5317   return saddr;
5318 }
5319
5320 static gssize
5321 g_socket_receive_message_with_timeout (GSocket                 *socket,
5322                                        GSocketAddress         **address,
5323                                        GInputVector            *vectors,
5324                                        gint                     num_vectors,
5325                                        GSocketControlMessage ***messages,
5326                                        gint                    *num_messages,
5327                                        gint                    *flags,
5328                                        gint64                   timeout_us,
5329                                        GCancellable            *cancellable,
5330                                        GError                 **error)
5331 {
5332   GInputVector one_vector;
5333   char one_byte;
5334   gint64 start_time;
5335
5336   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5337
5338   start_time = g_get_monotonic_time ();
5339
5340   if (!check_socket (socket, error))
5341     return -1;
5342
5343   if (!check_timeout (socket, error))
5344     return -1;
5345
5346   if (g_cancellable_set_error_if_cancelled (cancellable, error))
5347     return -1;
5348
5349   if (num_vectors == -1)
5350     {
5351       for (num_vectors = 0;
5352            vectors[num_vectors].buffer != NULL;
5353            num_vectors++)
5354         ;
5355     }
5356
5357   if (num_vectors == 0)
5358     {
5359       one_vector.buffer = &one_byte;
5360       one_vector.size = 1;
5361       num_vectors = 1;
5362       vectors = &one_vector;
5363     }
5364
5365 #ifndef G_OS_WIN32
5366   {
5367     GInputMessage input_message;
5368     struct msghdr msg;
5369     gssize result;
5370
5371     input_message.address = address;
5372     input_message.vectors = vectors;
5373     input_message.num_vectors = num_vectors;
5374     input_message.bytes_received = 0;
5375     input_message.flags = (flags != NULL) ? *flags : 0;
5376     input_message.control_messages = messages;
5377     input_message.num_control_messages = (guint *) num_messages;
5378
5379     /* We always set the close-on-exec flag so we don't leak file
5380      * descriptors into child processes.  Note that gunixfdmessage.c
5381      * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5382      */
5383 #ifdef MSG_CMSG_CLOEXEC
5384     input_message.flags |= MSG_CMSG_CLOEXEC;
5385 #endif
5386
5387     input_message_to_msghdr (&input_message, &msg);
5388
5389     /* do it */
5390     while (1)
5391       {
5392         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5393 #ifdef MSG_CMSG_CLOEXEC 
5394         if (result < 0 && get_socket_errno () == EINVAL)
5395           {
5396             /* We must be running on an old kernel.  Call without the flag. */
5397             msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
5398             result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5399           }
5400 #endif
5401
5402         if (result < 0)
5403           {
5404             int errsv = get_socket_errno ();
5405
5406             if (errsv == EINTR)
5407               continue;
5408
5409             if (timeout_us != 0 &&
5410                 (errsv == EWOULDBLOCK ||
5411                  errsv == EAGAIN))
5412               {
5413                 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5414                                        cancellable, error))
5415                   return -1;
5416
5417                 continue;
5418               }
5419
5420             socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5421             return -1;
5422           }
5423         break;
5424       }
5425
5426     input_message_from_msghdr (&msg, &input_message, socket);
5427
5428     if (flags != NULL)
5429       *flags = input_message.flags;
5430
5431     return result;
5432   }
5433 #else
5434   {
5435     struct sockaddr_storage addr;
5436     int addrlen;
5437     DWORD bytes_received;
5438     DWORD win_flags;
5439     int result;
5440     WSABUF *bufs;
5441     gint i;
5442
5443     /* iov */
5444     bufs = g_newa (WSABUF, num_vectors);
5445     for (i = 0; i < num_vectors; i++)
5446       {
5447         bufs[i].buf = (char *)vectors[i].buffer;
5448         bufs[i].len = (gulong)vectors[i].size;
5449       }
5450
5451     /* flags */
5452     if (flags != NULL)
5453       win_flags = *flags;
5454     else
5455       win_flags = 0;
5456
5457     /* do it */
5458     while (1)
5459       {
5460         /* addrlen has to be of type int because that’s how WSARecvFrom() is defined */
5461         G_STATIC_ASSERT (sizeof addr <= G_MAXINT);
5462
5463         addrlen = sizeof addr;
5464         if (address)
5465           result = WSARecvFrom (socket->priv->fd,
5466                                 bufs, num_vectors,
5467                                 &bytes_received, &win_flags,
5468                                 (struct sockaddr *)&addr, &addrlen,
5469                                 NULL, NULL);
5470         else
5471           result = WSARecv (socket->priv->fd,
5472                             bufs, num_vectors,
5473                             &bytes_received, &win_flags,
5474                             NULL, NULL);
5475         if (result != 0)
5476           {
5477             int errsv = get_socket_errno ();
5478
5479             if (errsv == WSAEINTR)
5480               continue;
5481
5482             win32_unset_event_mask (socket, FD_READ);
5483
5484             if (errsv == WSAEWOULDBLOCK)
5485               {
5486                 if (timeout_us != 0)
5487                   {
5488                     if (!block_on_timeout (socket, G_IO_IN, timeout_us,
5489                                            start_time, cancellable, error))
5490                       return -1;
5491
5492                     continue;
5493                   }
5494               }
5495
5496             socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5497             return -1;
5498           }
5499         win32_unset_event_mask (socket, FD_READ);
5500         break;
5501       }
5502
5503     /* decode address */
5504     if (address != NULL)
5505       {
5506         *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
5507       }
5508
5509     /* capture the flags */
5510     if (flags != NULL)
5511       *flags = win_flags;
5512
5513     if (messages != NULL)
5514       *messages = NULL;
5515     if (num_messages != NULL)
5516       *num_messages = 0;
5517
5518     return bytes_received;
5519   }
5520 #endif
5521 }
5522
5523 /**
5524  * g_socket_receive_messages:
5525  * @socket: a #GSocket
5526  * @messages: (array length=num_messages): an array of #GInputMessage structs
5527  * @num_messages: the number of elements in @messages
5528  * @flags: an int containing #GSocketMsgFlags flags for the overall operation,
5529  *    which may additionally contain
5530  *    [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5531  * @cancellable: (nullable): a %GCancellable or %NULL
5532  * @error: #GError for error reporting, or %NULL to ignore
5533  *
5534  * Receive multiple data messages from @socket in one go.  This is the most
5535  * complicated and fully-featured version of this call. For easier use, see
5536  * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5537  *
5538  * @messages must point to an array of #GInputMessage structs and
5539  * @num_messages must be the length of this array. Each #GInputMessage
5540  * contains a pointer to an array of #GInputVector structs describing the
5541  * buffers that the data received in each message will be written to. Using
5542  * multiple #GInputVectors is more memory-efficient than manually copying data
5543  * out of a single buffer to multiple sources, and more system-call-efficient
5544  * than making multiple calls to g_socket_receive(), such as in scenarios where
5545  * a lot of data packets need to be received (e.g. high-bandwidth video
5546  * streaming over RTP/UDP).
5547  *
5548  * @flags modify how all messages are received. The commonly available
5549  * arguments for this are available in the #GSocketMsgFlags enum, but the
5550  * values there are the same as the system values, and the flags
5551  * are passed in as-is, so you can pass in system-specific flags too. These
5552  * flags affect the overall receive operation. Flags affecting individual
5553  * messages are returned in #GInputMessage.flags.
5554  *
5555  * The other members of #GInputMessage are treated as described in its
5556  * documentation.
5557  *
5558  * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5559  * been received, or the end of the stream is reached.
5560  *
5561  * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5562  * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5563  * operating system to be received.
5564  *
5565  * In blocking mode, if #GSocket:timeout is positive and is reached before any
5566  * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5567  * @num_messages are returned. (Note: This is effectively the
5568  * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5569  *
5570  * To be notified when messages are available, wait for the
5571  * %G_IO_IN condition. Note though that you may still receive
5572  * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5573  * previously notified of a %G_IO_IN condition.
5574  *
5575  * If the remote peer closes the connection, any messages queued in the
5576  * operating system will be returned, and subsequent calls to
5577  * g_socket_receive_messages() will return 0 (with no error set).
5578  *
5579  * On error -1 is returned and @error is set accordingly. An error will only
5580  * be returned if zero messages could be received; otherwise the number of
5581  * messages successfully received before the error will be returned.
5582  *
5583  * Returns: number of messages received, or -1 on error. Note that the number
5584  *     of messages received may be smaller than @num_messages if in non-blocking
5585  *     mode, if the peer closed the connection, or if @num_messages
5586  *     was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5587  *     to receive the remaining messages.
5588  *
5589  * Since: 2.48
5590  */
5591 gint
5592 g_socket_receive_messages (GSocket        *socket,
5593                            GInputMessage  *messages,
5594                            guint           num_messages,
5595                            gint            flags,
5596                            GCancellable   *cancellable,
5597                            GError        **error)
5598 {
5599   if (!check_socket (socket, error) ||
5600       !check_timeout (socket, error))
5601     return -1;
5602
5603   return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5604                                                  flags,
5605                                                  socket->priv->blocking ? -1 : 0,
5606                                                  cancellable, error);
5607 }
5608
5609 static gint
5610 g_socket_receive_messages_with_timeout (GSocket        *socket,
5611                                         GInputMessage  *messages,
5612                                         guint           num_messages,
5613                                         gint            flags,
5614                                         gint64          timeout_us,
5615                                         GCancellable   *cancellable,
5616                                         GError        **error)
5617 {
5618   gint64 start_time;
5619
5620   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5621   g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5622   g_return_val_if_fail (cancellable == NULL ||
5623                         G_IS_CANCELLABLE (cancellable), -1);
5624   g_return_val_if_fail (error == NULL || *error == NULL, -1);
5625
5626   start_time = g_get_monotonic_time ();
5627
5628   if (!check_socket (socket, error))
5629     return -1;
5630
5631   if (!check_timeout (socket, error))
5632     return -1;
5633
5634   if (g_cancellable_set_error_if_cancelled (cancellable, error))
5635     return -1;
5636
5637   if (num_messages == 0)
5638     return 0;
5639
5640 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5641   {
5642     struct mmsghdr *msgvec;
5643     guint i, num_received;
5644
5645     /* Clamp the number of vectors if more given than we can write in one go.
5646      * The caller has to handle short writes anyway.
5647      */
5648     if (num_messages > G_IOV_MAX)
5649       num_messages = G_IOV_MAX;
5650
5651     msgvec = g_newa (struct mmsghdr, num_messages);
5652
5653     for (i = 0; i < num_messages; ++i)
5654       {
5655         GInputMessage *msg = &messages[i];
5656         struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5657
5658         input_message_to_msghdr (msg, msg_hdr);
5659         msgvec[i].msg_len = 0;
5660       }
5661
5662     /* We always set the close-on-exec flag so we don't leak file
5663      * descriptors into child processes.  Note that gunixfdmessage.c
5664      * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5665      */
5666 #ifdef MSG_CMSG_CLOEXEC
5667     flags |= MSG_CMSG_CLOEXEC;
5668 #endif
5669
5670     for (num_received = 0; num_received < num_messages;)
5671       {
5672         gint ret;
5673
5674         /* We operate in non-blocking mode and handle the timeout ourselves. */
5675         ret = recvmmsg (socket->priv->fd,
5676                         msgvec + num_received,
5677                         num_messages - num_received,
5678                         flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5679 #ifdef MSG_CMSG_CLOEXEC
5680         if (ret < 0 && get_socket_errno () == EINVAL)
5681           {
5682             /* We must be running on an old kernel. Call without the flag. */
5683             flags &= ~(MSG_CMSG_CLOEXEC);
5684             ret = recvmmsg (socket->priv->fd,
5685                             msgvec + num_received,
5686                             num_messages - num_received,
5687                             flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5688           }
5689 #endif
5690
5691         if (ret < 0)
5692           {
5693             int errsv = get_socket_errno ();
5694
5695             if (errsv == EINTR)
5696               continue;
5697
5698             if (timeout_us != 0 &&
5699                 (errsv == EWOULDBLOCK ||
5700                  errsv == EAGAIN))
5701               {
5702                 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5703                                        cancellable, error))
5704                   {
5705                     if (num_received > 0)
5706                       {
5707                         g_clear_error (error);
5708                         break;
5709                       }
5710
5711                     return -1;
5712                   }
5713
5714                 continue;
5715               }
5716
5717             /* If any messages were successfully received, do not error. */
5718             if (num_received > 0)
5719               break;
5720
5721             socket_set_error_lazy (error, errsv,
5722                                    _("Error receiving message: %s"));
5723
5724             return -1;
5725           }
5726         else if (ret == 0)
5727           {
5728             /* EOS. */
5729             break;
5730           }
5731
5732         num_received += ret;
5733       }
5734
5735     for (i = 0; i < num_received; ++i)
5736       {
5737         input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5738         messages[i].bytes_received = msgvec[i].msg_len;
5739       }
5740
5741     return num_received;
5742   }
5743 #else
5744   {
5745     guint i;
5746     gint64 wait_timeout;
5747
5748     wait_timeout = timeout_us;
5749
5750     for (i = 0; i < num_messages; i++)
5751       {
5752         GInputMessage *msg = &messages[i];
5753         gssize len;
5754         GError *msg_error = NULL;
5755
5756         msg->flags = flags;  /* in-out parameter */
5757
5758         len = g_socket_receive_message_with_timeout (socket,
5759                                                      msg->address,
5760                                                      msg->vectors,
5761                                                      msg->num_vectors,
5762                                                      msg->control_messages,
5763                                                      (gint *) msg->num_control_messages,
5764                                                      &msg->flags,
5765                                                      wait_timeout,
5766                                                      cancellable,
5767                                                      &msg_error);
5768
5769         /* check if we've timed out or how much time to wait at most */
5770         if (timeout_us > 0)
5771           {
5772             gint64 elapsed = g_get_monotonic_time () - start_time;
5773             wait_timeout = MAX (timeout_us - elapsed, 1);
5774           }
5775
5776         if (len >= 0)
5777           msg->bytes_received = len;
5778
5779         if (i != 0 &&
5780             (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5781              g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5782           {
5783             g_clear_error (&msg_error);
5784             break;
5785           }
5786
5787         if (msg_error != NULL)
5788           {
5789             g_propagate_error (error, msg_error);
5790             return -1;
5791           }
5792
5793         if (len == 0)
5794           break;
5795       }
5796
5797     return i;
5798   }
5799 #endif
5800 }
5801
5802 /**
5803  * g_socket_receive_message:
5804  * @socket: a #GSocket
5805  * @address: (out) (optional): a pointer to a #GSocketAddress
5806  *     pointer, or %NULL
5807  * @vectors: (array length=num_vectors): an array of #GInputVector structs
5808  * @num_vectors: the number of elements in @vectors, or -1
5809  * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5810  *    which may be filled with an array of #GSocketControlMessages, or %NULL
5811  * @num_messages: (out): a pointer which will be filled with the number of
5812  *    elements in @messages, or %NULL
5813  * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags,
5814  *    which may additionally contain
5815  *    [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5816  * @cancellable: a %GCancellable or %NULL
5817  * @error: a #GError pointer, or %NULL
5818  *
5819  * Receive data from a socket.  For receiving multiple messages, see
5820  * g_socket_receive_messages(); for easier use, see
5821  * g_socket_receive() and g_socket_receive_from().
5822  *
5823  * If @address is non-%NULL then @address will be set equal to the
5824  * source address of the received packet.
5825  * @address is owned by the caller.
5826  *
5827  * @vector must point to an array of #GInputVector structs and
5828  * @num_vectors must be the length of this array.  These structs
5829  * describe the buffers that received data will be scattered into.
5830  * If @num_vectors is -1, then @vectors is assumed to be terminated
5831  * by a #GInputVector with a %NULL buffer pointer.
5832  *
5833  * As a special case, if @num_vectors is 0 (in which case, @vectors
5834  * may of course be %NULL), then a single byte is received and
5835  * discarded. This is to facilitate the common practice of sending a
5836  * single '\0' byte for the purposes of transferring ancillary data.
5837  *
5838  * @messages, if non-%NULL, will be set to point to a newly-allocated
5839  * array of #GSocketControlMessage instances or %NULL if no such
5840  * messages was received. These correspond to the control messages
5841  * received from the kernel, one #GSocketControlMessage per message
5842  * from the kernel. This array is %NULL-terminated and must be freed
5843  * by the caller using g_free() after calling g_object_unref() on each
5844  * element. If @messages is %NULL, any control messages received will
5845  * be discarded.
5846  *
5847  * @num_messages, if non-%NULL, will be set to the number of control
5848  * messages received.
5849  *
5850  * If both @messages and @num_messages are non-%NULL, then
5851  * @num_messages gives the number of #GSocketControlMessage instances
5852  * in @messages (ie: not including the %NULL terminator).
5853  *
5854  * @flags is an in/out parameter. The commonly available arguments
5855  * for this are available in the #GSocketMsgFlags enum, but the
5856  * values there are the same as the system values, and the flags
5857  * are passed in as-is, so you can pass in system-specific flags too
5858  * (and g_socket_receive_message() may pass system-specific flags out).
5859  * Flags passed in to the parameter affect the receive operation; flags returned
5860  * out of it are relevant to the specific returned message.
5861  *
5862  * As with g_socket_receive(), data may be discarded if @socket is
5863  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5864  * provide enough buffer space to read a complete message. You can pass
5865  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5866  * removing it from the receive queue, but there is no portable way to find
5867  * out the length of the message other than by reading it into a
5868  * sufficiently-large buffer.
5869  *
5870  * If the socket is in blocking mode the call will block until there
5871  * is some data to receive, the connection is closed, or there is an
5872  * error. If there is no data available and the socket is in
5873  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5874  * returned. To be notified when data is available, wait for the
5875  * %G_IO_IN condition.
5876  *
5877  * On error -1 is returned and @error is set accordingly.
5878  *
5879  * Returns: Number of bytes read, or 0 if the connection was closed by
5880  * the peer, or -1 on error
5881  *
5882  * Since: 2.22
5883  */
5884 gssize
5885 g_socket_receive_message (GSocket                 *socket,
5886                           GSocketAddress         **address,
5887                           GInputVector            *vectors,
5888                           gint                     num_vectors,
5889                           GSocketControlMessage ***messages,
5890                           gint                    *num_messages,
5891                           gint                    *flags,
5892                           GCancellable            *cancellable,
5893                           GError                 **error)
5894 {
5895   return g_socket_receive_message_with_timeout (socket, address, vectors,
5896                                                  num_vectors, messages,
5897                                                  num_messages, flags,
5898                                                  socket->priv->blocking ? -1 : 0,
5899                                                  cancellable, error);
5900 }
5901
5902 /**
5903  * g_socket_get_credentials:
5904  * @socket: a #GSocket.
5905  * @error: #GError for error reporting, or %NULL to ignore.
5906  *
5907  * Returns the credentials of the foreign process connected to this
5908  * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5909  * sockets).
5910  *
5911  * If this operation isn't supported on the OS, the method fails with
5912  * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5913  * by reading the %SO_PEERCRED option on the underlying socket.
5914  *
5915  * This method can be expected to be available on the following platforms:
5916  *
5917  * - Linux since GLib 2.26
5918  * - OpenBSD since GLib 2.30
5919  * - Solaris, Illumos and OpenSolaris since GLib 2.40
5920  * - NetBSD since GLib 2.42
5921  * - macOS, tvOS, iOS since GLib 2.66
5922  *
5923  * Other ways to obtain credentials from a foreign peer includes the
5924  * #GUnixCredentialsMessage type and
5925  * g_unix_connection_send_credentials() /
5926  * g_unix_connection_receive_credentials() functions.
5927  *
5928  * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5929  * that must be freed with g_object_unref().
5930  *
5931  * Since: 2.26
5932  */
5933 GCredentials *
5934 g_socket_get_credentials (GSocket   *socket,
5935                           GError   **error)
5936 {
5937   GCredentials *ret;
5938
5939   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
5940   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5941
5942   if (!check_socket (socket, error))
5943     return NULL;
5944
5945   ret = NULL;
5946
5947 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5948
5949 #ifdef SO_PEERCRED
5950   {
5951     guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
5952     socklen_t optlen = sizeof (native_creds_buf);
5953
5954     if (getsockopt (socket->priv->fd,
5955                     SOL_SOCKET,
5956                     SO_PEERCRED,
5957                     native_creds_buf,
5958                     &optlen) == 0)
5959       {
5960         ret = g_credentials_new ();
5961         g_credentials_set_native (ret,
5962                                   G_CREDENTIALS_NATIVE_TYPE,
5963                                   native_creds_buf);
5964       }
5965   }
5966 #elif G_CREDENTIALS_USE_APPLE_XUCRED
5967   {
5968     struct xucred cred;
5969     socklen_t optlen = sizeof (cred);
5970
5971     if (getsockopt (socket->priv->fd,
5972                     0,
5973                     LOCAL_PEERCRED,
5974                     &cred,
5975                     &optlen) == 0)
5976       {
5977         if (cred.cr_version == XUCRED_VERSION)
5978           {
5979             ret = g_credentials_new ();
5980             g_credentials_set_native (ret,
5981                                       G_CREDENTIALS_NATIVE_TYPE,
5982                                       &cred);
5983           }
5984         else
5985           {
5986             g_set_error (error,
5987                          G_IO_ERROR,
5988                          G_IO_ERROR_NOT_SUPPORTED,
5989                          /* No point in translating this! */
5990                          "struct xucred cr_version %u != %u",
5991                          cred.cr_version, XUCRED_VERSION);
5992             /* Reuse a translatable string we already have */
5993             g_prefix_error (error,
5994                             _("Unable to read socket credentials: %s"),
5995                             "");
5996
5997             return NULL;
5998           }
5999       }
6000   }
6001 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
6002   {
6003     struct unpcbid cred;
6004     socklen_t optlen = sizeof (cred);
6005
6006     if (getsockopt (socket->priv->fd,
6007                     0,
6008                     LOCAL_PEEREID,
6009                     &cred,
6010                     &optlen) == 0)
6011       {
6012         ret = g_credentials_new ();
6013         g_credentials_set_native (ret,
6014                                   G_CREDENTIALS_NATIVE_TYPE,
6015                                   &cred);
6016       }
6017   }
6018 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
6019   {
6020     ucred_t *ucred = NULL;
6021
6022     if (getpeerucred (socket->priv->fd, &ucred) == 0)
6023       {
6024         ret = g_credentials_new ();
6025         g_credentials_set_native (ret,
6026                                   G_CREDENTIALS_TYPE_SOLARIS_UCRED,
6027                                   ucred);
6028         ucred_free (ucred);
6029       }
6030   }
6031 #else
6032   #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
6033 #endif
6034
6035   if (!ret)
6036     {
6037       int errsv = get_socket_errno ();
6038
6039       g_set_error (error,
6040                    G_IO_ERROR,
6041                    socket_io_error_from_errno (errsv),
6042                    _("Unable to read socket credentials: %s"),
6043                    socket_strerror (errsv));
6044     }
6045
6046 #else
6047
6048   g_set_error_literal (error,
6049                        G_IO_ERROR,
6050                        G_IO_ERROR_NOT_SUPPORTED,
6051                        _("g_socket_get_credentials not implemented for this OS"));
6052 #endif
6053
6054   return ret;
6055 }
6056
6057 /**
6058  * g_socket_get_option:
6059  * @socket: a #GSocket
6060  * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6061  * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6062  * @value: (out): return location for the option value
6063  * @error: #GError for error reporting, or %NULL to ignore.
6064  *
6065  * Gets the value of an integer-valued option on @socket, as with
6066  * getsockopt(). (If you need to fetch a  non-integer-valued option,
6067  * you will need to call getsockopt() directly.)
6068  *
6069  * The [<gio/gnetworking.h>][gio-gnetworking.h]
6070  * header pulls in system headers that will define most of the
6071  * standard/portable socket options. For unusual socket protocols or
6072  * platform-dependent options, you may need to include additional
6073  * headers.
6074  *
6075  * Note that even for socket options that are a single byte in size,
6076  * @value is still a pointer to a #gint variable, not a #guchar;
6077  * g_socket_get_option() will handle the conversion internally.
6078  *
6079  * Returns: success or failure. On failure, @error will be set, and
6080  *   the system error value (`errno` or WSAGetLastError()) will still
6081  *   be set to the result of the getsockopt() call.
6082  *
6083  * Since: 2.36
6084  */
6085 gboolean
6086 g_socket_get_option (GSocket  *socket,
6087                      gint      level,
6088                      gint      optname,
6089                      gint     *value,
6090                      GError  **error)
6091 {
6092   guint size;
6093
6094   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6095
6096   /* g_socket_get_option() is called during socket init, so skip the init checks
6097    * in check_socket() */
6098   if (socket->priv->inited && !check_socket (socket, error))
6099     return FALSE;
6100
6101   *value = 0;
6102   size = sizeof (gint);
6103   if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
6104     {
6105       int errsv = get_socket_errno ();
6106
6107       g_set_error_literal (error,
6108                            G_IO_ERROR,
6109                            socket_io_error_from_errno (errsv),
6110                            socket_strerror (errsv));
6111 #ifndef G_OS_WIN32
6112       /* Reset errno in case the caller wants to look at it */
6113       errno = errsv;
6114 #endif
6115       return FALSE;
6116     }
6117
6118 #if G_BYTE_ORDER == G_BIG_ENDIAN
6119   /* If the returned value is smaller than an int then we need to
6120    * slide it over into the low-order bytes of *value.
6121    */
6122   if (size != sizeof (gint))
6123     *value = *value >> (8 * (sizeof (gint) - size));
6124 #endif
6125
6126   return TRUE;
6127 }
6128
6129 /**
6130  * g_socket_set_option:
6131  * @socket: a #GSocket
6132  * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6133  * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6134  * @value: the value to set the option to
6135  * @error: #GError for error reporting, or %NULL to ignore.
6136  *
6137  * Sets the value of an integer-valued option on @socket, as with
6138  * setsockopt(). (If you need to set a non-integer-valued option,
6139  * you will need to call setsockopt() directly.)
6140  *
6141  * The [<gio/gnetworking.h>][gio-gnetworking.h]
6142  * header pulls in system headers that will define most of the
6143  * standard/portable socket options. For unusual socket protocols or
6144  * platform-dependent options, you may need to include additional
6145  * headers.
6146  *
6147  * Returns: success or failure. On failure, @error will be set, and
6148  *   the system error value (`errno` or WSAGetLastError()) will still
6149  *   be set to the result of the setsockopt() call.
6150  *
6151  * Since: 2.36
6152  */
6153 gboolean
6154 g_socket_set_option (GSocket  *socket,
6155                      gint      level,
6156                      gint      optname,
6157                      gint      value,
6158                      GError  **error)
6159 {
6160   gint errsv;
6161
6162   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6163
6164   if (!check_socket (socket, error))
6165     return FALSE;
6166
6167   if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
6168     return TRUE;
6169
6170 #if !defined (__linux__) && !defined (G_OS_WIN32)
6171   /* Linux and Windows let you set a single-byte value from an int,
6172    * but most other platforms don't.
6173    */
6174   if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
6175     {
6176 #if G_BYTE_ORDER == G_BIG_ENDIAN
6177       value = value << (8 * (sizeof (gint) - 1));
6178 #endif
6179       if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
6180         return TRUE;
6181     }
6182 #endif
6183
6184   errsv = get_socket_errno ();
6185
6186   g_set_error_literal (error,
6187                        G_IO_ERROR,
6188                        socket_io_error_from_errno (errsv),
6189                        socket_strerror (errsv));
6190 #ifndef G_OS_WIN32
6191   errno = errsv;
6192 #endif
6193   return FALSE;
6194 }