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