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