PageRenderTime 46ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/gio/gsocket.c

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