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