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