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