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