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