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