Merge branch '976-disable-assert-checks' into 'master'
[glib.git] / gio / gsocket.c
blob859e807cbba24cc52961d143c2d1fbcac94cdf89
1 /* GIO - GLib Input, Output and Streaming Library
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.
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.
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.
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/>.
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>
28 #include "config.h"
30 #include "gsocket.h"
32 #ifdef G_OS_UNIX
33 #include "glib-unix.h"
34 #endif
36 #include <errno.h>
37 #include <signal.h>
38 #include <string.h>
39 #include <stdlib.h>
41 #ifndef G_OS_WIN32
42 # include <fcntl.h>
43 # include <unistd.h>
44 # include <sys/ioctl.h>
45 #endif
47 #ifdef HAVE_SIOCGIFADDR
48 #include <net/if.h>
49 #endif
51 #ifdef HAVE_SYS_FILIO_H
52 # include <sys/filio.h>
53 #endif
55 #ifdef G_OS_UNIX
56 #include <sys/uio.h>
57 #endif
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"
78 #ifdef G_OS_WIN32
79 /* For Windows XP runtime compatibility, but use the system's if_nametoindex() if available */
80 #include "gwin32networking.h"
81 #endif
83 /**
84 * SECTION:gsocket
85 * @short_description: Low-level socket object
86 * @include: gio/gio.h
87 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
89 * A #GSocket is a low-level networking primitive. It is a more or less
90 * direct mapping of the BSD socket API in a portable GObject based API.
91 * It supports both the UNIX socket implementations and winsock2 on Windows.
93 * #GSocket is the platform independent base upon which the higher level
94 * network primitives are based. Applications are not typically meant to
95 * use it directly, but rather through classes like #GSocketClient,
96 * #GSocketService and #GSocketConnection. However there may be cases where
97 * direct use of #GSocket is useful.
99 * #GSocket implements the #GInitable interface, so if it is manually constructed
100 * by e.g. g_object_new() you must call g_initable_init() and check the
101 * results before using the object. This is done automatically in
102 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
103 * %NULL.
105 * Sockets operate in two general modes, blocking or non-blocking. When
106 * in blocking mode all operations (which don’t take an explicit blocking
107 * parameter) block until the requested operation
108 * is finished or there is an error. In non-blocking mode all calls that
109 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
110 * To know when a call would successfully run you can call g_socket_condition_check(),
111 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
112 * attach it to a #GMainContext to get callbacks when I/O is possible.
113 * Note that all sockets are always set to non blocking mode in the system, and
114 * blocking mode is emulated in GSocket.
116 * When working in non-blocking mode applications should always be able to
117 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
118 * function said that I/O was possible. This can easily happen in case
119 * of a race condition in the application, but it can also happen for other
120 * reasons. For instance, on Windows a socket is always seen as writable
121 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
123 * #GSockets can be either connection oriented or datagram based.
124 * For connection oriented types you must first establish a connection by
125 * either connecting to an address or accepting a connection from another
126 * address. For connectionless socket types the target/source address is
127 * specified or received in each I/O operation.
129 * All socket file descriptors are set to be close-on-exec.
131 * Note that creating a #GSocket causes the signal %SIGPIPE to be
132 * ignored for the remainder of the program. If you are writing a
133 * command-line utility that uses #GSocket, you may need to take into
134 * account the fact that your program will not automatically be killed
135 * if it tries to write to %stdout after it has been closed.
137 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
138 * a #GSocket concurrently from multiple threads, you must implement your own
139 * locking.
141 * Since: 2.22
144 static void g_socket_initable_iface_init (GInitableIface *iface);
145 static gboolean g_socket_initable_init (GInitable *initable,
146 GCancellable *cancellable,
147 GError **error);
149 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface);
150 static gint g_socket_datagram_based_receive_messages (GDatagramBased *self,
151 GInputMessage *messages,
152 guint num_messages,
153 gint flags,
154 gint64 timeout,
155 GCancellable *cancellable,
156 GError **error);
157 static gint g_socket_datagram_based_send_messages (GDatagramBased *self,
158 GOutputMessage *messages,
159 guint num_messages,
160 gint flags,
161 gint64 timeout,
162 GCancellable *cancellable,
163 GError **error);
164 static GSource *g_socket_datagram_based_create_source (GDatagramBased *self,
165 GIOCondition condition,
166 GCancellable *cancellable);
167 static GIOCondition g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
168 GIOCondition condition);
169 static gboolean g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
170 GIOCondition condition,
171 gint64 timeout,
172 GCancellable *cancellable,
173 GError **error);
175 static GSocketAddress *
176 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len);
178 static gssize
179 g_socket_receive_message_with_timeout (GSocket *socket,
180 GSocketAddress **address,
181 GInputVector *vectors,
182 gint num_vectors,
183 GSocketControlMessage ***messages,
184 gint *num_messages,
185 gint *flags,
186 gint64 timeout,
187 GCancellable *cancellable,
188 GError **error);
189 static gint
190 g_socket_receive_messages_with_timeout (GSocket *socket,
191 GInputMessage *messages,
192 guint num_messages,
193 gint flags,
194 gint64 timeout,
195 GCancellable *cancellable,
196 GError **error);
197 static gssize
198 g_socket_send_message_with_timeout (GSocket *socket,
199 GSocketAddress *address,
200 GOutputVector *vectors,
201 gint num_vectors,
202 GSocketControlMessage **messages,
203 gint num_messages,
204 gint flags,
205 gint64 timeout,
206 GCancellable *cancellable,
207 GError **error);
208 static gint
209 g_socket_send_messages_with_timeout (GSocket *socket,
210 GOutputMessage *messages,
211 guint num_messages,
212 gint flags,
213 gint64 timeout,
214 GCancellable *cancellable,
215 GError **error);
217 enum
219 PROP_0,
220 PROP_FAMILY,
221 PROP_TYPE,
222 PROP_PROTOCOL,
223 PROP_FD,
224 PROP_BLOCKING,
225 PROP_LISTEN_BACKLOG,
226 PROP_KEEPALIVE,
227 PROP_LOCAL_ADDRESS,
228 PROP_REMOTE_ADDRESS,
229 PROP_TIMEOUT,
230 PROP_TTL,
231 PROP_BROADCAST,
232 PROP_MULTICAST_LOOPBACK,
233 PROP_MULTICAST_TTL
236 /* Size of the receiver cache for g_socket_receive_from() */
237 #define RECV_ADDR_CACHE_SIZE 8
239 struct _GSocketPrivate
241 GSocketFamily family;
242 GSocketType type;
243 GSocketProtocol protocol;
244 gint fd;
245 gint listen_backlog;
246 guint timeout;
247 GError *construct_error;
248 GSocketAddress *remote_address;
249 guint inited : 1;
250 guint blocking : 1;
251 guint keepalive : 1;
252 guint closed : 1;
253 guint connected_read : 1;
254 guint connected_write : 1;
255 guint listening : 1;
256 guint timed_out : 1;
257 guint connect_pending : 1;
258 #ifdef G_OS_WIN32
259 WSAEVENT event;
260 gboolean waiting;
261 DWORD waiting_result;
262 int current_events;
263 int current_errors;
264 int selected_events;
265 GList *requested_conditions; /* list of requested GIOCondition * */
266 GMutex win32_source_lock;
267 GCond win32_source_cond;
268 #endif
270 struct {
271 GSocketAddress *addr;
272 struct sockaddr *native;
273 gint native_len;
274 guint64 last_used;
275 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
278 _G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket, g_socket, G_TYPE_OBJECT, 0,
279 /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
280 g_type_ensure (G_TYPE_SOCKET_FAMILY);
281 g_type_ensure (G_TYPE_SOCKET_TYPE);
282 g_type_ensure (G_TYPE_SOCKET_PROTOCOL);
283 g_type_ensure (G_TYPE_SOCKET_ADDRESS);
284 /* And networking init is appropriate for the prelude */
285 g_networking_init ();
286 , /* And now the regular type init code */
287 G_ADD_PRIVATE (GSocket)
288 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
289 g_socket_initable_iface_init);
290 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
291 g_socket_datagram_based_iface_init));
293 static int
294 get_socket_errno (void)
296 #ifndef G_OS_WIN32
297 return errno;
298 #else
299 return WSAGetLastError ();
300 #endif
303 static GIOErrorEnum
304 socket_io_error_from_errno (int err)
306 #ifdef G_OS_WIN32
307 return g_io_error_from_win32_error (err);
308 #else
309 return g_io_error_from_errno (err);
310 #endif
313 static const char *
314 socket_strerror (int err)
316 #ifndef G_OS_WIN32
317 return g_strerror (err);
318 #else
319 const char *msg_ret;
320 char *msg;
322 msg = g_win32_error_message (err);
324 msg_ret = g_intern_string (msg);
325 g_free (msg);
327 return msg_ret;
328 #endif
331 /* Wrapper around g_set_error() to avoid doing excess work */
332 #define socket_set_error_lazy(err, errsv, fmt) \
333 G_STMT_START { \
334 GError **__err = (err); \
335 int __errsv = (errsv); \
337 if (__err) \
339 int __code = socket_io_error_from_errno (__errsv); \
340 const char *__strerr = socket_strerror (__errsv); \
342 if (__code == G_IO_ERROR_WOULD_BLOCK) \
343 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
344 else \
345 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
347 } G_STMT_END
349 #ifdef G_OS_WIN32
350 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
351 static void
352 _win32_unset_event_mask (GSocket *socket, int mask)
354 g_mutex_lock (&socket->priv->win32_source_lock);
355 socket->priv->current_events &= ~mask;
356 socket->priv->current_errors &= ~mask;
357 g_mutex_unlock (&socket->priv->win32_source_lock);
359 #else
360 #define win32_unset_event_mask(_socket, _mask)
361 #endif
363 /* Windows has broken prototypes... */
364 #ifdef G_OS_WIN32
365 #define getsockopt(sockfd, level, optname, optval, optlen) \
366 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
367 #define setsockopt(sockfd, level, optname, optval, optlen) \
368 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
369 #define getsockname(sockfd, addr, addrlen) \
370 getsockname (sockfd, addr, (int *)addrlen)
371 #define getpeername(sockfd, addr, addrlen) \
372 getpeername (sockfd, addr, (int *)addrlen)
373 #define recv(sockfd, buf, len, flags) \
374 recv (sockfd, (gpointer)buf, len, flags)
375 #endif
377 static gboolean
378 check_socket (GSocket *socket,
379 GError **error)
381 if (!socket->priv->inited)
383 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
384 _("Invalid socket, not initialized"));
385 return FALSE;
388 if (socket->priv->construct_error)
390 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
391 _("Invalid socket, initialization failed due to: %s"),
392 socket->priv->construct_error->message);
393 return FALSE;
396 if (socket->priv->closed)
398 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
399 _("Socket is already closed"));
400 return FALSE;
403 return TRUE;
406 static gboolean
407 check_timeout (GSocket *socket,
408 GError **error)
410 if (socket->priv->timed_out)
412 socket->priv->timed_out = FALSE;
413 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
414 _("Socket I/O timed out"));
415 return FALSE;
418 return TRUE;
421 static void
422 g_socket_details_from_fd (GSocket *socket)
424 union {
425 struct sockaddr_storage storage;
426 struct sockaddr sa;
427 } address;
428 gint fd;
429 guint addrlen;
430 int value, family;
431 int errsv;
433 fd = socket->priv->fd;
434 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
436 errsv = get_socket_errno ();
437 goto err;
440 switch (value)
442 case SOCK_STREAM:
443 socket->priv->type = G_SOCKET_TYPE_STREAM;
444 break;
446 case SOCK_DGRAM:
447 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
448 break;
450 case SOCK_SEQPACKET:
451 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
452 break;
454 default:
455 socket->priv->type = G_SOCKET_TYPE_INVALID;
456 break;
459 addrlen = sizeof address;
460 if (getsockname (fd, &address.sa, &addrlen) != 0)
462 errsv = get_socket_errno ();
463 goto err;
466 if (addrlen > 0)
468 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
469 sizeof address.storage.ss_family <= addrlen);
470 family = address.storage.ss_family;
472 else
474 /* On Solaris, this happens if the socket is not yet connected.
475 * But we can use SO_DOMAIN as a workaround there.
477 #ifdef SO_DOMAIN
478 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
480 errsv = get_socket_errno ();
481 goto err;
483 #else
484 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
485 errsv = -1;
486 goto err;
487 #endif
490 switch (family)
492 case G_SOCKET_FAMILY_IPV4:
493 case G_SOCKET_FAMILY_IPV6:
494 socket->priv->family = address.storage.ss_family;
495 switch (socket->priv->type)
497 case G_SOCKET_TYPE_STREAM:
498 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
499 break;
501 case G_SOCKET_TYPE_DATAGRAM:
502 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
503 break;
505 case G_SOCKET_TYPE_SEQPACKET:
506 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
507 break;
509 default:
510 break;
512 break;
514 case G_SOCKET_FAMILY_UNIX:
515 socket->priv->family = G_SOCKET_FAMILY_UNIX;
516 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
517 break;
519 default:
520 socket->priv->family = G_SOCKET_FAMILY_INVALID;
521 break;
524 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
526 addrlen = sizeof address;
527 if (getpeername (fd, &address.sa, &addrlen) >= 0)
529 socket->priv->connected_read = TRUE;
530 socket->priv->connected_write = TRUE;
534 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
536 socket->priv->keepalive = !!value;
538 else
540 /* Can't read, maybe not supported, assume FALSE */
541 socket->priv->keepalive = FALSE;
544 return;
546 err:
547 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
548 socket_io_error_from_errno (errsv),
549 _("creating GSocket from fd: %s"),
550 socket_strerror (errsv));
553 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
554 gint
555 g_socket (gint domain,
556 gint type,
557 gint protocol,
558 GError **error)
560 int fd, errsv;
562 #ifdef SOCK_CLOEXEC
563 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
564 errsv = errno;
565 if (fd != -1)
566 return fd;
568 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
569 if (fd < 0 && (errsv == EINVAL || errsv == EPROTOTYPE))
570 #endif
571 fd = socket (domain, type, protocol);
573 if (fd < 0)
575 errsv = get_socket_errno ();
577 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
578 _("Unable to create socket: %s"), socket_strerror (errsv));
579 errno = errsv;
580 return -1;
583 #ifndef G_OS_WIN32
585 int flags;
587 /* We always want to set close-on-exec to protect users. If you
588 need to so some weird inheritance to exec you can re-enable this
589 using lower level hacks with g_socket_get_fd(). */
590 flags = fcntl (fd, F_GETFD, 0);
591 if (flags != -1 &&
592 (flags & FD_CLOEXEC) == 0)
594 flags |= FD_CLOEXEC;
595 fcntl (fd, F_SETFD, flags);
598 #endif
600 return fd;
603 static gint
604 g_socket_create_socket (GSocketFamily family,
605 GSocketType type,
606 int protocol,
607 GError **error)
609 gint native_type;
611 switch (type)
613 case G_SOCKET_TYPE_STREAM:
614 native_type = SOCK_STREAM;
615 break;
617 case G_SOCKET_TYPE_DATAGRAM:
618 native_type = SOCK_DGRAM;
619 break;
621 case G_SOCKET_TYPE_SEQPACKET:
622 native_type = SOCK_SEQPACKET;
623 break;
625 default:
626 g_assert_not_reached ();
629 if (family <= 0)
631 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
632 _("Unable to create socket: %s"), _("Unknown family was specified"));
633 return -1;
636 if (protocol == -1)
638 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
639 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
640 return -1;
643 return g_socket (family, native_type, protocol, error);
646 static void
647 g_socket_constructed (GObject *object)
649 GSocket *socket = G_SOCKET (object);
651 if (socket->priv->fd >= 0)
652 /* create socket->priv info from the fd */
653 g_socket_details_from_fd (socket);
655 else
656 /* create the fd from socket->priv info */
657 socket->priv->fd = g_socket_create_socket (socket->priv->family,
658 socket->priv->type,
659 socket->priv->protocol,
660 &socket->priv->construct_error);
662 if (socket->priv->fd != -1)
664 #ifndef G_OS_WIN32
665 GError *error = NULL;
666 #else
667 gulong arg;
668 #endif
670 /* Always use native nonblocking sockets, as Windows sets sockets to
671 * nonblocking automatically in certain operations. This way we make
672 * things work the same on all platforms.
674 #ifndef G_OS_WIN32
675 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
677 g_warning ("Error setting socket nonblocking: %s", error->message);
678 g_clear_error (&error);
680 #else
681 arg = TRUE;
683 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
685 int errsv = get_socket_errno ();
686 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
688 #endif
690 #ifdef SO_NOSIGPIPE
691 /* See note about SIGPIPE below. */
692 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
693 #endif
697 static void
698 g_socket_get_property (GObject *object,
699 guint prop_id,
700 GValue *value,
701 GParamSpec *pspec)
703 GSocket *socket = G_SOCKET (object);
704 GSocketAddress *address;
706 switch (prop_id)
708 case PROP_FAMILY:
709 g_value_set_enum (value, socket->priv->family);
710 break;
712 case PROP_TYPE:
713 g_value_set_enum (value, socket->priv->type);
714 break;
716 case PROP_PROTOCOL:
717 g_value_set_enum (value, socket->priv->protocol);
718 break;
720 case PROP_FD:
721 g_value_set_int (value, socket->priv->fd);
722 break;
724 case PROP_BLOCKING:
725 g_value_set_boolean (value, socket->priv->blocking);
726 break;
728 case PROP_LISTEN_BACKLOG:
729 g_value_set_int (value, socket->priv->listen_backlog);
730 break;
732 case PROP_KEEPALIVE:
733 g_value_set_boolean (value, socket->priv->keepalive);
734 break;
736 case PROP_LOCAL_ADDRESS:
737 address = g_socket_get_local_address (socket, NULL);
738 g_value_take_object (value, address);
739 break;
741 case PROP_REMOTE_ADDRESS:
742 address = g_socket_get_remote_address (socket, NULL);
743 g_value_take_object (value, address);
744 break;
746 case PROP_TIMEOUT:
747 g_value_set_uint (value, socket->priv->timeout);
748 break;
750 case PROP_TTL:
751 g_value_set_uint (value, g_socket_get_ttl (socket));
752 break;
754 case PROP_BROADCAST:
755 g_value_set_boolean (value, g_socket_get_broadcast (socket));
756 break;
758 case PROP_MULTICAST_LOOPBACK:
759 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
760 break;
762 case PROP_MULTICAST_TTL:
763 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
764 break;
766 default:
767 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
771 static void
772 g_socket_set_property (GObject *object,
773 guint prop_id,
774 const GValue *value,
775 GParamSpec *pspec)
777 GSocket *socket = G_SOCKET (object);
779 switch (prop_id)
781 case PROP_FAMILY:
782 socket->priv->family = g_value_get_enum (value);
783 break;
785 case PROP_TYPE:
786 socket->priv->type = g_value_get_enum (value);
787 break;
789 case PROP_PROTOCOL:
790 socket->priv->protocol = g_value_get_enum (value);
791 break;
793 case PROP_FD:
794 socket->priv->fd = g_value_get_int (value);
795 break;
797 case PROP_BLOCKING:
798 g_socket_set_blocking (socket, g_value_get_boolean (value));
799 break;
801 case PROP_LISTEN_BACKLOG:
802 g_socket_set_listen_backlog (socket, g_value_get_int (value));
803 break;
805 case PROP_KEEPALIVE:
806 g_socket_set_keepalive (socket, g_value_get_boolean (value));
807 break;
809 case PROP_TIMEOUT:
810 g_socket_set_timeout (socket, g_value_get_uint (value));
811 break;
813 case PROP_TTL:
814 g_socket_set_ttl (socket, g_value_get_uint (value));
815 break;
817 case PROP_BROADCAST:
818 g_socket_set_broadcast (socket, g_value_get_boolean (value));
819 break;
821 case PROP_MULTICAST_LOOPBACK:
822 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
823 break;
825 case PROP_MULTICAST_TTL:
826 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
827 break;
829 default:
830 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
834 static void
835 g_socket_finalize (GObject *object)
837 GSocket *socket = G_SOCKET (object);
838 gint i;
840 g_clear_error (&socket->priv->construct_error);
842 if (socket->priv->fd != -1 &&
843 !socket->priv->closed)
844 g_socket_close (socket, NULL);
846 if (socket->priv->remote_address)
847 g_object_unref (socket->priv->remote_address);
849 #ifdef G_OS_WIN32
850 if (socket->priv->event != WSA_INVALID_EVENT)
852 WSACloseEvent (socket->priv->event);
853 socket->priv->event = WSA_INVALID_EVENT;
856 g_assert (socket->priv->requested_conditions == NULL);
857 g_mutex_clear (&socket->priv->win32_source_lock);
858 g_cond_clear (&socket->priv->win32_source_cond);
859 #endif
861 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
863 if (socket->priv->recv_addr_cache[i].addr)
865 g_object_unref (socket->priv->recv_addr_cache[i].addr);
866 g_free (socket->priv->recv_addr_cache[i].native);
870 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
871 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
874 static void
875 g_socket_class_init (GSocketClass *klass)
877 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
879 #ifdef SIGPIPE
880 /* There is no portable, thread-safe way to avoid having the process
881 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
882 * forced to simply ignore the signal process-wide.
884 * Even if we ignore it though, gdb will still stop if the app
885 * receives a SIGPIPE, which can be confusing and annoying. So when
886 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
887 * prevent the signal from occurring at all.
889 signal (SIGPIPE, SIG_IGN);
890 #endif
892 gobject_class->finalize = g_socket_finalize;
893 gobject_class->constructed = g_socket_constructed;
894 gobject_class->set_property = g_socket_set_property;
895 gobject_class->get_property = g_socket_get_property;
897 g_object_class_install_property (gobject_class, PROP_FAMILY,
898 g_param_spec_enum ("family",
899 P_("Socket family"),
900 P_("The sockets address family"),
901 G_TYPE_SOCKET_FAMILY,
902 G_SOCKET_FAMILY_INVALID,
903 G_PARAM_CONSTRUCT_ONLY |
904 G_PARAM_READWRITE |
905 G_PARAM_STATIC_STRINGS));
907 g_object_class_install_property (gobject_class, PROP_TYPE,
908 g_param_spec_enum ("type",
909 P_("Socket type"),
910 P_("The sockets type"),
911 G_TYPE_SOCKET_TYPE,
912 G_SOCKET_TYPE_STREAM,
913 G_PARAM_CONSTRUCT_ONLY |
914 G_PARAM_READWRITE |
915 G_PARAM_STATIC_STRINGS));
917 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
918 g_param_spec_enum ("protocol",
919 P_("Socket protocol"),
920 P_("The id of the protocol to use, or -1 for unknown"),
921 G_TYPE_SOCKET_PROTOCOL,
922 G_SOCKET_PROTOCOL_UNKNOWN,
923 G_PARAM_CONSTRUCT_ONLY |
924 G_PARAM_READWRITE |
925 G_PARAM_STATIC_STRINGS));
927 g_object_class_install_property (gobject_class, PROP_FD,
928 g_param_spec_int ("fd",
929 P_("File descriptor"),
930 P_("The sockets file descriptor"),
931 G_MININT,
932 G_MAXINT,
934 G_PARAM_CONSTRUCT_ONLY |
935 G_PARAM_READWRITE |
936 G_PARAM_STATIC_STRINGS));
938 g_object_class_install_property (gobject_class, PROP_BLOCKING,
939 g_param_spec_boolean ("blocking",
940 P_("blocking"),
941 P_("Whether or not I/O on this socket is blocking"),
942 TRUE,
943 G_PARAM_READWRITE |
944 G_PARAM_STATIC_STRINGS));
946 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
947 g_param_spec_int ("listen-backlog",
948 P_("Listen backlog"),
949 P_("Outstanding connections in the listen queue"),
951 SOMAXCONN,
953 G_PARAM_READWRITE |
954 G_PARAM_STATIC_STRINGS));
956 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
957 g_param_spec_boolean ("keepalive",
958 P_("Keep connection alive"),
959 P_("Keep connection alive by sending periodic pings"),
960 FALSE,
961 G_PARAM_READWRITE |
962 G_PARAM_STATIC_STRINGS));
964 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
965 g_param_spec_object ("local-address",
966 P_("Local address"),
967 P_("The local address the socket is bound to"),
968 G_TYPE_SOCKET_ADDRESS,
969 G_PARAM_READABLE |
970 G_PARAM_STATIC_STRINGS));
972 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
973 g_param_spec_object ("remote-address",
974 P_("Remote address"),
975 P_("The remote address the socket is connected to"),
976 G_TYPE_SOCKET_ADDRESS,
977 G_PARAM_READABLE |
978 G_PARAM_STATIC_STRINGS));
981 * GSocket:timeout:
983 * The timeout in seconds on socket I/O
985 * Since: 2.26
987 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
988 g_param_spec_uint ("timeout",
989 P_("Timeout"),
990 P_("The timeout in seconds on socket I/O"),
992 G_MAXUINT,
994 G_PARAM_READWRITE |
995 G_PARAM_STATIC_STRINGS));
998 * GSocket:broadcast:
1000 * Whether the socket should allow sending to broadcast addresses.
1002 * Since: 2.32
1004 g_object_class_install_property (gobject_class, PROP_BROADCAST,
1005 g_param_spec_boolean ("broadcast",
1006 P_("Broadcast"),
1007 P_("Whether to allow sending to broadcast addresses"),
1008 FALSE,
1009 G_PARAM_READWRITE |
1010 G_PARAM_STATIC_STRINGS));
1013 * GSocket:ttl:
1015 * Time-to-live for outgoing unicast packets
1017 * Since: 2.32
1019 g_object_class_install_property (gobject_class, PROP_TTL,
1020 g_param_spec_uint ("ttl",
1021 P_("TTL"),
1022 P_("Time-to-live of outgoing unicast packets"),
1023 0, G_MAXUINT, 0,
1024 G_PARAM_READWRITE |
1025 G_PARAM_STATIC_STRINGS));
1028 * GSocket:multicast-loopback:
1030 * Whether outgoing multicast packets loop back to the local host.
1032 * Since: 2.32
1034 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1035 g_param_spec_boolean ("multicast-loopback",
1036 P_("Multicast loopback"),
1037 P_("Whether outgoing multicast packets loop back to the local host"),
1038 TRUE,
1039 G_PARAM_READWRITE |
1040 G_PARAM_STATIC_STRINGS));
1043 * GSocket:multicast-ttl:
1045 * Time-to-live out outgoing multicast packets
1047 * Since: 2.32
1049 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1050 g_param_spec_uint ("multicast-ttl",
1051 P_("Multicast TTL"),
1052 P_("Time-to-live of outgoing multicast packets"),
1053 0, G_MAXUINT, 1,
1054 G_PARAM_READWRITE |
1055 G_PARAM_STATIC_STRINGS));
1058 static void
1059 g_socket_initable_iface_init (GInitableIface *iface)
1061 iface->init = g_socket_initable_init;
1064 static void
1065 g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1067 iface->receive_messages = g_socket_datagram_based_receive_messages;
1068 iface->send_messages = g_socket_datagram_based_send_messages;
1069 iface->create_source = g_socket_datagram_based_create_source;
1070 iface->condition_check = g_socket_datagram_based_condition_check;
1071 iface->condition_wait = g_socket_datagram_based_condition_wait;
1074 static void
1075 g_socket_init (GSocket *socket)
1077 socket->priv = g_socket_get_instance_private (socket);
1079 socket->priv->fd = -1;
1080 socket->priv->blocking = TRUE;
1081 socket->priv->listen_backlog = 10;
1082 socket->priv->construct_error = NULL;
1083 #ifdef G_OS_WIN32
1084 socket->priv->event = WSA_INVALID_EVENT;
1085 g_mutex_init (&socket->priv->win32_source_lock);
1086 g_cond_init (&socket->priv->win32_source_cond);
1087 #endif
1090 static gboolean
1091 g_socket_initable_init (GInitable *initable,
1092 GCancellable *cancellable,
1093 GError **error)
1095 GSocket *socket;
1097 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1099 socket = G_SOCKET (initable);
1101 if (cancellable != NULL)
1103 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1104 _("Cancellable initialization not supported"));
1105 return FALSE;
1108 socket->priv->inited = TRUE;
1110 if (socket->priv->construct_error)
1112 if (error)
1113 *error = g_error_copy (socket->priv->construct_error);
1114 return FALSE;
1118 return TRUE;
1121 static gboolean
1122 check_datagram_based (GDatagramBased *self,
1123 GError **error)
1125 switch (g_socket_get_socket_type (G_SOCKET (self)))
1127 case G_SOCKET_TYPE_INVALID:
1128 case G_SOCKET_TYPE_STREAM:
1129 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1130 _("Cannot use datagram operations on a non-datagram "
1131 "socket."));
1132 return FALSE;
1133 case G_SOCKET_TYPE_DATAGRAM:
1134 case G_SOCKET_TYPE_SEQPACKET:
1135 /* Fall through. */
1136 break;
1139 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1140 * pretty tricky to split out #GSocket:timeout so that it does not affect
1141 * #GDatagramBased operations (but still affects #GSocket operations). It is
1142 * not worth that effort — just disallow it and require the user to specify
1143 * timeouts on a per-operation basis. */
1144 if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1146 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1147 _("Cannot use datagram operations on a socket with a "
1148 "timeout set."));
1149 return FALSE;
1152 return TRUE;
1155 static gint
1156 g_socket_datagram_based_receive_messages (GDatagramBased *self,
1157 GInputMessage *messages,
1158 guint num_messages,
1159 gint flags,
1160 gint64 timeout,
1161 GCancellable *cancellable,
1162 GError **error)
1164 if (!check_datagram_based (self, error))
1165 return FALSE;
1167 return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1168 num_messages, flags, timeout,
1169 cancellable, error);
1172 static gint
1173 g_socket_datagram_based_send_messages (GDatagramBased *self,
1174 GOutputMessage *messages,
1175 guint num_messages,
1176 gint flags,
1177 gint64 timeout,
1178 GCancellable *cancellable,
1179 GError **error)
1181 if (!check_datagram_based (self, error))
1182 return FALSE;
1184 return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1185 num_messages, flags, timeout,
1186 cancellable, error);
1189 static GSource *
1190 g_socket_datagram_based_create_source (GDatagramBased *self,
1191 GIOCondition condition,
1192 GCancellable *cancellable)
1194 if (!check_datagram_based (self, NULL))
1195 return NULL;
1197 return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1200 static GIOCondition
1201 g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
1202 GIOCondition condition)
1204 if (!check_datagram_based (datagram_based, NULL))
1205 return G_IO_ERR;
1207 return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1210 static gboolean
1211 g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
1212 GIOCondition condition,
1213 gint64 timeout,
1214 GCancellable *cancellable,
1215 GError **error)
1217 if (!check_datagram_based (datagram_based, error))
1218 return FALSE;
1220 return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1221 timeout, cancellable, error);
1225 * g_socket_new:
1226 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1227 * @type: the socket type to use.
1228 * @protocol: the id of the protocol to use, or 0 for default.
1229 * @error: #GError for error reporting, or %NULL to ignore.
1231 * Creates a new #GSocket with the defined family, type and protocol.
1232 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1233 * for the family and type is used.
1235 * The @protocol is a family and type specific int that specifies what
1236 * kind of protocol to use. #GSocketProtocol lists several common ones.
1237 * Many families only support one protocol, and use 0 for this, others
1238 * support several and using 0 means to use the default protocol for
1239 * the family and type.
1241 * The protocol id is passed directly to the operating
1242 * system, so you can use protocols not listed in #GSocketProtocol if you
1243 * know the protocol number used for it.
1245 * Returns: a #GSocket or %NULL on error.
1246 * Free the returned object with g_object_unref().
1248 * Since: 2.22
1250 GSocket *
1251 g_socket_new (GSocketFamily family,
1252 GSocketType type,
1253 GSocketProtocol protocol,
1254 GError **error)
1256 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1257 NULL, error,
1258 "family", family,
1259 "type", type,
1260 "protocol", protocol,
1261 NULL));
1265 * g_socket_new_from_fd:
1266 * @fd: a native socket file descriptor.
1267 * @error: #GError for error reporting, or %NULL to ignore.
1269 * Creates a new #GSocket from a native file descriptor
1270 * or winsock SOCKET handle.
1272 * This reads all the settings from the file descriptor so that
1273 * all properties should work. Note that the file descriptor
1274 * will be set to non-blocking mode, independent on the blocking
1275 * mode of the #GSocket.
1277 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1278 * caller must close @fd themselves.
1280 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1281 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1283 * Returns: a #GSocket or %NULL on error.
1284 * Free the returned object with g_object_unref().
1286 * Since: 2.22
1288 GSocket *
1289 g_socket_new_from_fd (gint fd,
1290 GError **error)
1292 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1293 NULL, error,
1294 "fd", fd,
1295 NULL));
1299 * g_socket_set_blocking:
1300 * @socket: a #GSocket.
1301 * @blocking: Whether to use blocking I/O or not.
1303 * Sets the blocking mode of the socket. In blocking mode
1304 * all operations (which don’t take an explicit blocking parameter) block until
1305 * they succeed or there is an error. In
1306 * non-blocking mode all functions return results immediately or
1307 * with a %G_IO_ERROR_WOULD_BLOCK error.
1309 * All sockets are created in blocking mode. However, note that the
1310 * platform level socket is always non-blocking, and blocking mode
1311 * is a GSocket level feature.
1313 * Since: 2.22
1315 void
1316 g_socket_set_blocking (GSocket *socket,
1317 gboolean blocking)
1319 g_return_if_fail (G_IS_SOCKET (socket));
1321 blocking = !!blocking;
1323 if (socket->priv->blocking == blocking)
1324 return;
1326 socket->priv->blocking = blocking;
1327 g_object_notify (G_OBJECT (socket), "blocking");
1331 * g_socket_get_blocking:
1332 * @socket: a #GSocket.
1334 * Gets the blocking mode of the socket. For details on blocking I/O,
1335 * see g_socket_set_blocking().
1337 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1339 * Since: 2.22
1341 gboolean
1342 g_socket_get_blocking (GSocket *socket)
1344 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1346 return socket->priv->blocking;
1350 * g_socket_set_keepalive:
1351 * @socket: a #GSocket.
1352 * @keepalive: Value for the keepalive flag
1354 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1355 * this flag is set on a socket, the system will attempt to verify that the
1356 * remote socket endpoint is still present if a sufficiently long period of
1357 * time passes with no data being exchanged. If the system is unable to
1358 * verify the presence of the remote endpoint, it will automatically close
1359 * the connection.
1361 * This option is only functional on certain kinds of sockets. (Notably,
1362 * %G_SOCKET_PROTOCOL_TCP sockets.)
1364 * The exact time between pings is system- and protocol-dependent, but will
1365 * normally be at least two hours. Most commonly, you would set this flag
1366 * on a server socket if you want to allow clients to remain idle for long
1367 * periods of time, but also want to ensure that connections are eventually
1368 * garbage-collected if clients crash or become unreachable.
1370 * Since: 2.22
1372 void
1373 g_socket_set_keepalive (GSocket *socket,
1374 gboolean keepalive)
1376 GError *error = NULL;
1378 g_return_if_fail (G_IS_SOCKET (socket));
1380 keepalive = !!keepalive;
1381 if (socket->priv->keepalive == keepalive)
1382 return;
1384 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1385 keepalive, &error))
1387 g_warning ("error setting keepalive: %s", error->message);
1388 g_error_free (error);
1389 return;
1392 socket->priv->keepalive = keepalive;
1393 g_object_notify (G_OBJECT (socket), "keepalive");
1397 * g_socket_get_keepalive:
1398 * @socket: a #GSocket.
1400 * Gets the keepalive mode of the socket. For details on this,
1401 * see g_socket_set_keepalive().
1403 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1405 * Since: 2.22
1407 gboolean
1408 g_socket_get_keepalive (GSocket *socket)
1410 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1412 return socket->priv->keepalive;
1416 * g_socket_get_listen_backlog:
1417 * @socket: a #GSocket.
1419 * Gets the listen backlog setting of the socket. For details on this,
1420 * see g_socket_set_listen_backlog().
1422 * Returns: the maximum number of pending connections.
1424 * Since: 2.22
1426 gint
1427 g_socket_get_listen_backlog (GSocket *socket)
1429 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1431 return socket->priv->listen_backlog;
1435 * g_socket_set_listen_backlog:
1436 * @socket: a #GSocket.
1437 * @backlog: the maximum number of pending connections.
1439 * Sets the maximum number of outstanding connections allowed
1440 * when listening on this socket. If more clients than this are
1441 * connecting to the socket and the application is not handling them
1442 * on time then the new connections will be refused.
1444 * Note that this must be called before g_socket_listen() and has no
1445 * effect if called after that.
1447 * Since: 2.22
1449 void
1450 g_socket_set_listen_backlog (GSocket *socket,
1451 gint backlog)
1453 g_return_if_fail (G_IS_SOCKET (socket));
1454 g_return_if_fail (!socket->priv->listening);
1456 if (backlog != socket->priv->listen_backlog)
1458 socket->priv->listen_backlog = backlog;
1459 g_object_notify (G_OBJECT (socket), "listen-backlog");
1464 * g_socket_get_timeout:
1465 * @socket: a #GSocket.
1467 * Gets the timeout setting of the socket. For details on this, see
1468 * g_socket_set_timeout().
1470 * Returns: the timeout in seconds
1472 * Since: 2.26
1474 guint
1475 g_socket_get_timeout (GSocket *socket)
1477 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1479 return socket->priv->timeout;
1483 * g_socket_set_timeout:
1484 * @socket: a #GSocket.
1485 * @timeout: the timeout for @socket, in seconds, or 0 for none
1487 * Sets the time in seconds after which I/O operations on @socket will
1488 * time out if they have not yet completed.
1490 * On a blocking socket, this means that any blocking #GSocket
1491 * operation will time out after @timeout seconds of inactivity,
1492 * returning %G_IO_ERROR_TIMED_OUT.
1494 * On a non-blocking socket, calls to g_socket_condition_wait() will
1495 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1496 * created with g_socket_create_source() will trigger after
1497 * @timeout seconds of inactivity, with the requested condition
1498 * set, at which point calling g_socket_receive(), g_socket_send(),
1499 * g_socket_check_connect_result(), etc, will fail with
1500 * %G_IO_ERROR_TIMED_OUT.
1502 * If @timeout is 0 (the default), operations will never time out
1503 * on their own.
1505 * Note that if an I/O operation is interrupted by a signal, this may
1506 * cause the timeout to be reset.
1508 * Since: 2.26
1510 void
1511 g_socket_set_timeout (GSocket *socket,
1512 guint timeout)
1514 g_return_if_fail (G_IS_SOCKET (socket));
1516 if (timeout != socket->priv->timeout)
1518 socket->priv->timeout = timeout;
1519 g_object_notify (G_OBJECT (socket), "timeout");
1524 * g_socket_get_ttl:
1525 * @socket: a #GSocket.
1527 * Gets the unicast time-to-live setting on @socket; see
1528 * g_socket_set_ttl() for more details.
1530 * Returns: the time-to-live setting on @socket
1532 * Since: 2.32
1534 guint
1535 g_socket_get_ttl (GSocket *socket)
1537 GError *error = NULL;
1538 gint value;
1540 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1542 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1544 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1545 &value, &error);
1547 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1549 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1550 &value, &error);
1552 else
1553 g_return_val_if_reached (0);
1555 if (error)
1557 g_warning ("error getting unicast ttl: %s", error->message);
1558 g_error_free (error);
1559 return 0;
1562 return value;
1566 * g_socket_set_ttl:
1567 * @socket: a #GSocket.
1568 * @ttl: the time-to-live value for all unicast packets on @socket
1570 * Sets the time-to-live for outgoing unicast packets on @socket.
1571 * By default the platform-specific default value is used.
1573 * Since: 2.32
1575 void
1576 g_socket_set_ttl (GSocket *socket,
1577 guint ttl)
1579 GError *error = NULL;
1581 g_return_if_fail (G_IS_SOCKET (socket));
1583 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1585 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1586 ttl, &error);
1588 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1590 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1591 ttl, NULL);
1592 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1593 ttl, &error);
1595 else
1596 g_return_if_reached ();
1598 if (error)
1600 g_warning ("error setting unicast ttl: %s", error->message);
1601 g_error_free (error);
1602 return;
1605 g_object_notify (G_OBJECT (socket), "ttl");
1609 * g_socket_get_broadcast:
1610 * @socket: a #GSocket.
1612 * Gets the broadcast setting on @socket; if %TRUE,
1613 * it is possible to send packets to broadcast
1614 * addresses.
1616 * Returns: the broadcast setting on @socket
1618 * Since: 2.32
1620 gboolean
1621 g_socket_get_broadcast (GSocket *socket)
1623 GError *error = NULL;
1624 gint value;
1626 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1628 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1629 &value, &error))
1631 g_warning ("error getting broadcast: %s", error->message);
1632 g_error_free (error);
1633 return FALSE;
1636 return !!value;
1640 * g_socket_set_broadcast:
1641 * @socket: a #GSocket.
1642 * @broadcast: whether @socket should allow sending to broadcast
1643 * addresses
1645 * Sets whether @socket should allow sending to broadcast addresses.
1646 * This is %FALSE by default.
1648 * Since: 2.32
1650 void
1651 g_socket_set_broadcast (GSocket *socket,
1652 gboolean broadcast)
1654 GError *error = NULL;
1656 g_return_if_fail (G_IS_SOCKET (socket));
1658 broadcast = !!broadcast;
1660 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1661 broadcast, &error))
1663 g_warning ("error setting broadcast: %s", error->message);
1664 g_error_free (error);
1665 return;
1668 g_object_notify (G_OBJECT (socket), "broadcast");
1672 * g_socket_get_multicast_loopback:
1673 * @socket: a #GSocket.
1675 * Gets the multicast loopback setting on @socket; if %TRUE (the
1676 * default), outgoing multicast packets will be looped back to
1677 * multicast listeners on the same host.
1679 * Returns: the multicast loopback setting on @socket
1681 * Since: 2.32
1683 gboolean
1684 g_socket_get_multicast_loopback (GSocket *socket)
1686 GError *error = NULL;
1687 gint value;
1689 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1691 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1693 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1694 &value, &error);
1696 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1698 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1699 &value, &error);
1701 else
1702 g_return_val_if_reached (FALSE);
1704 if (error)
1706 g_warning ("error getting multicast loopback: %s", error->message);
1707 g_error_free (error);
1708 return FALSE;
1711 return !!value;
1715 * g_socket_set_multicast_loopback:
1716 * @socket: a #GSocket.
1717 * @loopback: whether @socket should receive messages sent to its
1718 * multicast groups from the local host
1720 * Sets whether outgoing multicast packets will be received by sockets
1721 * listening on that multicast address on the same host. This is %TRUE
1722 * by default.
1724 * Since: 2.32
1726 void
1727 g_socket_set_multicast_loopback (GSocket *socket,
1728 gboolean loopback)
1730 GError *error = NULL;
1732 g_return_if_fail (G_IS_SOCKET (socket));
1734 loopback = !!loopback;
1736 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1738 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1739 loopback, &error);
1741 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1743 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1744 loopback, NULL);
1745 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1746 loopback, &error);
1748 else
1749 g_return_if_reached ();
1751 if (error)
1753 g_warning ("error setting multicast loopback: %s", error->message);
1754 g_error_free (error);
1755 return;
1758 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1762 * g_socket_get_multicast_ttl:
1763 * @socket: a #GSocket.
1765 * Gets the multicast time-to-live setting on @socket; see
1766 * g_socket_set_multicast_ttl() for more details.
1768 * Returns: the multicast time-to-live setting on @socket
1770 * Since: 2.32
1772 guint
1773 g_socket_get_multicast_ttl (GSocket *socket)
1775 GError *error = NULL;
1776 gint value;
1778 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1780 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1782 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1783 &value, &error);
1785 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1787 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1788 &value, &error);
1790 else
1791 g_return_val_if_reached (FALSE);
1793 if (error)
1795 g_warning ("error getting multicast ttl: %s", error->message);
1796 g_error_free (error);
1797 return FALSE;
1800 return value;
1804 * g_socket_set_multicast_ttl:
1805 * @socket: a #GSocket.
1806 * @ttl: the time-to-live value for all multicast datagrams on @socket
1808 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1809 * By default, this is 1, meaning that multicast packets will not leave
1810 * the local network.
1812 * Since: 2.32
1814 void
1815 g_socket_set_multicast_ttl (GSocket *socket,
1816 guint ttl)
1818 GError *error = NULL;
1820 g_return_if_fail (G_IS_SOCKET (socket));
1822 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1824 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1825 ttl, &error);
1827 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1829 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1830 ttl, NULL);
1831 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1832 ttl, &error);
1834 else
1835 g_return_if_reached ();
1837 if (error)
1839 g_warning ("error setting multicast ttl: %s", error->message);
1840 g_error_free (error);
1841 return;
1844 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1848 * g_socket_get_family:
1849 * @socket: a #GSocket.
1851 * Gets the socket family of the socket.
1853 * Returns: a #GSocketFamily
1855 * Since: 2.22
1857 GSocketFamily
1858 g_socket_get_family (GSocket *socket)
1860 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1862 return socket->priv->family;
1866 * g_socket_get_socket_type:
1867 * @socket: a #GSocket.
1869 * Gets the socket type of the socket.
1871 * Returns: a #GSocketType
1873 * Since: 2.22
1875 GSocketType
1876 g_socket_get_socket_type (GSocket *socket)
1878 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1880 return socket->priv->type;
1884 * g_socket_get_protocol:
1885 * @socket: a #GSocket.
1887 * Gets the socket protocol id the socket was created with.
1888 * In case the protocol is unknown, -1 is returned.
1890 * Returns: a protocol id, or -1 if unknown
1892 * Since: 2.22
1894 GSocketProtocol
1895 g_socket_get_protocol (GSocket *socket)
1897 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1899 return socket->priv->protocol;
1903 * g_socket_get_fd:
1904 * @socket: a #GSocket.
1906 * Returns the underlying OS socket object. On unix this
1907 * is a socket file descriptor, and on Windows this is
1908 * a Winsock2 SOCKET handle. This may be useful for
1909 * doing platform specific or otherwise unusual operations
1910 * on the socket.
1912 * Returns: the file descriptor of the socket.
1914 * Since: 2.22
1917 g_socket_get_fd (GSocket *socket)
1919 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1921 return socket->priv->fd;
1925 * g_socket_get_local_address:
1926 * @socket: a #GSocket.
1927 * @error: #GError for error reporting, or %NULL to ignore.
1929 * Try to get the local address of a bound socket. This is only
1930 * useful if the socket has been bound to a local address,
1931 * either explicitly or implicitly when connecting.
1933 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1934 * Free the returned object with g_object_unref().
1936 * Since: 2.22
1938 GSocketAddress *
1939 g_socket_get_local_address (GSocket *socket,
1940 GError **error)
1942 union {
1943 struct sockaddr_storage storage;
1944 struct sockaddr sa;
1945 } buffer;
1946 guint len = sizeof (buffer);
1948 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1950 if (getsockname (socket->priv->fd, &buffer.sa, &len) < 0)
1952 int errsv = get_socket_errno ();
1953 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1954 _("could not get local address: %s"), socket_strerror (errsv));
1955 return NULL;
1958 return g_socket_address_new_from_native (&buffer.storage, len);
1962 * g_socket_get_remote_address:
1963 * @socket: a #GSocket.
1964 * @error: #GError for error reporting, or %NULL to ignore.
1966 * Try to get the remote address of a connected socket. This is only
1967 * useful for connection oriented sockets that have been connected.
1969 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1970 * Free the returned object with g_object_unref().
1972 * Since: 2.22
1974 GSocketAddress *
1975 g_socket_get_remote_address (GSocket *socket,
1976 GError **error)
1978 union {
1979 struct sockaddr_storage storage;
1980 struct sockaddr sa;
1981 } buffer;
1982 guint len = sizeof (buffer);
1984 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1986 if (socket->priv->connect_pending)
1988 if (!g_socket_check_connect_result (socket, error))
1989 return NULL;
1990 else
1991 socket->priv->connect_pending = FALSE;
1994 if (!socket->priv->remote_address)
1996 if (getpeername (socket->priv->fd, &buffer.sa, &len) < 0)
1998 int errsv = get_socket_errno ();
1999 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2000 _("could not get remote address: %s"), socket_strerror (errsv));
2001 return NULL;
2004 socket->priv->remote_address = g_socket_address_new_from_native (&buffer.storage, len);
2007 return g_object_ref (socket->priv->remote_address);
2011 * g_socket_is_connected:
2012 * @socket: a #GSocket.
2014 * Check whether the socket is connected. This is only useful for
2015 * connection-oriented sockets.
2017 * If using g_socket_shutdown(), this function will return %TRUE until the
2018 * socket has been shut down for reading and writing. If you do a non-blocking
2019 * connect, this function will not return %TRUE until after you call
2020 * g_socket_check_connect_result().
2022 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2024 * Since: 2.22
2026 gboolean
2027 g_socket_is_connected (GSocket *socket)
2029 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2031 return (socket->priv->connected_read || socket->priv->connected_write);
2035 * g_socket_listen:
2036 * @socket: a #GSocket.
2037 * @error: #GError for error reporting, or %NULL to ignore.
2039 * Marks the socket as a server socket, i.e. a socket that is used
2040 * to accept incoming requests using g_socket_accept().
2042 * Before calling this the socket must be bound to a local address using
2043 * g_socket_bind().
2045 * To set the maximum amount of outstanding clients, use
2046 * g_socket_set_listen_backlog().
2048 * Returns: %TRUE on success, %FALSE on error.
2050 * Since: 2.22
2052 gboolean
2053 g_socket_listen (GSocket *socket,
2054 GError **error)
2056 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2058 if (!check_socket (socket, error))
2059 return FALSE;
2061 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2063 int errsv = get_socket_errno ();
2065 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2066 _("could not listen: %s"), socket_strerror (errsv));
2067 return FALSE;
2070 socket->priv->listening = TRUE;
2072 return TRUE;
2076 * g_socket_bind:
2077 * @socket: a #GSocket.
2078 * @address: a #GSocketAddress specifying the local address.
2079 * @allow_reuse: whether to allow reusing this address
2080 * @error: #GError for error reporting, or %NULL to ignore.
2082 * When a socket is created it is attached to an address family, but it
2083 * doesn't have an address in this family. g_socket_bind() assigns the
2084 * address (sometimes called name) of the socket.
2086 * It is generally required to bind to a local address before you can
2087 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2088 * In certain situations, you may also want to bind a socket that will be
2089 * used to initiate connections, though this is not normally required.
2091 * If @socket is a TCP socket, then @allow_reuse controls the setting
2092 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2093 * server sockets (sockets that you will eventually call
2094 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2095 * set this flag on a server socket may cause g_socket_bind() to return
2096 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2097 * immediately restarted.)
2099 * If @socket is a UDP socket, then @allow_reuse determines whether or
2100 * not other UDP sockets can be bound to the same address at the same
2101 * time. In particular, you can have several UDP sockets bound to the
2102 * same address, and they will all receive all of the multicast and
2103 * broadcast packets sent to that address. (The behavior of unicast
2104 * UDP packets to an address with multiple listeners is not defined.)
2106 * Returns: %TRUE on success, %FALSE on error.
2108 * Since: 2.22
2110 gboolean
2111 g_socket_bind (GSocket *socket,
2112 GSocketAddress *address,
2113 gboolean reuse_address,
2114 GError **error)
2116 union {
2117 struct sockaddr_storage storage;
2118 struct sockaddr sa;
2119 } addr;
2120 gboolean so_reuseaddr;
2121 #ifdef SO_REUSEPORT
2122 gboolean so_reuseport;
2123 #endif
2125 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2127 if (!check_socket (socket, error))
2128 return FALSE;
2130 if (!g_socket_address_to_native (address, &addr.storage, sizeof addr, error))
2131 return FALSE;
2133 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2134 * sockets, but has nasty side effects we don't want for TCP
2135 * sockets.
2137 * On other platforms, we set SO_REUSEPORT, if it exists, for
2138 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2139 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2140 * the desired semantics on UDP (as it does on Linux, although
2141 * Linux has SO_REUSEPORT too as of 3.9).
2144 #ifdef G_OS_WIN32
2145 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2146 #else
2147 so_reuseaddr = !!reuse_address;
2148 #endif
2150 #ifdef SO_REUSEPORT
2151 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2152 #endif
2154 /* Ignore errors here, the only likely error is "not supported", and
2155 * this is a "best effort" thing mainly.
2157 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2158 #ifdef SO_REUSEPORT
2159 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2160 #endif
2162 if (bind (socket->priv->fd, &addr.sa,
2163 g_socket_address_get_native_size (address)) < 0)
2165 int errsv = get_socket_errno ();
2166 g_set_error (error,
2167 G_IO_ERROR, socket_io_error_from_errno (errsv),
2168 _("Error binding to address: %s"), socket_strerror (errsv));
2169 return FALSE;
2172 return TRUE;
2175 static gboolean
2176 g_socket_multicast_group_operation (GSocket *socket,
2177 GInetAddress *group,
2178 gboolean source_specific,
2179 const gchar *iface,
2180 gboolean join_group,
2181 GError **error)
2183 const guint8 *native_addr;
2184 gint optname, result;
2186 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2187 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2188 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2190 if (!check_socket (socket, error))
2191 return FALSE;
2193 native_addr = g_inet_address_to_bytes (group);
2194 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2196 #ifdef HAVE_IP_MREQN
2197 struct ip_mreqn mc_req;
2198 #else
2199 struct ip_mreq mc_req;
2200 #endif
2202 memset (&mc_req, 0, sizeof (mc_req));
2203 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2205 #ifdef HAVE_IP_MREQN
2206 if (iface)
2207 mc_req.imr_ifindex = if_nametoindex (iface);
2208 else
2209 mc_req.imr_ifindex = 0; /* Pick any. */
2210 #elif defined(G_OS_WIN32)
2211 if (iface)
2212 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2213 else
2214 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2215 #else
2216 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2217 #endif
2219 if (source_specific)
2221 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2222 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2223 #else
2224 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2225 join_group ?
2226 _("Error joining multicast group: %s") :
2227 _("Error leaving multicast group: %s"),
2228 _("No support for source-specific multicast"));
2229 return FALSE;
2230 #endif
2232 else
2233 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2234 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2235 &mc_req, sizeof (mc_req));
2237 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2239 struct ipv6_mreq mc_req_ipv6;
2241 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2242 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2243 #ifdef HAVE_IF_NAMETOINDEX
2244 if (iface)
2245 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2246 else
2247 #endif
2248 mc_req_ipv6.ipv6mr_interface = 0;
2250 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2251 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2252 &mc_req_ipv6, sizeof (mc_req_ipv6));
2254 else
2255 g_return_val_if_reached (FALSE);
2257 if (result < 0)
2259 int errsv = get_socket_errno ();
2261 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2262 join_group ?
2263 _("Error joining multicast group: %s") :
2264 _("Error leaving multicast group: %s"),
2265 socket_strerror (errsv));
2266 return FALSE;
2269 return TRUE;
2273 * g_socket_join_multicast_group:
2274 * @socket: a #GSocket.
2275 * @group: a #GInetAddress specifying the group address to join.
2276 * @iface: (nullable): Name of the interface to use, or %NULL
2277 * @source_specific: %TRUE if source-specific multicast should be used
2278 * @error: #GError for error reporting, or %NULL to ignore.
2280 * Registers @socket to receive multicast messages sent to @group.
2281 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2282 * been bound to an appropriate interface and port with
2283 * g_socket_bind().
2285 * If @iface is %NULL, the system will automatically pick an interface
2286 * to bind to based on @group.
2288 * If @source_specific is %TRUE, source-specific multicast as defined
2289 * in RFC 4604 is used. Note that on older platforms this may fail
2290 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2292 * To bind to a given source-specific multicast address, use
2293 * g_socket_join_multicast_group_ssm() instead.
2295 * Returns: %TRUE on success, %FALSE on error.
2297 * Since: 2.32
2299 gboolean
2300 g_socket_join_multicast_group (GSocket *socket,
2301 GInetAddress *group,
2302 gboolean source_specific,
2303 const gchar *iface,
2304 GError **error)
2306 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2310 * g_socket_leave_multicast_group:
2311 * @socket: a #GSocket.
2312 * @group: a #GInetAddress specifying the group address to leave.
2313 * @iface: (nullable): Interface used
2314 * @source_specific: %TRUE if source-specific multicast was used
2315 * @error: #GError for error reporting, or %NULL to ignore.
2317 * Removes @socket from the multicast group defined by @group, @iface,
2318 * and @source_specific (which must all have the same values they had
2319 * when you joined the group).
2321 * @socket remains bound to its address and port, and can still receive
2322 * unicast messages after calling this.
2324 * To unbind to a given source-specific multicast address, use
2325 * g_socket_leave_multicast_group_ssm() instead.
2327 * Returns: %TRUE on success, %FALSE on error.
2329 * Since: 2.32
2331 gboolean
2332 g_socket_leave_multicast_group (GSocket *socket,
2333 GInetAddress *group,
2334 gboolean source_specific,
2335 const gchar *iface,
2336 GError **error)
2338 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2341 static gboolean
2342 g_socket_multicast_group_operation_ssm (GSocket *socket,
2343 GInetAddress *group,
2344 GInetAddress *source_specific,
2345 const gchar *iface,
2346 gboolean join_group,
2347 GError **error)
2349 gint result;
2351 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2352 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2353 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2354 g_return_val_if_fail (iface == NULL || *iface != '\0', FALSE);
2355 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2357 if (!source_specific)
2359 return g_socket_multicast_group_operation (socket, group, FALSE, iface,
2360 join_group, error);
2363 if (!check_socket (socket, error))
2364 return FALSE;
2366 switch (g_inet_address_get_family (group))
2368 case G_SOCKET_FAMILY_INVALID:
2369 case G_SOCKET_FAMILY_UNIX:
2371 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2372 join_group ?
2373 _("Error joining multicast group: %s") :
2374 _("Error leaving multicast group: %s"),
2375 _("Unsupported socket family"));
2376 return FALSE;
2378 break;
2380 case G_SOCKET_FAMILY_IPV4:
2382 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2384 #ifdef BROKEN_IP_MREQ_SOURCE_STRUCT
2385 #define S_ADDR_FIELD(src) src.imr_interface
2386 #else
2387 #define S_ADDR_FIELD(src) src.imr_interface.s_addr
2388 #endif
2390 gint optname;
2391 struct ip_mreq_source mc_req_src;
2393 if (g_inet_address_get_family (source_specific) !=
2394 G_SOCKET_FAMILY_IPV4)
2396 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2397 join_group ?
2398 _("Error joining multicast group: %s") :
2399 _("Error leaving multicast group: %s"),
2400 _("source-specific not an IPv4 address"));
2401 return FALSE;
2404 memset (&mc_req_src, 0, sizeof (mc_req_src));
2406 /* By default use the default IPv4 multicast interface. */
2407 S_ADDR_FIELD(mc_req_src) = g_htonl (INADDR_ANY);
2409 if (iface)
2411 #if defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX)
2412 guint iface_index = if_nametoindex (iface);
2413 if (iface_index == 0)
2415 int errsv = errno;
2417 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2418 _("Interface not found: %s"), g_strerror (errsv));
2419 return FALSE;
2421 /* (0.0.0.iface_index) only works on Windows. */
2422 S_ADDR_FIELD(mc_req_src) = g_htonl (iface_index);
2423 #elif defined (HAVE_SIOCGIFADDR)
2424 int ret;
2425 struct ifreq ifr;
2426 struct sockaddr_in *iface_addr;
2427 size_t if_name_len = strlen (iface);
2429 memset (&ifr, 0, sizeof (ifr));
2431 if (if_name_len >= sizeof (ifr.ifr_name))
2433 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FILENAME_TOO_LONG,
2434 _("Interface name too long"));
2435 return FALSE;
2438 memcpy (ifr.ifr_name, iface, if_name_len);
2440 /* Get the IPv4 address of the given network interface name. */
2441 ret = ioctl (socket->priv->fd, SIOCGIFADDR, &ifr);
2442 if (ret < 0)
2444 int errsv = errno;
2446 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2447 _("Interface not found: %s"), g_strerror (errsv));
2448 return FALSE;
2451 iface_addr = (struct sockaddr_in *) &ifr.ifr_addr;
2452 S_ADDR_FIELD(mc_req_src) = iface_addr->sin_addr.s_addr;
2453 #endif /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2455 memcpy (&mc_req_src.imr_multiaddr, g_inet_address_to_bytes (group),
2456 g_inet_address_get_native_size (group));
2457 memcpy (&mc_req_src.imr_sourceaddr,
2458 g_inet_address_to_bytes (source_specific),
2459 g_inet_address_get_native_size (source_specific));
2461 optname =
2462 join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2463 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2464 &mc_req_src, sizeof (mc_req_src));
2466 #undef S_ADDR_FIELD
2468 #else
2469 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2470 join_group ?
2471 _("Error joining multicast group: %s") :
2472 _("Error leaving multicast group: %s"),
2473 _("No support for IPv4 source-specific multicast"));
2474 return FALSE;
2475 #endif /* IP_ADD_SOURCE_MEMBERSHIP */
2477 break;
2479 case G_SOCKET_FAMILY_IPV6:
2481 #ifdef MCAST_JOIN_SOURCE_GROUP
2482 gboolean res;
2483 gint optname;
2484 struct group_source_req mc_req_src;
2485 GSocketAddress *saddr_group, *saddr_source_specific;
2486 guint iface_index = 0;
2488 #if defined (HAVE_IF_NAMETOINDEX)
2489 if (iface)
2491 iface_index = if_nametoindex (iface);
2492 if (iface_index == 0)
2494 int errsv = errno;
2496 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2497 _("Interface not found: %s"), g_strerror (errsv));
2498 return FALSE;
2501 #endif /* defined (HAVE_IF_NAMETOINDEX) */
2502 mc_req_src.gsr_interface = iface_index;
2504 saddr_group = g_inet_socket_address_new (group, 0);
2505 res = g_socket_address_to_native (saddr_group, &mc_req_src.gsr_group,
2506 sizeof (mc_req_src.gsr_group),
2507 error);
2508 g_object_unref (saddr_group);
2509 if (!res)
2510 return FALSE;
2512 saddr_source_specific = g_inet_socket_address_new (source_specific, 0);
2513 res = g_socket_address_to_native (saddr_source_specific,
2514 &mc_req_src.gsr_source,
2515 sizeof (mc_req_src.gsr_source),
2516 error);
2517 g_object_unref (saddr_source_specific);
2519 if (!res)
2520 return FALSE;
2522 optname =
2523 join_group ? MCAST_JOIN_SOURCE_GROUP : MCAST_LEAVE_SOURCE_GROUP;
2524 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2525 &mc_req_src, sizeof (mc_req_src));
2526 #else
2527 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2528 join_group ?
2529 _("Error joining multicast group: %s") :
2530 _("Error leaving multicast group: %s"),
2531 _("No support for IPv6 source-specific multicast"));
2532 return FALSE;
2533 #endif /* MCAST_JOIN_SOURCE_GROUP */
2535 break;
2537 default:
2538 g_return_val_if_reached (FALSE);
2541 if (result < 0)
2543 int errsv = get_socket_errno ();
2545 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2546 join_group ?
2547 _("Error joining multicast group: %s") :
2548 _("Error leaving multicast group: %s"),
2549 socket_strerror (errsv));
2550 return FALSE;
2553 return TRUE;
2557 * g_socket_join_multicast_group_ssm:
2558 * @socket: a #GSocket.
2559 * @group: a #GInetAddress specifying the group address to join.
2560 * @source_specific: (nullable): a #GInetAddress specifying the
2561 * source-specific multicast address or %NULL to ignore.
2562 * @iface: (nullable): Name of the interface to use, or %NULL
2563 * @error: #GError for error reporting, or %NULL to ignore.
2565 * Registers @socket to receive multicast messages sent to @group.
2566 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2567 * been bound to an appropriate interface and port with
2568 * g_socket_bind().
2570 * If @iface is %NULL, the system will automatically pick an interface
2571 * to bind to based on @group.
2573 * If @source_specific is not %NULL, use source-specific multicast as
2574 * defined in RFC 4604. Note that on older platforms this may fail
2575 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2577 * Note that this function can be called multiple times for the same
2578 * @group with different @source_specific in order to receive multicast
2579 * packets from more than one source.
2581 * Returns: %TRUE on success, %FALSE on error.
2583 * Since: 2.56
2585 gboolean
2586 g_socket_join_multicast_group_ssm (GSocket *socket,
2587 GInetAddress *group,
2588 GInetAddress *source_specific,
2589 const gchar *iface,
2590 GError **error)
2592 return g_socket_multicast_group_operation_ssm (socket, group,
2593 source_specific, iface, TRUE, error);
2597 * g_socket_leave_multicast_group_ssm:
2598 * @socket: a #GSocket.
2599 * @group: a #GInetAddress specifying the group address to leave.
2600 * @source_specific: (nullable): a #GInetAddress specifying the
2601 * source-specific multicast address or %NULL to ignore.
2602 * @iface: (nullable): Name of the interface to use, or %NULL
2603 * @error: #GError for error reporting, or %NULL to ignore.
2605 * Removes @socket from the multicast group defined by @group, @iface,
2606 * and @source_specific (which must all have the same values they had
2607 * when you joined the group).
2609 * @socket remains bound to its address and port, and can still receive
2610 * unicast messages after calling this.
2612 * Returns: %TRUE on success, %FALSE on error.
2614 * Since: 2.56
2616 gboolean
2617 g_socket_leave_multicast_group_ssm (GSocket *socket,
2618 GInetAddress *group,
2619 GInetAddress *source_specific,
2620 const gchar *iface,
2621 GError **error)
2623 return g_socket_multicast_group_operation_ssm (socket, group,
2624 source_specific, iface, FALSE, error);
2628 * g_socket_speaks_ipv4:
2629 * @socket: a #GSocket
2631 * Checks if a socket is capable of speaking IPv4.
2633 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2634 * and under some combinations of circumstances IPv6 sockets are also
2635 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2636 * information.
2638 * No other types of sockets are currently considered as being capable
2639 * of speaking IPv4.
2641 * Returns: %TRUE if this socket can be used with IPv4.
2643 * Since: 2.22
2645 gboolean
2646 g_socket_speaks_ipv4 (GSocket *socket)
2648 switch (socket->priv->family)
2650 case G_SOCKET_FAMILY_IPV4:
2651 return TRUE;
2653 case G_SOCKET_FAMILY_IPV6:
2654 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2656 gint v6_only;
2658 if (!g_socket_get_option (socket,
2659 IPPROTO_IPV6, IPV6_V6ONLY,
2660 &v6_only, NULL))
2661 return FALSE;
2663 return !v6_only;
2665 #else
2666 return FALSE;
2667 #endif
2669 default:
2670 return FALSE;
2675 * g_socket_accept:
2676 * @socket: a #GSocket.
2677 * @cancellable: (nullable): a %GCancellable or %NULL
2678 * @error: #GError for error reporting, or %NULL to ignore.
2680 * Accept incoming connections on a connection-based socket. This removes
2681 * the first outstanding connection request from the listening socket and
2682 * creates a #GSocket object for it.
2684 * The @socket must be bound to a local address with g_socket_bind() and
2685 * must be listening for incoming connections (g_socket_listen()).
2687 * If there are no outstanding connections then the operation will block
2688 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2689 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2691 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2692 * Free the returned object with g_object_unref().
2694 * Since: 2.22
2696 GSocket *
2697 g_socket_accept (GSocket *socket,
2698 GCancellable *cancellable,
2699 GError **error)
2701 GSocket *new_socket;
2702 gint ret;
2704 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2706 if (!check_socket (socket, error))
2707 return NULL;
2709 if (!check_timeout (socket, error))
2710 return NULL;
2712 while (TRUE)
2714 win32_unset_event_mask (socket, FD_ACCEPT);
2716 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2718 int errsv = get_socket_errno ();
2720 if (errsv == EINTR)
2721 continue;
2723 #ifdef WSAEWOULDBLOCK
2724 if (errsv == WSAEWOULDBLOCK)
2725 #else
2726 if (errsv == EWOULDBLOCK ||
2727 errsv == EAGAIN)
2728 #endif
2730 if (socket->priv->blocking)
2732 if (!g_socket_condition_wait (socket,
2733 G_IO_IN, cancellable, error))
2734 return NULL;
2736 continue;
2740 socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2741 return NULL;
2743 break;
2746 #ifdef G_OS_WIN32
2748 /* The socket inherits the accepting sockets event mask and even object,
2749 we need to remove that */
2750 WSAEventSelect (ret, NULL, 0);
2752 #else
2754 int flags;
2756 /* We always want to set close-on-exec to protect users. If you
2757 need to so some weird inheritance to exec you can re-enable this
2758 using lower level hacks with g_socket_get_fd(). */
2759 flags = fcntl (ret, F_GETFD, 0);
2760 if (flags != -1 &&
2761 (flags & FD_CLOEXEC) == 0)
2763 flags |= FD_CLOEXEC;
2764 fcntl (ret, F_SETFD, flags);
2767 #endif
2769 new_socket = g_socket_new_from_fd (ret, error);
2770 if (new_socket == NULL)
2772 #ifdef G_OS_WIN32
2773 closesocket (ret);
2774 #else
2775 close (ret);
2776 #endif
2778 else
2779 new_socket->priv->protocol = socket->priv->protocol;
2781 return new_socket;
2785 * g_socket_connect:
2786 * @socket: a #GSocket.
2787 * @address: a #GSocketAddress specifying the remote address.
2788 * @cancellable: (nullable): a %GCancellable or %NULL
2789 * @error: #GError for error reporting, or %NULL to ignore.
2791 * Connect the socket to the specified remote address.
2793 * For connection oriented socket this generally means we attempt to make
2794 * a connection to the @address. For a connection-less socket it sets
2795 * the default address for g_socket_send() and discards all incoming datagrams
2796 * from other sources.
2798 * Generally connection oriented sockets can only connect once, but
2799 * connection-less sockets can connect multiple times to change the
2800 * default address.
2802 * If the connect call needs to do network I/O it will block, unless
2803 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2804 * and the user can be notified of the connection finishing by waiting
2805 * for the G_IO_OUT condition. The result of the connection must then be
2806 * checked with g_socket_check_connect_result().
2808 * Returns: %TRUE if connected, %FALSE on error.
2810 * Since: 2.22
2812 gboolean
2813 g_socket_connect (GSocket *socket,
2814 GSocketAddress *address,
2815 GCancellable *cancellable,
2816 GError **error)
2818 union {
2819 struct sockaddr_storage storage;
2820 struct sockaddr sa;
2821 } buffer;
2823 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2825 if (!check_socket (socket, error))
2826 return FALSE;
2828 if (!g_socket_address_to_native (address, &buffer.storage, sizeof buffer, error))
2829 return FALSE;
2831 if (socket->priv->remote_address)
2832 g_object_unref (socket->priv->remote_address);
2833 socket->priv->remote_address = g_object_ref (address);
2835 while (1)
2837 win32_unset_event_mask (socket, FD_CONNECT);
2839 if (connect (socket->priv->fd, &buffer.sa,
2840 g_socket_address_get_native_size (address)) < 0)
2842 int errsv = get_socket_errno ();
2844 if (errsv == EINTR)
2845 continue;
2847 #ifndef G_OS_WIN32
2848 if (errsv == EINPROGRESS)
2849 #else
2850 if (errsv == WSAEWOULDBLOCK)
2851 #endif
2853 if (socket->priv->blocking)
2855 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2857 if (g_socket_check_connect_result (socket, error))
2858 break;
2861 else
2863 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2864 _("Connection in progress"));
2865 socket->priv->connect_pending = TRUE;
2868 else
2869 g_set_error_literal (error, G_IO_ERROR,
2870 socket_io_error_from_errno (errsv),
2871 socket_strerror (errsv));
2873 return FALSE;
2875 break;
2878 socket->priv->connected_read = TRUE;
2879 socket->priv->connected_write = TRUE;
2881 return TRUE;
2885 * g_socket_check_connect_result:
2886 * @socket: a #GSocket
2887 * @error: #GError for error reporting, or %NULL to ignore.
2889 * Checks and resets the pending connect error for the socket.
2890 * This is used to check for errors when g_socket_connect() is
2891 * used in non-blocking mode.
2893 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2895 * Since: 2.22
2897 gboolean
2898 g_socket_check_connect_result (GSocket *socket,
2899 GError **error)
2901 int value;
2903 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2905 if (!check_socket (socket, error))
2906 return FALSE;
2908 if (!check_timeout (socket, error))
2909 return FALSE;
2911 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2913 g_prefix_error (error, _("Unable to get pending error: "));
2914 return FALSE;
2917 if (value != 0)
2919 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2920 socket_strerror (value));
2921 if (socket->priv->remote_address)
2923 g_object_unref (socket->priv->remote_address);
2924 socket->priv->remote_address = NULL;
2926 return FALSE;
2929 socket->priv->connected_read = TRUE;
2930 socket->priv->connected_write = TRUE;
2932 return TRUE;
2936 * g_socket_get_available_bytes:
2937 * @socket: a #GSocket
2939 * Get the amount of data pending in the OS input buffer, without blocking.
2941 * If @socket is a UDP or SCTP socket, this will return the size of
2942 * just the next packet, even if additional packets are buffered after
2943 * that one.
2945 * Note that on Windows, this function is rather inefficient in the
2946 * UDP case, and so if you know any plausible upper bound on the size
2947 * of the incoming packet, it is better to just do a
2948 * g_socket_receive() with a buffer of that size, rather than calling
2949 * g_socket_get_available_bytes() first and then doing a receive of
2950 * exactly the right size.
2952 * Returns: the number of bytes that can be read from the socket
2953 * without blocking or truncating, or -1 on error.
2955 * Since: 2.32
2957 gssize
2958 g_socket_get_available_bytes (GSocket *socket)
2960 #ifndef SO_NREAD
2961 const gint bufsize = 64 * 1024;
2962 static guchar *buf = NULL;
2963 #endif
2964 #ifdef G_OS_WIN32
2965 u_long avail;
2966 #else
2967 gint avail;
2968 #endif
2970 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2972 #ifdef SO_NREAD
2973 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2974 return -1;
2975 #else
2976 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2978 if (G_UNLIKELY (g_once_init_enter (&buf)))
2979 g_once_init_leave (&buf, g_malloc (bufsize));
2981 /* On datagram sockets, FIONREAD ioctl is not reliable because many
2982 * systems add internal header size to the reported size, making it
2983 * unusable for this function. */
2984 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2985 if (avail == -1)
2987 int errsv = get_socket_errno ();
2988 #ifdef G_OS_WIN32
2989 if (errsv == WSAEWOULDBLOCK)
2990 #else
2991 if (errsv == EWOULDBLOCK || errsv == EAGAIN)
2992 #endif
2993 avail = 0;
2996 else
2998 #ifdef G_OS_WIN32
2999 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
3000 #else
3001 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
3002 #endif
3003 avail = -1;
3005 #endif
3007 return avail;
3010 /* Block on a timed wait for @condition until (@start_time + @timeout).
3011 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
3013 static gboolean
3014 block_on_timeout (GSocket *socket,
3015 GIOCondition condition,
3016 gint64 timeout,
3017 gint64 start_time,
3018 GCancellable *cancellable,
3019 GError **error)
3021 gint64 wait_timeout = -1;
3023 g_return_val_if_fail (timeout != 0, TRUE);
3025 /* check if we've timed out or how much time to wait at most */
3026 if (timeout >= 0)
3028 gint64 elapsed = g_get_monotonic_time () - start_time;
3030 if (elapsed >= timeout)
3032 g_set_error_literal (error,
3033 G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3034 _("Socket I/O timed out"));
3035 return FALSE;
3038 wait_timeout = timeout - elapsed;
3041 return g_socket_condition_timed_wait (socket, condition, wait_timeout,
3042 cancellable, error);
3045 static gssize
3046 g_socket_receive_with_timeout (GSocket *socket,
3047 guint8 *buffer,
3048 gsize size,
3049 gint64 timeout,
3050 GCancellable *cancellable,
3051 GError **error)
3053 gssize ret;
3054 gint64 start_time;
3056 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3058 start_time = g_get_monotonic_time ();
3060 if (!check_socket (socket, error))
3061 return -1;
3063 if (!check_timeout (socket, error))
3064 return -1;
3066 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3067 return -1;
3069 while (1)
3071 win32_unset_event_mask (socket, FD_READ);
3073 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
3075 int errsv = get_socket_errno ();
3077 if (errsv == EINTR)
3078 continue;
3080 #ifdef WSAEWOULDBLOCK
3081 if (errsv == WSAEWOULDBLOCK)
3082 #else
3083 if (errsv == EWOULDBLOCK ||
3084 errsv == EAGAIN)
3085 #endif
3087 if (timeout != 0)
3089 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
3090 cancellable, error))
3091 return -1;
3093 continue;
3097 socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
3098 return -1;
3101 break;
3104 return ret;
3108 * g_socket_receive:
3109 * @socket: a #GSocket
3110 * @buffer: (array length=size) (element-type guint8): a buffer to
3111 * read data into (which should be at least @size bytes long).
3112 * @size: the number of bytes you want to read from the socket
3113 * @cancellable: (nullable): a %GCancellable or %NULL
3114 * @error: #GError for error reporting, or %NULL to ignore.
3116 * Receive data (up to @size bytes) from a socket. This is mainly used by
3117 * connection-oriented sockets; it is identical to g_socket_receive_from()
3118 * with @address set to %NULL.
3120 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3121 * g_socket_receive() will always read either 0 or 1 complete messages from
3122 * the socket. If the received message is too large to fit in @buffer, then
3123 * the data beyond @size bytes will be discarded, without any explicit
3124 * indication that this has occurred.
3126 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3127 * number of bytes, up to @size. If more than @size bytes have been
3128 * received, the additional data will be returned in future calls to
3129 * g_socket_receive().
3131 * If the socket is in blocking mode the call will block until there
3132 * is some data to receive, the connection is closed, or there is an
3133 * error. If there is no data available and the socket is in
3134 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3135 * returned. To be notified when data is available, wait for the
3136 * %G_IO_IN condition.
3138 * On error -1 is returned and @error is set accordingly.
3140 * Returns: Number of bytes read, or 0 if the connection was closed by
3141 * the peer, or -1 on error
3143 * Since: 2.22
3145 gssize
3146 g_socket_receive (GSocket *socket,
3147 gchar *buffer,
3148 gsize size,
3149 GCancellable *cancellable,
3150 GError **error)
3152 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3153 socket->priv->blocking ? -1 : 0,
3154 cancellable, error);
3158 * g_socket_receive_with_blocking:
3159 * @socket: a #GSocket
3160 * @buffer: (array length=size) (element-type guint8): a buffer to
3161 * read data into (which should be at least @size bytes long).
3162 * @size: the number of bytes you want to read from the socket
3163 * @blocking: whether to do blocking or non-blocking I/O
3164 * @cancellable: (nullable): a %GCancellable or %NULL
3165 * @error: #GError for error reporting, or %NULL to ignore.
3167 * This behaves exactly the same as g_socket_receive(), except that
3168 * the choice of blocking or non-blocking behavior is determined by
3169 * the @blocking argument rather than by @socket's properties.
3171 * Returns: Number of bytes read, or 0 if the connection was closed by
3172 * the peer, or -1 on error
3174 * Since: 2.26
3176 gssize
3177 g_socket_receive_with_blocking (GSocket *socket,
3178 gchar *buffer,
3179 gsize size,
3180 gboolean blocking,
3181 GCancellable *cancellable,
3182 GError **error)
3184 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3185 blocking ? -1 : 0, cancellable, error);
3189 * g_socket_receive_from:
3190 * @socket: a #GSocket
3191 * @address: (out) (optional): a pointer to a #GSocketAddress
3192 * pointer, or %NULL
3193 * @buffer: (array length=size) (element-type guint8): a buffer to
3194 * read data into (which should be at least @size bytes long).
3195 * @size: the number of bytes you want to read from the socket
3196 * @cancellable: (nullable): a %GCancellable or %NULL
3197 * @error: #GError for error reporting, or %NULL to ignore.
3199 * Receive data (up to @size bytes) from a socket.
3201 * If @address is non-%NULL then @address will be set equal to the
3202 * source address of the received packet.
3203 * @address is owned by the caller.
3205 * See g_socket_receive() for additional information.
3207 * Returns: Number of bytes read, or 0 if the connection was closed by
3208 * the peer, or -1 on error
3210 * Since: 2.22
3212 gssize
3213 g_socket_receive_from (GSocket *socket,
3214 GSocketAddress **address,
3215 gchar *buffer,
3216 gsize size,
3217 GCancellable *cancellable,
3218 GError **error)
3220 GInputVector v;
3222 v.buffer = buffer;
3223 v.size = size;
3225 return g_socket_receive_message (socket,
3226 address,
3227 &v, 1,
3228 NULL, 0, NULL,
3229 cancellable,
3230 error);
3233 /* See the comment about SIGPIPE above. */
3234 #ifdef MSG_NOSIGNAL
3235 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3236 #else
3237 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
3238 #endif
3240 static gssize
3241 g_socket_send_with_timeout (GSocket *socket,
3242 const guint8 *buffer,
3243 gsize size,
3244 gint64 timeout,
3245 GCancellable *cancellable,
3246 GError **error)
3248 gssize ret;
3249 gint64 start_time;
3251 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3253 start_time = g_get_monotonic_time ();
3255 if (!check_socket (socket, error))
3256 return -1;
3258 if (!check_timeout (socket, error))
3259 return -1;
3261 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3262 return -1;
3264 while (1)
3266 win32_unset_event_mask (socket, FD_WRITE);
3268 if ((ret = send (socket->priv->fd, (const char *)buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
3270 int errsv = get_socket_errno ();
3272 if (errsv == EINTR)
3273 continue;
3275 #ifdef WSAEWOULDBLOCK
3276 if (errsv == WSAEWOULDBLOCK)
3277 #else
3278 if (errsv == EWOULDBLOCK ||
3279 errsv == EAGAIN)
3280 #endif
3282 if (timeout != 0)
3284 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
3285 cancellable, error))
3286 return -1;
3288 continue;
3292 socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3293 return -1;
3295 break;
3298 return ret;
3302 * g_socket_send:
3303 * @socket: a #GSocket
3304 * @buffer: (array length=size) (element-type guint8): the buffer
3305 * containing the data to send.
3306 * @size: the number of bytes to send
3307 * @cancellable: (nullable): a %GCancellable or %NULL
3308 * @error: #GError for error reporting, or %NULL to ignore.
3310 * Tries to send @size bytes from @buffer on the socket. This is
3311 * mainly used by connection-oriented sockets; it is identical to
3312 * g_socket_send_to() with @address set to %NULL.
3314 * If the socket is in blocking mode the call will block until there is
3315 * space for the data in the socket queue. If there is no space available
3316 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3317 * will be returned. To be notified when space is available, wait for the
3318 * %G_IO_OUT condition. Note though that you may still receive
3319 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3320 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3321 * very common due to the way the underlying APIs work.)
3323 * On error -1 is returned and @error is set accordingly.
3325 * Returns: Number of bytes written (which may be less than @size), or -1
3326 * on error
3328 * Since: 2.22
3330 gssize
3331 g_socket_send (GSocket *socket,
3332 const gchar *buffer,
3333 gsize size,
3334 GCancellable *cancellable,
3335 GError **error)
3337 return g_socket_send_with_blocking (socket, buffer, size,
3338 socket->priv->blocking,
3339 cancellable, error);
3343 * g_socket_send_with_blocking:
3344 * @socket: a #GSocket
3345 * @buffer: (array length=size) (element-type guint8): the buffer
3346 * containing the data to send.
3347 * @size: the number of bytes to send
3348 * @blocking: whether to do blocking or non-blocking I/O
3349 * @cancellable: (nullable): a %GCancellable or %NULL
3350 * @error: #GError for error reporting, or %NULL to ignore.
3352 * This behaves exactly the same as g_socket_send(), except that
3353 * the choice of blocking or non-blocking behavior is determined by
3354 * the @blocking argument rather than by @socket's properties.
3356 * Returns: Number of bytes written (which may be less than @size), or -1
3357 * on error
3359 * Since: 2.26
3361 gssize
3362 g_socket_send_with_blocking (GSocket *socket,
3363 const gchar *buffer,
3364 gsize size,
3365 gboolean blocking,
3366 GCancellable *cancellable,
3367 GError **error)
3369 return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3370 blocking ? -1 : 0, cancellable, error);
3374 * g_socket_send_to:
3375 * @socket: a #GSocket
3376 * @address: (nullable): a #GSocketAddress, or %NULL
3377 * @buffer: (array length=size) (element-type guint8): the buffer
3378 * containing the data to send.
3379 * @size: the number of bytes to send
3380 * @cancellable: (nullable): a %GCancellable or %NULL
3381 * @error: #GError for error reporting, or %NULL to ignore.
3383 * Tries to send @size bytes from @buffer to @address. If @address is
3384 * %NULL then the message is sent to the default receiver (set by
3385 * g_socket_connect()).
3387 * See g_socket_send() for additional information.
3389 * Returns: Number of bytes written (which may be less than @size), or -1
3390 * on error
3392 * Since: 2.22
3394 gssize
3395 g_socket_send_to (GSocket *socket,
3396 GSocketAddress *address,
3397 const gchar *buffer,
3398 gsize size,
3399 GCancellable *cancellable,
3400 GError **error)
3402 GOutputVector v;
3404 v.buffer = buffer;
3405 v.size = size;
3407 return g_socket_send_message (socket,
3408 address,
3409 &v, 1,
3410 NULL, 0,
3412 cancellable,
3413 error);
3417 * g_socket_shutdown:
3418 * @socket: a #GSocket
3419 * @shutdown_read: whether to shut down the read side
3420 * @shutdown_write: whether to shut down the write side
3421 * @error: #GError for error reporting, or %NULL to ignore.
3423 * Shut down part or all of a full-duplex connection.
3425 * If @shutdown_read is %TRUE then the receiving side of the connection
3426 * is shut down, and further reading is disallowed.
3428 * If @shutdown_write is %TRUE then the sending side of the connection
3429 * is shut down, and further writing is disallowed.
3431 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3433 * One example where it is useful to shut down only one side of a connection is
3434 * graceful disconnect for TCP connections where you close the sending side,
3435 * then wait for the other side to close the connection, thus ensuring that the
3436 * other side saw all sent data.
3438 * Returns: %TRUE on success, %FALSE on error
3440 * Since: 2.22
3442 gboolean
3443 g_socket_shutdown (GSocket *socket,
3444 gboolean shutdown_read,
3445 gboolean shutdown_write,
3446 GError **error)
3448 int how;
3450 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3452 if (!check_socket (socket, error))
3453 return FALSE;
3455 /* Do nothing? */
3456 if (!shutdown_read && !shutdown_write)
3457 return TRUE;
3459 #ifndef G_OS_WIN32
3460 if (shutdown_read && shutdown_write)
3461 how = SHUT_RDWR;
3462 else if (shutdown_read)
3463 how = SHUT_RD;
3464 else
3465 how = SHUT_WR;
3466 #else
3467 if (shutdown_read && shutdown_write)
3468 how = SD_BOTH;
3469 else if (shutdown_read)
3470 how = SD_RECEIVE;
3471 else
3472 how = SD_SEND;
3473 #endif
3475 if (shutdown (socket->priv->fd, how) != 0)
3477 int errsv = get_socket_errno ();
3478 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3479 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3480 return FALSE;
3483 if (shutdown_read)
3484 socket->priv->connected_read = FALSE;
3485 if (shutdown_write)
3486 socket->priv->connected_write = FALSE;
3488 return TRUE;
3492 * g_socket_close:
3493 * @socket: a #GSocket
3494 * @error: #GError for error reporting, or %NULL to ignore.
3496 * Closes the socket, shutting down any active connection.
3498 * Closing a socket does not wait for all outstanding I/O operations
3499 * to finish, so the caller should not rely on them to be guaranteed
3500 * to complete even if the close returns with no error.
3502 * Once the socket is closed, all other operations will return
3503 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3504 * return an error.
3506 * Sockets will be automatically closed when the last reference
3507 * is dropped, but you might want to call this function to make sure
3508 * resources are released as early as possible.
3510 * Beware that due to the way that TCP works, it is possible for
3511 * recently-sent data to be lost if either you close a socket while the
3512 * %G_IO_IN condition is set, or else if the remote connection tries to
3513 * send something to you after you close the socket but before it has
3514 * finished reading all of the data you sent. There is no easy generic
3515 * way to avoid this problem; the easiest fix is to design the network
3516 * protocol such that the client will never send data "out of turn".
3517 * Another solution is for the server to half-close the connection by
3518 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3519 * and then wait for the client to notice this and close its side of the
3520 * connection, after which the server can safely call g_socket_close().
3521 * (This is what #GTcpConnection does if you call
3522 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3523 * only works if the client will close its connection after the server
3524 * does.)
3526 * Returns: %TRUE on success, %FALSE on error
3528 * Since: 2.22
3530 gboolean
3531 g_socket_close (GSocket *socket,
3532 GError **error)
3534 int res;
3536 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3538 if (socket->priv->closed)
3539 return TRUE; /* Multiple close not an error */
3541 if (!check_socket (socket, error))
3542 return FALSE;
3544 while (1)
3546 #ifdef G_OS_WIN32
3547 res = closesocket (socket->priv->fd);
3548 #else
3549 res = close (socket->priv->fd);
3550 #endif
3551 if (res == -1)
3553 int errsv = get_socket_errno ();
3555 if (errsv == EINTR)
3556 continue;
3558 g_set_error (error, G_IO_ERROR,
3559 socket_io_error_from_errno (errsv),
3560 _("Error closing socket: %s"),
3561 socket_strerror (errsv));
3562 return FALSE;
3564 break;
3567 socket->priv->fd = -1;
3568 socket->priv->connected_read = FALSE;
3569 socket->priv->connected_write = FALSE;
3570 socket->priv->closed = TRUE;
3571 if (socket->priv->remote_address)
3573 g_object_unref (socket->priv->remote_address);
3574 socket->priv->remote_address = NULL;
3577 return TRUE;
3581 * g_socket_is_closed:
3582 * @socket: a #GSocket
3584 * Checks whether a socket is closed.
3586 * Returns: %TRUE if socket is closed, %FALSE otherwise
3588 * Since: 2.22
3590 gboolean
3591 g_socket_is_closed (GSocket *socket)
3593 return socket->priv->closed;
3596 #ifdef G_OS_WIN32
3597 /* Broken source, used on errors */
3598 static gboolean
3599 broken_dispatch (GSource *source,
3600 GSourceFunc callback,
3601 gpointer user_data)
3603 return TRUE;
3606 static GSourceFuncs broken_funcs =
3608 NULL,
3609 NULL,
3610 broken_dispatch,
3611 NULL
3614 static gint
3615 network_events_for_condition (GIOCondition condition)
3617 int event_mask = 0;
3619 if (condition & G_IO_IN)
3620 event_mask |= (FD_READ | FD_ACCEPT);
3621 if (condition & G_IO_OUT)
3622 event_mask |= (FD_WRITE | FD_CONNECT);
3623 event_mask |= FD_CLOSE;
3625 return event_mask;
3628 static void
3629 ensure_event (GSocket *socket)
3631 if (socket->priv->event == WSA_INVALID_EVENT)
3632 socket->priv->event = WSACreateEvent();
3635 static void
3636 update_select_events (GSocket *socket)
3638 int event_mask;
3639 GIOCondition *ptr;
3640 GList *l;
3641 WSAEVENT event;
3643 ensure_event (socket);
3645 event_mask = 0;
3646 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3648 ptr = l->data;
3649 event_mask |= network_events_for_condition (*ptr);
3652 if (event_mask != socket->priv->selected_events)
3654 /* If no events selected, disable event so we can unset
3655 nonblocking mode */
3657 if (event_mask == 0)
3658 event = NULL;
3659 else
3660 event = socket->priv->event;
3662 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3663 socket->priv->selected_events = event_mask;
3667 static void
3668 add_condition_watch (GSocket *socket,
3669 GIOCondition *condition)
3671 g_mutex_lock (&socket->priv->win32_source_lock);
3672 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3674 socket->priv->requested_conditions =
3675 g_list_prepend (socket->priv->requested_conditions, condition);
3677 update_select_events (socket);
3678 g_mutex_unlock (&socket->priv->win32_source_lock);
3681 static void
3682 remove_condition_watch (GSocket *socket,
3683 GIOCondition *condition)
3685 g_mutex_lock (&socket->priv->win32_source_lock);
3686 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3688 socket->priv->requested_conditions =
3689 g_list_remove (socket->priv->requested_conditions, condition);
3691 update_select_events (socket);
3692 g_mutex_unlock (&socket->priv->win32_source_lock);
3695 static GIOCondition
3696 update_condition_unlocked (GSocket *socket)
3698 WSANETWORKEVENTS events;
3699 GIOCondition condition;
3701 if (WSAEnumNetworkEvents (socket->priv->fd,
3702 socket->priv->event,
3703 &events) == 0)
3705 socket->priv->current_events |= events.lNetworkEvents;
3706 if (events.lNetworkEvents & FD_WRITE &&
3707 events.iErrorCode[FD_WRITE_BIT] != 0)
3708 socket->priv->current_errors |= FD_WRITE;
3709 if (events.lNetworkEvents & FD_CONNECT &&
3710 events.iErrorCode[FD_CONNECT_BIT] != 0)
3711 socket->priv->current_errors |= FD_CONNECT;
3714 condition = 0;
3715 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3716 condition |= G_IO_IN;
3718 if (socket->priv->current_events & FD_CLOSE)
3720 int r, errsv, buffer;
3722 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3723 if (r < 0)
3724 errsv = get_socket_errno ();
3726 if (r > 0 ||
3727 (r < 0 && errsv == WSAENOTCONN))
3728 condition |= G_IO_IN;
3729 else if (r == 0 ||
3730 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3731 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3732 condition |= G_IO_HUP;
3733 else
3734 condition |= G_IO_ERR;
3737 if (socket->priv->closed)
3738 condition |= G_IO_HUP;
3740 /* Never report both G_IO_OUT and HUP, these are
3741 mutually exclusive (can't write to a closed socket) */
3742 if ((condition & G_IO_HUP) == 0 &&
3743 socket->priv->current_events & FD_WRITE)
3745 if (socket->priv->current_errors & FD_WRITE)
3746 condition |= G_IO_ERR;
3747 else
3748 condition |= G_IO_OUT;
3750 else
3752 if (socket->priv->current_events & FD_CONNECT)
3754 if (socket->priv->current_errors & FD_CONNECT)
3755 condition |= (G_IO_HUP | G_IO_ERR);
3756 else
3757 condition |= G_IO_OUT;
3761 return condition;
3764 static GIOCondition
3765 update_condition (GSocket *socket)
3767 GIOCondition res;
3768 g_mutex_lock (&socket->priv->win32_source_lock);
3769 res = update_condition_unlocked (socket);
3770 g_mutex_unlock (&socket->priv->win32_source_lock);
3771 return res;
3773 #endif
3775 typedef struct {
3776 GSource source;
3777 #ifdef G_OS_WIN32
3778 GPollFD pollfd;
3779 #else
3780 gpointer fd_tag;
3781 #endif
3782 GSocket *socket;
3783 GIOCondition condition;
3784 } GSocketSource;
3786 static gboolean
3787 socket_source_prepare (GSource *source,
3788 gint *timeout)
3790 GSocketSource *socket_source = (GSocketSource *)source;
3792 *timeout = -1;
3794 #ifdef G_OS_WIN32
3795 if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
3796 return TRUE;
3798 if (g_socket_is_closed (socket_source->socket))
3800 g_source_remove_poll (source, &socket_source->pollfd);
3801 socket_source->pollfd.revents = G_IO_NVAL;
3802 return TRUE;
3805 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3806 #else
3807 return g_socket_is_closed (socket_source->socket) && socket_source->fd_tag != NULL;
3808 #endif
3811 #ifdef G_OS_WIN32
3812 static gboolean
3813 socket_source_check_win32 (GSource *source)
3815 int timeout;
3817 return socket_source_prepare (source, &timeout);
3819 #endif
3821 static gboolean
3822 socket_source_dispatch (GSource *source,
3823 GSourceFunc callback,
3824 gpointer user_data)
3826 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3827 GSocketSource *socket_source = (GSocketSource *)source;
3828 GSocket *socket = socket_source->socket;
3829 gint64 timeout;
3830 guint events;
3831 gboolean ret;
3833 #ifdef G_OS_WIN32
3834 events = update_condition (socket_source->socket);
3835 #else
3836 if (g_socket_is_closed (socket_source->socket))
3838 if (socket_source->fd_tag)
3839 g_source_remove_unix_fd (source, socket_source->fd_tag);
3840 socket_source->fd_tag = NULL;
3841 events = G_IO_NVAL;
3843 else
3845 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3847 #endif
3849 timeout = g_source_get_ready_time (source);
3850 if (timeout >= 0 && timeout < g_source_get_time (source) &&
3851 !g_socket_is_closed (socket_source->socket))
3853 socket->priv->timed_out = TRUE;
3854 events |= (G_IO_IN | G_IO_OUT);
3857 ret = (*func) (socket, events & socket_source->condition, user_data);
3859 if (socket->priv->timeout && !g_socket_is_closed (socket_source->socket))
3860 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3861 else
3862 g_source_set_ready_time (source, -1);
3864 return ret;
3867 static void
3868 socket_source_finalize (GSource *source)
3870 GSocketSource *socket_source = (GSocketSource *)source;
3871 GSocket *socket;
3873 socket = socket_source->socket;
3875 #ifdef G_OS_WIN32
3876 remove_condition_watch (socket, &socket_source->condition);
3877 #endif
3879 g_object_unref (socket);
3882 static gboolean
3883 socket_source_closure_callback (GSocket *socket,
3884 GIOCondition condition,
3885 gpointer data)
3887 GClosure *closure = data;
3889 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3890 GValue result_value = G_VALUE_INIT;
3891 gboolean result;
3893 g_value_init (&result_value, G_TYPE_BOOLEAN);
3895 g_value_init (&params[0], G_TYPE_SOCKET);
3896 g_value_set_object (&params[0], socket);
3897 g_value_init (&params[1], G_TYPE_IO_CONDITION);
3898 g_value_set_flags (&params[1], condition);
3900 g_closure_invoke (closure, &result_value, 2, params, NULL);
3902 result = g_value_get_boolean (&result_value);
3903 g_value_unset (&result_value);
3904 g_value_unset (&params[0]);
3905 g_value_unset (&params[1]);
3907 return result;
3910 static GSourceFuncs socket_source_funcs =
3912 socket_source_prepare,
3913 #ifdef G_OS_WIN32
3914 socket_source_check_win32,
3915 #else
3916 NULL,
3917 #endif
3918 socket_source_dispatch,
3919 socket_source_finalize,
3920 (GSourceFunc)socket_source_closure_callback,
3923 static GSource *
3924 socket_source_new (GSocket *socket,
3925 GIOCondition condition,
3926 GCancellable *cancellable)
3928 GSource *source;
3929 GSocketSource *socket_source;
3931 #ifdef G_OS_WIN32
3932 ensure_event (socket);
3934 if (socket->priv->event == WSA_INVALID_EVENT)
3936 g_warning ("Failed to create WSAEvent");
3937 return g_source_new (&broken_funcs, sizeof (GSource));
3939 #endif
3941 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3943 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3944 g_source_set_name (source, "GSocket");
3945 socket_source = (GSocketSource *)source;
3947 socket_source->socket = g_object_ref (socket);
3948 socket_source->condition = condition;
3950 if (cancellable)
3952 GSource *cancellable_source;
3954 cancellable_source = g_cancellable_source_new (cancellable);
3955 g_source_add_child_source (source, cancellable_source);
3956 g_source_set_dummy_callback (cancellable_source);
3957 g_source_unref (cancellable_source);
3960 #ifdef G_OS_WIN32
3961 add_condition_watch (socket, &socket_source->condition);
3962 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3963 socket_source->pollfd.events = condition;
3964 socket_source->pollfd.revents = 0;
3965 g_source_add_poll (source, &socket_source->pollfd);
3966 #else
3967 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3968 #endif
3970 if (socket->priv->timeout)
3971 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3972 else
3973 g_source_set_ready_time (source, -1);
3975 return source;
3979 * g_socket_create_source: (skip)
3980 * @socket: a #GSocket
3981 * @condition: a #GIOCondition mask to monitor
3982 * @cancellable: (nullable): a %GCancellable or %NULL
3984 * Creates a #GSource that can be attached to a %GMainContext to monitor
3985 * for the availability of the specified @condition on the socket. The #GSource
3986 * keeps a reference to the @socket.
3988 * The callback on the source is of the #GSocketSourceFunc type.
3990 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3991 * these conditions will always be reported output if they are true.
3993 * @cancellable if not %NULL can be used to cancel the source, which will
3994 * cause the source to trigger, reporting the current condition (which
3995 * is likely 0 unless cancellation happened at the same time as a
3996 * condition change). You can check for this in the callback using
3997 * g_cancellable_is_cancelled().
3999 * If @socket has a timeout set, and it is reached before @condition
4000 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
4001 * %G_IO_OUT depending on @condition. However, @socket will have been
4002 * marked as having had a timeout, and so the next #GSocket I/O method
4003 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
4005 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
4007 * Since: 2.22
4009 GSource *
4010 g_socket_create_source (GSocket *socket,
4011 GIOCondition condition,
4012 GCancellable *cancellable)
4014 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
4016 return socket_source_new (socket, condition, cancellable);
4020 * g_socket_condition_check:
4021 * @socket: a #GSocket
4022 * @condition: a #GIOCondition mask to check
4024 * Checks on the readiness of @socket to perform operations.
4025 * The operations specified in @condition are checked for and masked
4026 * against the currently-satisfied conditions on @socket. The result
4027 * is returned.
4029 * Note that on Windows, it is possible for an operation to return
4030 * %G_IO_ERROR_WOULD_BLOCK even immediately after
4031 * g_socket_condition_check() has claimed that the socket is ready for
4032 * writing. Rather than calling g_socket_condition_check() and then
4033 * writing to the socket if it succeeds, it is generally better to
4034 * simply try writing to the socket right away, and try again later if
4035 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
4037 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
4038 * these conditions will always be set in the output if they are true.
4040 * This call never blocks.
4042 * Returns: the @GIOCondition mask of the current state
4044 * Since: 2.22
4046 GIOCondition
4047 g_socket_condition_check (GSocket *socket,
4048 GIOCondition condition)
4050 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
4052 if (!check_socket (socket, NULL))
4053 return 0;
4055 #ifdef G_OS_WIN32
4057 GIOCondition current_condition;
4059 condition |= G_IO_ERR | G_IO_HUP;
4061 add_condition_watch (socket, &condition);
4062 current_condition = update_condition (socket);
4063 remove_condition_watch (socket, &condition);
4064 return condition & current_condition;
4066 #else
4068 GPollFD poll_fd;
4069 gint result;
4070 poll_fd.fd = socket->priv->fd;
4071 poll_fd.events = condition;
4072 poll_fd.revents = 0;
4075 result = g_poll (&poll_fd, 1, 0);
4076 while (result == -1 && get_socket_errno () == EINTR);
4078 return poll_fd.revents;
4080 #endif
4084 * g_socket_condition_wait:
4085 * @socket: a #GSocket
4086 * @condition: a #GIOCondition mask to wait for
4087 * @cancellable: (nullable): a #GCancellable, or %NULL
4088 * @error: a #GError pointer, or %NULL
4090 * Waits for @condition to become true on @socket. When the condition
4091 * is met, %TRUE is returned.
4093 * If @cancellable is cancelled before the condition is met, or if the
4094 * socket has a timeout set and it is reached before the condition is
4095 * met, then %FALSE is returned and @error, if non-%NULL, is set to
4096 * the appropriate value (%G_IO_ERROR_CANCELLED or
4097 * %G_IO_ERROR_TIMED_OUT).
4099 * See also g_socket_condition_timed_wait().
4101 * Returns: %TRUE if the condition was met, %FALSE otherwise
4103 * Since: 2.22
4105 gboolean
4106 g_socket_condition_wait (GSocket *socket,
4107 GIOCondition condition,
4108 GCancellable *cancellable,
4109 GError **error)
4111 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4113 return g_socket_condition_timed_wait (socket, condition, -1,
4114 cancellable, error);
4118 * g_socket_condition_timed_wait:
4119 * @socket: a #GSocket
4120 * @condition: a #GIOCondition mask to wait for
4121 * @timeout: the maximum time (in microseconds) to wait, or -1
4122 * @cancellable: (nullable): a #GCancellable, or %NULL
4123 * @error: a #GError pointer, or %NULL
4125 * Waits for up to @timeout microseconds for @condition to become true
4126 * on @socket. If the condition is met, %TRUE is returned.
4128 * If @cancellable is cancelled before the condition is met, or if
4129 * @timeout (or the socket's #GSocket:timeout) is reached before the
4130 * condition is met, then %FALSE is returned and @error, if non-%NULL,
4131 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4132 * %G_IO_ERROR_TIMED_OUT).
4134 * If you don't want a timeout, use g_socket_condition_wait().
4135 * (Alternatively, you can pass -1 for @timeout.)
4137 * Note that although @timeout is in microseconds for consistency with
4138 * other GLib APIs, this function actually only has millisecond
4139 * resolution, and the behavior is undefined if @timeout is not an
4140 * exact number of milliseconds.
4142 * Returns: %TRUE if the condition was met, %FALSE otherwise
4144 * Since: 2.32
4146 gboolean
4147 g_socket_condition_timed_wait (GSocket *socket,
4148 GIOCondition condition,
4149 gint64 timeout,
4150 GCancellable *cancellable,
4151 GError **error)
4153 gint64 start_time;
4155 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4157 if (!check_socket (socket, error))
4158 return FALSE;
4160 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4161 return FALSE;
4163 if (socket->priv->timeout &&
4164 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
4165 timeout = (gint64) socket->priv->timeout * 1000;
4166 else if (timeout != -1)
4167 timeout = timeout / 1000;
4169 start_time = g_get_monotonic_time ();
4171 #ifdef G_OS_WIN32
4173 GIOCondition current_condition;
4174 WSAEVENT events[2];
4175 DWORD res;
4176 GPollFD cancel_fd;
4177 int num_events;
4179 /* Always check these */
4180 condition |= G_IO_ERR | G_IO_HUP;
4182 add_condition_watch (socket, &condition);
4184 num_events = 0;
4185 events[num_events++] = socket->priv->event;
4187 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
4188 events[num_events++] = (WSAEVENT)cancel_fd.fd;
4190 if (timeout == -1)
4191 timeout = WSA_INFINITE;
4193 g_mutex_lock (&socket->priv->win32_source_lock);
4194 current_condition = update_condition_unlocked (socket);
4195 while ((condition & current_condition) == 0)
4197 if (!socket->priv->waiting)
4199 socket->priv->waiting = TRUE;
4200 socket->priv->waiting_result = 0;
4201 g_mutex_unlock (&socket->priv->win32_source_lock);
4203 res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout, FALSE);
4205 g_mutex_lock (&socket->priv->win32_source_lock);
4206 socket->priv->waiting = FALSE;
4207 socket->priv->waiting_result = res;
4208 g_cond_broadcast (&socket->priv->win32_source_cond);
4210 else
4212 if (timeout != WSA_INFINITE)
4214 if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout))
4216 res = WSA_WAIT_TIMEOUT;
4217 break;
4219 else
4221 res = socket->priv->waiting_result;
4224 else
4226 g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
4227 res = socket->priv->waiting_result;
4231 if (res == WSA_WAIT_FAILED)
4233 int errsv = get_socket_errno ();
4235 g_set_error (error, G_IO_ERROR,
4236 socket_io_error_from_errno (errsv),
4237 _("Waiting for socket condition: %s"),
4238 socket_strerror (errsv));
4239 break;
4241 else if (res == WSA_WAIT_TIMEOUT)
4243 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4244 _("Socket I/O timed out"));
4245 break;
4248 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4249 break;
4251 current_condition = update_condition_unlocked (socket);
4253 if (timeout != WSA_INFINITE)
4255 timeout -= (g_get_monotonic_time () - start_time) * 1000;
4256 if (timeout < 0)
4257 timeout = 0;
4260 g_mutex_unlock (&socket->priv->win32_source_lock);
4261 remove_condition_watch (socket, &condition);
4262 if (num_events > 1)
4263 g_cancellable_release_fd (cancellable);
4265 return (condition & current_condition) != 0;
4267 #else
4269 GPollFD poll_fd[2];
4270 gint result;
4271 gint num;
4273 poll_fd[0].fd = socket->priv->fd;
4274 poll_fd[0].events = condition;
4275 num = 1;
4277 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
4278 num++;
4280 while (TRUE)
4282 int errsv;
4283 result = g_poll (poll_fd, num, timeout);
4284 errsv = errno;
4285 if (result != -1 || errsv != EINTR)
4286 break;
4288 if (timeout != -1)
4290 timeout -= (g_get_monotonic_time () - start_time) / 1000;
4291 if (timeout < 0)
4292 timeout = 0;
4296 if (num > 1)
4297 g_cancellable_release_fd (cancellable);
4299 if (result == 0)
4301 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4302 _("Socket I/O timed out"));
4303 return FALSE;
4306 return !g_cancellable_set_error_if_cancelled (cancellable, error);
4308 #endif
4311 #ifndef G_OS_WIN32
4313 /* Unfortunately these have to be macros rather than inline functions due to
4314 * using alloca(). */
4315 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4316 G_STMT_START { \
4317 const GOutputMessage *_message = (message); \
4318 const GOutputMessage *_prev_message = (prev_message); \
4319 struct msghdr *_msg = (msg); \
4320 const struct msghdr *_prev_msg = (prev_msg); \
4321 GError **_error = (error); \
4323 _msg->msg_flags = 0; \
4325 /* name */ \
4326 if (_prev_message != NULL && _prev_message->address == _message->address) \
4328 _msg->msg_name = _prev_msg->msg_name; \
4329 _msg->msg_namelen = _prev_msg->msg_namelen; \
4331 else if (_message->address != NULL) \
4333 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4334 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4335 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4336 _msg->msg_namelen, _error)) \
4337 break; \
4339 else \
4341 _msg->msg_name = NULL; \
4342 _msg->msg_namelen = 0; \
4345 /* iov */ \
4347 /* this entire expression will be evaluated at compile time */ \
4348 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4349 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4350 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4351 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4352 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4353 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4354 G_STRUCT_OFFSET (GOutputVector, size)) \
4355 /* ABI is compatible */ \
4357 _msg->msg_iov = (struct iovec *) _message->vectors; \
4358 _msg->msg_iovlen = _message->num_vectors; \
4360 else \
4361 /* ABI is incompatible */ \
4363 gint i; \
4365 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4366 for (i = 0; i < _message->num_vectors; i++) \
4368 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4369 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4371 _msg->msg_iovlen = _message->num_vectors; \
4375 /* control */ \
4377 struct cmsghdr *cmsg; \
4378 gint i; \
4380 _msg->msg_controllen = 0; \
4381 for (i = 0; i < _message->num_control_messages; i++) \
4382 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4384 if (_msg->msg_controllen == 0) \
4385 _msg->msg_control = NULL; \
4386 else \
4388 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4389 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4392 cmsg = CMSG_FIRSTHDR (_msg); \
4393 for (i = 0; i < _message->num_control_messages; i++) \
4395 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4396 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4397 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4398 g_socket_control_message_serialize (_message->control_messages[i], \
4399 CMSG_DATA (cmsg)); \
4400 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4402 g_assert (cmsg == NULL); \
4404 } G_STMT_END
4406 #define input_message_to_msghdr(message, msg) \
4407 G_STMT_START { \
4408 const GInputMessage *_message = (message); \
4409 struct msghdr *_msg = (msg); \
4411 /* name */ \
4412 if (_message->address) \
4414 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4415 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4417 else \
4419 _msg->msg_name = NULL; \
4420 _msg->msg_namelen = 0; \
4423 /* iov */ \
4424 /* this entire expression will be evaluated at compile time */ \
4425 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4426 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4427 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4428 G_STRUCT_OFFSET (GInputVector, buffer) && \
4429 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4430 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4431 G_STRUCT_OFFSET (GInputVector, size)) \
4432 /* ABI is compatible */ \
4434 _msg->msg_iov = (struct iovec *) _message->vectors; \
4435 _msg->msg_iovlen = _message->num_vectors; \
4437 else \
4438 /* ABI is incompatible */ \
4440 guint i; \
4442 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4443 for (i = 0; i < _message->num_vectors; i++) \
4445 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4446 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4448 _msg->msg_iovlen = _message->num_vectors; \
4451 /* control */ \
4452 if (_message->control_messages == NULL) \
4454 _msg->msg_controllen = 0; \
4455 _msg->msg_control = NULL; \
4457 else \
4459 _msg->msg_controllen = 2048; \
4460 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4463 /* flags */ \
4464 _msg->msg_flags = _message->flags; \
4465 } G_STMT_END
4467 static void
4468 input_message_from_msghdr (const struct msghdr *msg,
4469 GInputMessage *message,
4470 GSocket *socket)
4472 /* decode address */
4473 if (message->address != NULL)
4475 *message->address = cache_recv_address (socket, msg->msg_name,
4476 msg->msg_namelen);
4479 /* decode control messages */
4481 GPtrArray *my_messages = NULL;
4482 struct cmsghdr *cmsg;
4484 if (msg->msg_controllen >= sizeof (struct cmsghdr))
4486 g_assert (message->control_messages != NULL);
4487 for (cmsg = CMSG_FIRSTHDR (msg);
4488 cmsg != NULL;
4489 cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4491 GSocketControlMessage *control_message;
4493 control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4494 cmsg->cmsg_type,
4495 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4496 CMSG_DATA (cmsg));
4497 if (control_message == NULL)
4498 /* We've already spewed about the problem in the
4499 deserialization code, so just continue */
4500 continue;
4502 if (my_messages == NULL)
4503 my_messages = g_ptr_array_new ();
4504 g_ptr_array_add (my_messages, control_message);
4508 if (message->num_control_messages)
4509 *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4511 if (message->control_messages)
4513 if (my_messages == NULL)
4515 *message->control_messages = NULL;
4517 else
4519 g_ptr_array_add (my_messages, NULL);
4520 *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4523 else
4525 g_assert (my_messages == NULL);
4529 /* capture the flags */
4530 message->flags = msg->msg_flags;
4532 #endif
4535 * g_socket_send_message:
4536 * @socket: a #GSocket
4537 * @address: (nullable): a #GSocketAddress, or %NULL
4538 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4539 * @num_vectors: the number of elements in @vectors, or -1
4540 * @messages: (array length=num_messages) (nullable): a pointer to an
4541 * array of #GSocketControlMessages, or %NULL.
4542 * @num_messages: number of elements in @messages, or -1.
4543 * @flags: an int containing #GSocketMsgFlags flags
4544 * @cancellable: (nullable): a %GCancellable or %NULL
4545 * @error: #GError for error reporting, or %NULL to ignore.
4547 * Send data to @address on @socket. For sending multiple messages see
4548 * g_socket_send_messages(); for easier use, see
4549 * g_socket_send() and g_socket_send_to().
4551 * If @address is %NULL then the message is sent to the default receiver
4552 * (set by g_socket_connect()).
4554 * @vectors must point to an array of #GOutputVector structs and
4555 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4556 * then @vectors is assumed to be terminated by a #GOutputVector with a
4557 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4558 * that the sent data will be gathered from. Using multiple
4559 * #GOutputVectors is more memory-efficient than manually copying
4560 * data from multiple sources into a single buffer, and more
4561 * network-efficient than making multiple calls to g_socket_send().
4563 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4564 * #GSocketControlMessage instances. These correspond to the control
4565 * messages to be sent on the socket.
4566 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4567 * array.
4569 * @flags modify how the message is sent. The commonly available arguments
4570 * for this are available in the #GSocketMsgFlags enum, but the
4571 * values there are the same as the system values, and the flags
4572 * are passed in as-is, so you can pass in system-specific flags too.
4574 * If the socket is in blocking mode the call will block until there is
4575 * space for the data in the socket queue. If there is no space available
4576 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4577 * will be returned. To be notified when space is available, wait for the
4578 * %G_IO_OUT condition. Note though that you may still receive
4579 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4580 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4581 * very common due to the way the underlying APIs work.)
4583 * On error -1 is returned and @error is set accordingly.
4585 * Returns: Number of bytes written (which may be less than @size), or -1
4586 * on error
4588 * Since: 2.22
4590 gssize
4591 g_socket_send_message (GSocket *socket,
4592 GSocketAddress *address,
4593 GOutputVector *vectors,
4594 gint num_vectors,
4595 GSocketControlMessage **messages,
4596 gint num_messages,
4597 gint flags,
4598 GCancellable *cancellable,
4599 GError **error)
4601 return g_socket_send_message_with_timeout (socket, address,
4602 vectors, num_vectors,
4603 messages, num_messages, flags,
4604 socket->priv->blocking ? -1 : 0,
4605 cancellable, error);
4608 static gssize
4609 g_socket_send_message_with_timeout (GSocket *socket,
4610 GSocketAddress *address,
4611 GOutputVector *vectors,
4612 gint num_vectors,
4613 GSocketControlMessage **messages,
4614 gint num_messages,
4615 gint flags,
4616 gint64 timeout,
4617 GCancellable *cancellable,
4618 GError **error)
4620 GOutputVector one_vector;
4621 char zero;
4622 gint64 start_time;
4624 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4625 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), -1);
4626 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, -1);
4627 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4628 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4629 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4631 start_time = g_get_monotonic_time ();
4633 if (!check_socket (socket, error))
4634 return -1;
4636 if (!check_timeout (socket, error))
4637 return -1;
4639 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4640 return -1;
4642 if (num_vectors == -1)
4644 for (num_vectors = 0;
4645 vectors[num_vectors].buffer != NULL;
4646 num_vectors++)
4650 if (num_messages == -1)
4652 for (num_messages = 0;
4653 messages != NULL && messages[num_messages] != NULL;
4654 num_messages++)
4658 if (num_vectors == 0)
4660 zero = '\0';
4662 one_vector.buffer = &zero;
4663 one_vector.size = 1;
4664 num_vectors = 1;
4665 vectors = &one_vector;
4668 #ifndef G_OS_WIN32
4670 GOutputMessage output_message;
4671 struct msghdr msg;
4672 gssize result;
4673 GError *child_error = NULL;
4675 output_message.address = address;
4676 output_message.vectors = vectors;
4677 output_message.num_vectors = num_vectors;
4678 output_message.bytes_sent = 0;
4679 output_message.control_messages = messages;
4680 output_message.num_control_messages = num_messages;
4682 output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4684 if (child_error != NULL)
4686 g_propagate_error (error, child_error);
4687 return -1;
4690 while (1)
4692 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4693 if (result < 0)
4695 int errsv = get_socket_errno ();
4697 if (errsv == EINTR)
4698 continue;
4700 if (timeout != 0 &&
4701 (errsv == EWOULDBLOCK ||
4702 errsv == EAGAIN))
4704 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
4705 cancellable, error))
4706 return -1;
4708 continue;
4711 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4712 return -1;
4714 break;
4717 return result;
4719 #else
4721 struct sockaddr_storage addr;
4722 guint addrlen;
4723 DWORD bytes_sent;
4724 int result;
4725 WSABUF *bufs;
4726 gint i;
4728 /* Win32 doesn't support control messages.
4729 Actually this is possible for raw and datagram sockets
4730 via WSASendMessage on Vista or later, but that doesn't
4731 seem very useful */
4732 if (num_messages != 0)
4734 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4735 _("GSocketControlMessage not supported on Windows"));
4736 return -1;
4739 /* iov */
4740 bufs = g_newa (WSABUF, num_vectors);
4741 for (i = 0; i < num_vectors; i++)
4743 bufs[i].buf = (char *)vectors[i].buffer;
4744 bufs[i].len = (gulong)vectors[i].size;
4747 /* name */
4748 addrlen = 0; /* Avoid warning */
4749 if (address)
4751 addrlen = g_socket_address_get_native_size (address);
4752 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
4753 return -1;
4756 while (1)
4758 win32_unset_event_mask (socket, FD_WRITE);
4760 if (address)
4761 result = WSASendTo (socket->priv->fd,
4762 bufs, num_vectors,
4763 &bytes_sent, flags,
4764 (const struct sockaddr *)&addr, addrlen,
4765 NULL, NULL);
4766 else
4767 result = WSASend (socket->priv->fd,
4768 bufs, num_vectors,
4769 &bytes_sent, flags,
4770 NULL, NULL);
4772 if (result != 0)
4774 int errsv = get_socket_errno ();
4776 if (errsv == WSAEINTR)
4777 continue;
4779 if (errsv == WSAEWOULDBLOCK)
4781 if (timeout != 0)
4783 if (!block_on_timeout (socket, G_IO_OUT, timeout,
4784 start_time, cancellable, error))
4785 return -1;
4787 continue;
4791 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4792 return -1;
4794 break;
4797 return bytes_sent;
4799 #endif
4803 * g_socket_send_messages:
4804 * @socket: a #GSocket
4805 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4806 * @num_messages: the number of elements in @messages
4807 * @flags: an int containing #GSocketMsgFlags flags
4808 * @cancellable: (nullable): a %GCancellable or %NULL
4809 * @error: #GError for error reporting, or %NULL to ignore.
4811 * Send multiple data messages from @socket in one go. This is the most
4812 * complicated and fully-featured version of this call. For easier use, see
4813 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4815 * @messages must point to an array of #GOutputMessage structs and
4816 * @num_messages must be the length of this array. Each #GOutputMessage
4817 * contains an address to send the data to, and a pointer to an array of
4818 * #GOutputVector structs to describe the buffers that the data to be sent
4819 * for each message will be gathered from. Using multiple #GOutputVectors is
4820 * more memory-efficient than manually copying data from multiple sources
4821 * into a single buffer, and more network-efficient than making multiple
4822 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4823 * overhead of making a lot of syscalls in scenarios where a lot of data
4824 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4825 * or where the same data needs to be sent to multiple recipients.
4827 * @flags modify how the message is sent. The commonly available arguments
4828 * for this are available in the #GSocketMsgFlags enum, but the
4829 * values there are the same as the system values, and the flags
4830 * are passed in as-is, so you can pass in system-specific flags too.
4832 * If the socket is in blocking mode the call will block until there is
4833 * space for all the data in the socket queue. If there is no space available
4834 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4835 * will be returned if no data was written at all, otherwise the number of
4836 * messages sent will be returned. To be notified when space is available,
4837 * wait for the %G_IO_OUT condition. Note though that you may still receive
4838 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4839 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4840 * very common due to the way the underlying APIs work.)
4842 * On error -1 is returned and @error is set accordingly. An error will only
4843 * be returned if zero messages could be sent; otherwise the number of messages
4844 * successfully sent before the error will be returned.
4846 * Returns: number of messages sent, or -1 on error. Note that the number of
4847 * messages sent may be smaller than @num_messages if the socket is
4848 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4849 * in which case the caller may re-try to send the remaining messages.
4851 * Since: 2.44
4853 gint
4854 g_socket_send_messages (GSocket *socket,
4855 GOutputMessage *messages,
4856 guint num_messages,
4857 gint flags,
4858 GCancellable *cancellable,
4859 GError **error)
4861 return g_socket_send_messages_with_timeout (socket, messages, num_messages,
4862 flags,
4863 socket->priv->blocking ? -1 : 0,
4864 cancellable, error);
4867 static gint
4868 g_socket_send_messages_with_timeout (GSocket *socket,
4869 GOutputMessage *messages,
4870 guint num_messages,
4871 gint flags,
4872 gint64 timeout,
4873 GCancellable *cancellable,
4874 GError **error)
4876 gint64 start_time;
4878 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4879 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4880 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4881 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4883 start_time = g_get_monotonic_time ();
4885 if (!check_socket (socket, error))
4886 return -1;
4888 if (!check_timeout (socket, error))
4889 return -1;
4891 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4892 return -1;
4894 if (num_messages == 0)
4895 return 0;
4897 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4899 struct mmsghdr *msgvec;
4900 gint i, num_sent;
4902 #ifdef UIO_MAXIOV
4903 #define MAX_NUM_MESSAGES UIO_MAXIOV
4904 #else
4905 #define MAX_NUM_MESSAGES 1024
4906 #endif
4908 if (num_messages > MAX_NUM_MESSAGES)
4909 num_messages = MAX_NUM_MESSAGES;
4911 msgvec = g_newa (struct mmsghdr, num_messages);
4913 for (i = 0; i < num_messages; ++i)
4915 GOutputMessage *msg = &messages[i];
4916 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
4917 GError *child_error = NULL;
4919 msgvec[i].msg_len = 0;
4921 output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
4922 msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
4923 &child_error);
4925 if (child_error != NULL)
4927 g_propagate_error (error, child_error);
4928 return -1;
4932 for (num_sent = 0; num_sent < num_messages;)
4934 gint ret;
4936 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
4937 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4939 if (ret < 0)
4941 int errsv = get_socket_errno ();
4943 if (errsv == EINTR)
4944 continue;
4946 if (timeout != 0 &&
4947 (errsv == EWOULDBLOCK ||
4948 errsv == EAGAIN))
4950 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
4951 cancellable, error))
4953 if (num_sent > 0)
4955 g_clear_error (error);
4956 break;
4959 return -1;
4962 continue;
4965 /* If any messages were successfully sent, do not error. */
4966 if (num_sent > 0)
4967 break;
4969 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4971 return -1;
4974 num_sent += ret;
4977 for (i = 0; i < num_sent; ++i)
4978 messages[i].bytes_sent = msgvec[i].msg_len;
4980 return num_sent;
4982 #else
4984 gssize result;
4985 gint i;
4986 gint64 wait_timeout;
4988 wait_timeout = timeout;
4990 for (i = 0; i < num_messages; ++i)
4992 GOutputMessage *msg = &messages[i];
4993 GError *msg_error = NULL;
4995 result = g_socket_send_message_with_timeout (socket, msg->address,
4996 msg->vectors,
4997 msg->num_vectors,
4998 msg->control_messages,
4999 msg->num_control_messages,
5000 flags, wait_timeout,
5001 cancellable, &msg_error);
5003 /* check if we've timed out or how much time to wait at most */
5004 if (timeout > 0)
5006 gint64 elapsed = g_get_monotonic_time () - start_time;
5007 wait_timeout = MAX (timeout - elapsed, 1);
5010 if (result < 0)
5012 /* if we couldn't send all messages, just return how many we did
5013 * manage to send, provided we managed to send at least one */
5014 if (i > 0)
5016 g_error_free (msg_error);
5017 return i;
5019 else
5021 g_propagate_error (error, msg_error);
5022 return -1;
5026 msg->bytes_sent = result;
5029 return i;
5031 #endif
5034 static GSocketAddress *
5035 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
5037 GSocketAddress *saddr;
5038 gint i;
5039 guint64 oldest_time = G_MAXUINT64;
5040 gint oldest_index = 0;
5042 if (native_len <= 0)
5043 return NULL;
5045 saddr = NULL;
5046 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
5048 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
5049 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
5050 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
5052 if (!tmp)
5053 continue;
5055 if (tmp_native_len != native_len)
5056 continue;
5058 if (memcmp (tmp_native, native, native_len) == 0)
5060 saddr = g_object_ref (tmp);
5061 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
5062 return saddr;
5065 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
5067 oldest_time = socket->priv->recv_addr_cache[i].last_used;
5068 oldest_index = i;
5072 saddr = g_socket_address_new_from_native (native, native_len);
5074 if (socket->priv->recv_addr_cache[oldest_index].addr)
5076 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
5077 g_free (socket->priv->recv_addr_cache[oldest_index].native);
5080 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
5081 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
5082 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
5083 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
5085 return saddr;
5088 static gssize
5089 g_socket_receive_message_with_timeout (GSocket *socket,
5090 GSocketAddress **address,
5091 GInputVector *vectors,
5092 gint num_vectors,
5093 GSocketControlMessage ***messages,
5094 gint *num_messages,
5095 gint *flags,
5096 gint64 timeout,
5097 GCancellable *cancellable,
5098 GError **error)
5100 GInputVector one_vector;
5101 char one_byte;
5102 gint64 start_time;
5104 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5106 start_time = g_get_monotonic_time ();
5108 if (!check_socket (socket, error))
5109 return -1;
5111 if (!check_timeout (socket, error))
5112 return -1;
5114 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5115 return -1;
5117 if (num_vectors == -1)
5119 for (num_vectors = 0;
5120 vectors[num_vectors].buffer != NULL;
5121 num_vectors++)
5125 if (num_vectors == 0)
5127 one_vector.buffer = &one_byte;
5128 one_vector.size = 1;
5129 num_vectors = 1;
5130 vectors = &one_vector;
5133 #ifndef G_OS_WIN32
5135 GInputMessage input_message;
5136 struct msghdr msg;
5137 gssize result;
5139 input_message.address = address;
5140 input_message.vectors = vectors;
5141 input_message.num_vectors = num_vectors;
5142 input_message.bytes_received = 0;
5143 input_message.flags = (flags != NULL) ? *flags : 0;
5144 input_message.control_messages = messages;
5145 input_message.num_control_messages = (guint *) num_messages;
5147 /* We always set the close-on-exec flag so we don't leak file
5148 * descriptors into child processes. Note that gunixfdmessage.c
5149 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5151 #ifdef MSG_CMSG_CLOEXEC
5152 input_message.flags |= MSG_CMSG_CLOEXEC;
5153 #endif
5155 input_message_to_msghdr (&input_message, &msg);
5157 /* do it */
5158 while (1)
5160 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5161 #ifdef MSG_CMSG_CLOEXEC
5162 if (result < 0 && get_socket_errno () == EINVAL)
5164 /* We must be running on an old kernel. Call without the flag. */
5165 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
5166 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5168 #endif
5170 if (result < 0)
5172 int errsv = get_socket_errno ();
5174 if (errsv == EINTR)
5175 continue;
5177 if (timeout != 0 &&
5178 (errsv == EWOULDBLOCK ||
5179 errsv == EAGAIN))
5181 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
5182 cancellable, error))
5183 return -1;
5185 continue;
5188 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5189 return -1;
5191 break;
5194 input_message_from_msghdr (&msg, &input_message, socket);
5196 if (flags != NULL)
5197 *flags = input_message.flags;
5199 return result;
5201 #else
5203 struct sockaddr_storage addr;
5204 int addrlen;
5205 DWORD bytes_received;
5206 DWORD win_flags;
5207 int result;
5208 WSABUF *bufs;
5209 gint i;
5211 /* iov */
5212 bufs = g_newa (WSABUF, num_vectors);
5213 for (i = 0; i < num_vectors; i++)
5215 bufs[i].buf = (char *)vectors[i].buffer;
5216 bufs[i].len = (gulong)vectors[i].size;
5219 /* flags */
5220 if (flags != NULL)
5221 win_flags = *flags;
5222 else
5223 win_flags = 0;
5225 /* do it */
5226 while (1)
5228 win32_unset_event_mask (socket, FD_READ);
5230 addrlen = sizeof addr;
5231 if (address)
5232 result = WSARecvFrom (socket->priv->fd,
5233 bufs, num_vectors,
5234 &bytes_received, &win_flags,
5235 (struct sockaddr *)&addr, &addrlen,
5236 NULL, NULL);
5237 else
5238 result = WSARecv (socket->priv->fd,
5239 bufs, num_vectors,
5240 &bytes_received, &win_flags,
5241 NULL, NULL);
5242 if (result != 0)
5244 int errsv = get_socket_errno ();
5246 if (errsv == WSAEINTR)
5247 continue;
5249 if (errsv == WSAEWOULDBLOCK)
5251 if (timeout != 0)
5253 if (!block_on_timeout (socket, G_IO_IN, timeout,
5254 start_time, cancellable, error))
5255 return -1;
5257 continue;
5261 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5262 return -1;
5264 break;
5267 /* decode address */
5268 if (address != NULL)
5270 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
5273 /* capture the flags */
5274 if (flags != NULL)
5275 *flags = win_flags;
5277 if (messages != NULL)
5278 *messages = NULL;
5279 if (num_messages != NULL)
5280 *num_messages = 0;
5282 return bytes_received;
5284 #endif
5288 * g_socket_receive_messages:
5289 * @socket: a #GSocket
5290 * @messages: (array length=num_messages): an array of #GInputMessage structs
5291 * @num_messages: the number of elements in @messages
5292 * @flags: an int containing #GSocketMsgFlags flags for the overall operation
5293 * @cancellable: (nullable): a %GCancellable or %NULL
5294 * @error: #GError for error reporting, or %NULL to ignore
5296 * Receive multiple data messages from @socket in one go. This is the most
5297 * complicated and fully-featured version of this call. For easier use, see
5298 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5300 * @messages must point to an array of #GInputMessage structs and
5301 * @num_messages must be the length of this array. Each #GInputMessage
5302 * contains a pointer to an array of #GInputVector structs describing the
5303 * buffers that the data received in each message will be written to. Using
5304 * multiple #GInputVectors is more memory-efficient than manually copying data
5305 * out of a single buffer to multiple sources, and more system-call-efficient
5306 * than making multiple calls to g_socket_receive(), such as in scenarios where
5307 * a lot of data packets need to be received (e.g. high-bandwidth video
5308 * streaming over RTP/UDP).
5310 * @flags modify how all messages are received. The commonly available
5311 * arguments for this are available in the #GSocketMsgFlags enum, but the
5312 * values there are the same as the system values, and the flags
5313 * are passed in as-is, so you can pass in system-specific flags too. These
5314 * flags affect the overall receive operation. Flags affecting individual
5315 * messages are returned in #GInputMessage.flags.
5317 * The other members of #GInputMessage are treated as described in its
5318 * documentation.
5320 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5321 * been received, or the end of the stream is reached.
5323 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5324 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5325 * operating system to be received.
5327 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5328 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5329 * @num_messages are returned. (Note: This is effectively the
5330 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5332 * To be notified when messages are available, wait for the
5333 * %G_IO_IN condition. Note though that you may still receive
5334 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5335 * previously notified of a %G_IO_IN condition.
5337 * If the remote peer closes the connection, any messages queued in the
5338 * operating system will be returned, and subsequent calls to
5339 * g_socket_receive_messages() will return 0 (with no error set).
5341 * On error -1 is returned and @error is set accordingly. An error will only
5342 * be returned if zero messages could be received; otherwise the number of
5343 * messages successfully received before the error will be returned.
5345 * Returns: number of messages received, or -1 on error. Note that the number
5346 * of messages received may be smaller than @num_messages if in non-blocking
5347 * mode, if the peer closed the connection, or if @num_messages
5348 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5349 * to receive the remaining messages.
5351 * Since: 2.48
5353 gint
5354 g_socket_receive_messages (GSocket *socket,
5355 GInputMessage *messages,
5356 guint num_messages,
5357 gint flags,
5358 GCancellable *cancellable,
5359 GError **error)
5361 if (!check_socket (socket, error) ||
5362 !check_timeout (socket, error))
5363 return -1;
5365 return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5366 flags,
5367 socket->priv->blocking ? -1 : 0,
5368 cancellable, error);
5371 static gint
5372 g_socket_receive_messages_with_timeout (GSocket *socket,
5373 GInputMessage *messages,
5374 guint num_messages,
5375 gint flags,
5376 gint64 timeout,
5377 GCancellable *cancellable,
5378 GError **error)
5380 gint64 start_time;
5382 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5383 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5384 g_return_val_if_fail (cancellable == NULL ||
5385 G_IS_CANCELLABLE (cancellable), -1);
5386 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5388 start_time = g_get_monotonic_time ();
5390 if (!check_socket (socket, error))
5391 return -1;
5393 if (!check_timeout (socket, error))
5394 return -1;
5396 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5397 return -1;
5399 if (num_messages == 0)
5400 return 0;
5402 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5404 struct mmsghdr *msgvec;
5405 guint i, num_received;
5407 #ifdef UIO_MAXIOV
5408 #define MAX_NUM_MESSAGES UIO_MAXIOV
5409 #else
5410 #define MAX_NUM_MESSAGES 1024
5411 #endif
5413 if (num_messages > MAX_NUM_MESSAGES)
5414 num_messages = MAX_NUM_MESSAGES;
5416 msgvec = g_newa (struct mmsghdr, num_messages);
5418 for (i = 0; i < num_messages; ++i)
5420 GInputMessage *msg = &messages[i];
5421 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5423 input_message_to_msghdr (msg, msg_hdr);
5424 msgvec[i].msg_len = 0;
5427 /* We always set the close-on-exec flag so we don't leak file
5428 * descriptors into child processes. Note that gunixfdmessage.c
5429 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5431 #ifdef MSG_CMSG_CLOEXEC
5432 flags |= MSG_CMSG_CLOEXEC;
5433 #endif
5435 for (num_received = 0; num_received < num_messages;)
5437 gint ret;
5439 /* We operate in non-blocking mode and handle the timeout ourselves. */
5440 ret = recvmmsg (socket->priv->fd,
5441 msgvec + num_received,
5442 num_messages - num_received,
5443 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5444 #ifdef MSG_CMSG_CLOEXEC
5445 if (ret < 0 && get_socket_errno () == EINVAL)
5447 /* We must be running on an old kernel. Call without the flag. */
5448 flags &= ~(MSG_CMSG_CLOEXEC);
5449 ret = recvmmsg (socket->priv->fd,
5450 msgvec + num_received,
5451 num_messages - num_received,
5452 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5454 #endif
5456 if (ret < 0)
5458 int errsv = get_socket_errno ();
5460 if (errsv == EINTR)
5461 continue;
5463 if (timeout != 0 &&
5464 (errsv == EWOULDBLOCK ||
5465 errsv == EAGAIN))
5467 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
5468 cancellable, error))
5470 if (num_received > 0)
5472 g_clear_error (error);
5473 break;
5476 return -1;
5479 continue;
5482 /* If any messages were successfully received, do not error. */
5483 if (num_received > 0)
5484 break;
5486 socket_set_error_lazy (error, errsv,
5487 _("Error receiving message: %s"));
5489 return -1;
5491 else if (ret == 0)
5493 /* EOS. */
5494 break;
5497 num_received += ret;
5500 for (i = 0; i < num_received; ++i)
5502 input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5503 messages[i].bytes_received = msgvec[i].msg_len;
5506 return num_received;
5508 #else
5510 guint i;
5511 gint64 wait_timeout;
5513 wait_timeout = timeout;
5515 for (i = 0; i < num_messages; i++)
5517 GInputMessage *msg = &messages[i];
5518 gssize len;
5519 GError *msg_error = NULL;
5521 msg->flags = flags; /* in-out parameter */
5523 len = g_socket_receive_message_with_timeout (socket,
5524 msg->address,
5525 msg->vectors,
5526 msg->num_vectors,
5527 msg->control_messages,
5528 (gint *) msg->num_control_messages,
5529 &msg->flags,
5530 wait_timeout,
5531 cancellable,
5532 &msg_error);
5534 /* check if we've timed out or how much time to wait at most */
5535 if (timeout > 0)
5537 gint64 elapsed = g_get_monotonic_time () - start_time;
5538 wait_timeout = MAX (timeout - elapsed, 1);
5541 if (len >= 0)
5542 msg->bytes_received = len;
5544 if (i != 0 &&
5545 (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5546 g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5548 g_clear_error (&msg_error);
5549 break;
5552 if (msg_error != NULL)
5554 g_propagate_error (error, msg_error);
5555 return -1;
5558 if (len == 0)
5559 break;
5562 return i;
5564 #endif
5568 * g_socket_receive_message:
5569 * @socket: a #GSocket
5570 * @address: (out) (optional): a pointer to a #GSocketAddress
5571 * pointer, or %NULL
5572 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5573 * @num_vectors: the number of elements in @vectors, or -1
5574 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5575 * which may be filled with an array of #GSocketControlMessages, or %NULL
5576 * @num_messages: (out): a pointer which will be filled with the number of
5577 * elements in @messages, or %NULL
5578 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags
5579 * @cancellable: a %GCancellable or %NULL
5580 * @error: a #GError pointer, or %NULL
5582 * Receive data from a socket. For receiving multiple messages, see
5583 * g_socket_receive_messages(); for easier use, see
5584 * g_socket_receive() and g_socket_receive_from().
5586 * If @address is non-%NULL then @address will be set equal to the
5587 * source address of the received packet.
5588 * @address is owned by the caller.
5590 * @vector must point to an array of #GInputVector structs and
5591 * @num_vectors must be the length of this array. These structs
5592 * describe the buffers that received data will be scattered into.
5593 * If @num_vectors is -1, then @vectors is assumed to be terminated
5594 * by a #GInputVector with a %NULL buffer pointer.
5596 * As a special case, if @num_vectors is 0 (in which case, @vectors
5597 * may of course be %NULL), then a single byte is received and
5598 * discarded. This is to facilitate the common practice of sending a
5599 * single '\0' byte for the purposes of transferring ancillary data.
5601 * @messages, if non-%NULL, will be set to point to a newly-allocated
5602 * array of #GSocketControlMessage instances or %NULL if no such
5603 * messages was received. These correspond to the control messages
5604 * received from the kernel, one #GSocketControlMessage per message
5605 * from the kernel. This array is %NULL-terminated and must be freed
5606 * by the caller using g_free() after calling g_object_unref() on each
5607 * element. If @messages is %NULL, any control messages received will
5608 * be discarded.
5610 * @num_messages, if non-%NULL, will be set to the number of control
5611 * messages received.
5613 * If both @messages and @num_messages are non-%NULL, then
5614 * @num_messages gives the number of #GSocketControlMessage instances
5615 * in @messages (ie: not including the %NULL terminator).
5617 * @flags is an in/out parameter. The commonly available arguments
5618 * for this are available in the #GSocketMsgFlags enum, but the
5619 * values there are the same as the system values, and the flags
5620 * are passed in as-is, so you can pass in system-specific flags too
5621 * (and g_socket_receive_message() may pass system-specific flags out).
5622 * Flags passed in to the parameter affect the receive operation; flags returned
5623 * out of it are relevant to the specific returned message.
5625 * As with g_socket_receive(), data may be discarded if @socket is
5626 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5627 * provide enough buffer space to read a complete message. You can pass
5628 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5629 * removing it from the receive queue, but there is no portable way to find
5630 * out the length of the message other than by reading it into a
5631 * sufficiently-large buffer.
5633 * If the socket is in blocking mode the call will block until there
5634 * is some data to receive, the connection is closed, or there is an
5635 * error. If there is no data available and the socket is in
5636 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5637 * returned. To be notified when data is available, wait for the
5638 * %G_IO_IN condition.
5640 * On error -1 is returned and @error is set accordingly.
5642 * Returns: Number of bytes read, or 0 if the connection was closed by
5643 * the peer, or -1 on error
5645 * Since: 2.22
5647 gssize
5648 g_socket_receive_message (GSocket *socket,
5649 GSocketAddress **address,
5650 GInputVector *vectors,
5651 gint num_vectors,
5652 GSocketControlMessage ***messages,
5653 gint *num_messages,
5654 gint *flags,
5655 GCancellable *cancellable,
5656 GError **error)
5658 return g_socket_receive_message_with_timeout (socket, address, vectors,
5659 num_vectors, messages,
5660 num_messages, flags,
5661 socket->priv->blocking ? -1 : 0,
5662 cancellable, error);
5666 * g_socket_get_credentials:
5667 * @socket: a #GSocket.
5668 * @error: #GError for error reporting, or %NULL to ignore.
5670 * Returns the credentials of the foreign process connected to this
5671 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5672 * sockets).
5674 * If this operation isn't supported on the OS, the method fails with
5675 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5676 * by reading the %SO_PEERCRED option on the underlying socket.
5678 * Other ways to obtain credentials from a foreign peer includes the
5679 * #GUnixCredentialsMessage type and
5680 * g_unix_connection_send_credentials() /
5681 * g_unix_connection_receive_credentials() functions.
5683 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5684 * that must be freed with g_object_unref().
5686 * Since: 2.26
5688 GCredentials *
5689 g_socket_get_credentials (GSocket *socket,
5690 GError **error)
5692 GCredentials *ret;
5694 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
5695 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5697 ret = NULL;
5699 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5701 #ifdef SO_PEERCRED
5703 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
5704 socklen_t optlen = sizeof (native_creds_buf);
5706 if (getsockopt (socket->priv->fd,
5707 SOL_SOCKET,
5708 SO_PEERCRED,
5709 native_creds_buf,
5710 &optlen) == 0)
5712 ret = g_credentials_new ();
5713 g_credentials_set_native (ret,
5714 G_CREDENTIALS_NATIVE_TYPE,
5715 native_creds_buf);
5718 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5720 struct unpcbid cred;
5721 socklen_t optlen = sizeof (cred);
5723 if (getsockopt (socket->priv->fd,
5725 LOCAL_PEEREID,
5726 &cred,
5727 &optlen) == 0)
5729 ret = g_credentials_new ();
5730 g_credentials_set_native (ret,
5731 G_CREDENTIALS_NATIVE_TYPE,
5732 &cred);
5735 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
5737 ucred_t *ucred = NULL;
5739 if (getpeerucred (socket->priv->fd, &ucred) == 0)
5741 ret = g_credentials_new ();
5742 g_credentials_set_native (ret,
5743 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
5744 ucred);
5745 ucred_free (ucred);
5748 #else
5749 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
5750 #endif
5752 if (!ret)
5754 int errsv = get_socket_errno ();
5756 g_set_error (error,
5757 G_IO_ERROR,
5758 socket_io_error_from_errno (errsv),
5759 _("Unable to read socket credentials: %s"),
5760 socket_strerror (errsv));
5763 #else
5765 g_set_error_literal (error,
5766 G_IO_ERROR,
5767 G_IO_ERROR_NOT_SUPPORTED,
5768 _("g_socket_get_credentials not implemented for this OS"));
5769 #endif
5771 return ret;
5775 * g_socket_get_option:
5776 * @socket: a #GSocket
5777 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5778 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5779 * @value: (out): return location for the option value
5780 * @error: #GError for error reporting, or %NULL to ignore.
5782 * Gets the value of an integer-valued option on @socket, as with
5783 * getsockopt(). (If you need to fetch a non-integer-valued option,
5784 * you will need to call getsockopt() directly.)
5786 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5787 * header pulls in system headers that will define most of the
5788 * standard/portable socket options. For unusual socket protocols or
5789 * platform-dependent options, you may need to include additional
5790 * headers.
5792 * Note that even for socket options that are a single byte in size,
5793 * @value is still a pointer to a #gint variable, not a #guchar;
5794 * g_socket_get_option() will handle the conversion internally.
5796 * Returns: success or failure. On failure, @error will be set, and
5797 * the system error value (`errno` or WSAGetLastError()) will still
5798 * be set to the result of the getsockopt() call.
5800 * Since: 2.36
5802 gboolean
5803 g_socket_get_option (GSocket *socket,
5804 gint level,
5805 gint optname,
5806 gint *value,
5807 GError **error)
5809 guint size;
5811 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5813 *value = 0;
5814 size = sizeof (gint);
5815 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
5817 int errsv = get_socket_errno ();
5819 g_set_error_literal (error,
5820 G_IO_ERROR,
5821 socket_io_error_from_errno (errsv),
5822 socket_strerror (errsv));
5823 #ifndef G_OS_WIN32
5824 /* Reset errno in case the caller wants to look at it */
5825 errno = errsv;
5826 #endif
5827 return FALSE;
5830 #if G_BYTE_ORDER == G_BIG_ENDIAN
5831 /* If the returned value is smaller than an int then we need to
5832 * slide it over into the low-order bytes of *value.
5834 if (size != sizeof (gint))
5835 *value = *value >> (8 * (sizeof (gint) - size));
5836 #endif
5838 return TRUE;
5842 * g_socket_set_option:
5843 * @socket: a #GSocket
5844 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5845 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5846 * @value: the value to set the option to
5847 * @error: #GError for error reporting, or %NULL to ignore.
5849 * Sets the value of an integer-valued option on @socket, as with
5850 * setsockopt(). (If you need to set a non-integer-valued option,
5851 * you will need to call setsockopt() directly.)
5853 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5854 * header pulls in system headers that will define most of the
5855 * standard/portable socket options. For unusual socket protocols or
5856 * platform-dependent options, you may need to include additional
5857 * headers.
5859 * Returns: success or failure. On failure, @error will be set, and
5860 * the system error value (`errno` or WSAGetLastError()) will still
5861 * be set to the result of the setsockopt() call.
5863 * Since: 2.36
5865 gboolean
5866 g_socket_set_option (GSocket *socket,
5867 gint level,
5868 gint optname,
5869 gint value,
5870 GError **error)
5872 gint errsv;
5874 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5876 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
5877 return TRUE;
5879 #if !defined (__linux__) && !defined (G_OS_WIN32)
5880 /* Linux and Windows let you set a single-byte value from an int,
5881 * but most other platforms don't.
5883 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
5885 #if G_BYTE_ORDER == G_BIG_ENDIAN
5886 value = value << (8 * (sizeof (gint) - 1));
5887 #endif
5888 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
5889 return TRUE;
5891 #endif
5893 errsv = get_socket_errno ();
5895 g_set_error_literal (error,
5896 G_IO_ERROR,
5897 socket_io_error_from_errno (errsv),
5898 socket_strerror (errsv));
5899 #ifndef G_OS_WIN32
5900 errno = errsv;
5901 #endif
5902 return FALSE;