PageRenderTime 59ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/gio/gsocketlistener.c

https://gitlab.com/ImageMagick/glib
C | 1235 lines | 705 code | 168 blank | 362 comment | 106 complexity | 6a872c30058e99324b48e754d03fc18d MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0
  1. /* GIO - GLib Input, Output and Streaming Library
  2. *
  3. * Copyright © 2008 Christian Kellner, Samuel Cormier-Iijima
  4. * Copyright © 2009 codethink
  5. * Copyright © 2009 Red Hat, Inc
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General
  18. * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
  19. *
  20. * Authors: Christian Kellner <gicmo@gnome.org>
  21. * Samuel Cormier-Iijima <sciyoshi@gmail.com>
  22. * Ryan Lortie <desrt@desrt.ca>
  23. * Alexander Larsson <alexl@redhat.com>
  24. */
  25. #include "config.h"
  26. #include "gsocketlistener.h"
  27. #include <gio/gioenumtypes.h>
  28. #include <gio/gtask.h>
  29. #include <gio/gcancellable.h>
  30. #include <gio/gsocketaddress.h>
  31. #include <gio/ginetaddress.h>
  32. #include <gio/gioerror.h>
  33. #include <gio/gsocket.h>
  34. #include <gio/gsocketconnection.h>
  35. #include <gio/ginetsocketaddress.h>
  36. #include "glibintl.h"
  37. /**
  38. * SECTION:gsocketlistener
  39. * @title: GSocketListener
  40. * @short_description: Helper for accepting network client connections
  41. * @include: gio/gio.h
  42. * @see_also: #GThreadedSocketService, #GSocketService.
  43. *
  44. * A #GSocketListener is an object that keeps track of a set
  45. * of server sockets and helps you accept sockets from any of the
  46. * socket, either sync or async.
  47. *
  48. * If you want to implement a network server, also look at #GSocketService
  49. * and #GThreadedSocketService which are subclass of #GSocketListener
  50. * that makes this even easier.
  51. *
  52. * Since: 2.22
  53. */
  54. enum
  55. {
  56. PROP_0,
  57. PROP_LISTEN_BACKLOG
  58. };
  59. enum
  60. {
  61. EVENT,
  62. LAST_SIGNAL
  63. };
  64. static guint signals[LAST_SIGNAL] = { 0 };
  65. static GQuark source_quark = 0;
  66. struct _GSocketListenerPrivate
  67. {
  68. GPtrArray *sockets;
  69. GMainContext *main_context;
  70. int listen_backlog;
  71. guint closed : 1;
  72. };
  73. G_DEFINE_TYPE_WITH_PRIVATE (GSocketListener, g_socket_listener, G_TYPE_OBJECT)
  74. static void
  75. g_socket_listener_finalize (GObject *object)
  76. {
  77. GSocketListener *listener = G_SOCKET_LISTENER (object);
  78. if (listener->priv->main_context)
  79. g_main_context_unref (listener->priv->main_context);
  80. /* Do not explicitly close the sockets. Instead, let them close themselves if
  81. * their final reference is dropped, but keep them open if a reference is
  82. * held externally to the GSocketListener (which is possible if
  83. * g_socket_listener_add_socket() was used).
  84. */
  85. g_ptr_array_free (listener->priv->sockets, TRUE);
  86. G_OBJECT_CLASS (g_socket_listener_parent_class)
  87. ->finalize (object);
  88. }
  89. static void
  90. g_socket_listener_get_property (GObject *object,
  91. guint prop_id,
  92. GValue *value,
  93. GParamSpec *pspec)
  94. {
  95. GSocketListener *listener = G_SOCKET_LISTENER (object);
  96. switch (prop_id)
  97. {
  98. case PROP_LISTEN_BACKLOG:
  99. g_value_set_int (value, listener->priv->listen_backlog);
  100. break;
  101. default:
  102. G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
  103. }
  104. }
  105. static void
  106. g_socket_listener_set_property (GObject *object,
  107. guint prop_id,
  108. const GValue *value,
  109. GParamSpec *pspec)
  110. {
  111. GSocketListener *listener = G_SOCKET_LISTENER (object);
  112. switch (prop_id)
  113. {
  114. case PROP_LISTEN_BACKLOG:
  115. g_socket_listener_set_backlog (listener, g_value_get_int (value));
  116. break;
  117. default:
  118. G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
  119. }
  120. }
  121. static void
  122. g_socket_listener_class_init (GSocketListenerClass *klass)
  123. {
  124. GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
  125. gobject_class->finalize = g_socket_listener_finalize;
  126. gobject_class->set_property = g_socket_listener_set_property;
  127. gobject_class->get_property = g_socket_listener_get_property;
  128. g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
  129. g_param_spec_int ("listen-backlog",
  130. P_("Listen backlog"),
  131. P_("outstanding connections in the listen queue"),
  132. 0,
  133. 2000,
  134. 10,
  135. G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  136. /**
  137. * GSocketListener::event:
  138. * @listener: the #GSocketListener
  139. * @event: the event that is occurring
  140. * @socket: the #GSocket the event is occurring on
  141. *
  142. * Emitted when @listener's activity on @socket changes state.
  143. * Note that when @listener is used to listen on both IPv4 and
  144. * IPv6, a separate set of signals will be emitted for each, and
  145. * the order they happen in is undefined.
  146. *
  147. * Since: 2.46
  148. */
  149. signals[EVENT] =
  150. g_signal_new (I_("event"),
  151. G_TYPE_FROM_CLASS (gobject_class),
  152. G_SIGNAL_RUN_LAST,
  153. G_STRUCT_OFFSET (GSocketListenerClass, event),
  154. NULL, NULL, NULL,
  155. G_TYPE_NONE, 2,
  156. G_TYPE_SOCKET_LISTENER_EVENT,
  157. G_TYPE_SOCKET);
  158. source_quark = g_quark_from_static_string ("g-socket-listener-source");
  159. }
  160. static void
  161. g_socket_listener_init (GSocketListener *listener)
  162. {
  163. listener->priv = g_socket_listener_get_instance_private (listener);
  164. listener->priv->sockets =
  165. g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
  166. listener->priv->listen_backlog = 10;
  167. }
  168. /**
  169. * g_socket_listener_new:
  170. *
  171. * Creates a new #GSocketListener with no sockets to listen for.
  172. * New listeners can be added with e.g. g_socket_listener_add_address()
  173. * or g_socket_listener_add_inet_port().
  174. *
  175. * Returns: a new #GSocketListener.
  176. *
  177. * Since: 2.22
  178. */
  179. GSocketListener *
  180. g_socket_listener_new (void)
  181. {
  182. return g_object_new (G_TYPE_SOCKET_LISTENER, NULL);
  183. }
  184. static gboolean
  185. check_listener (GSocketListener *listener,
  186. GError **error)
  187. {
  188. if (listener->priv->closed)
  189. {
  190. g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
  191. _("Listener is already closed"));
  192. return FALSE;
  193. }
  194. return TRUE;
  195. }
  196. /**
  197. * g_socket_listener_add_socket:
  198. * @listener: a #GSocketListener
  199. * @socket: a listening #GSocket
  200. * @source_object: (nullable): Optional #GObject identifying this source
  201. * @error: #GError for error reporting, or %NULL to ignore.
  202. *
  203. * Adds @socket to the set of sockets that we try to accept
  204. * new clients from. The socket must be bound to a local
  205. * address and listened to.
  206. *
  207. * @source_object will be passed out in the various calls
  208. * to accept to identify this particular source, which is
  209. * useful if you're listening on multiple addresses and do
  210. * different things depending on what address is connected to.
  211. *
  212. * The @socket will not be automatically closed when the @listener is finalized
  213. * unless the listener held the final reference to the socket. Before GLib 2.42,
  214. * the @socket was automatically closed on finalization of the @listener, even
  215. * if references to it were held elsewhere.
  216. *
  217. * Returns: %TRUE on success, %FALSE on error.
  218. *
  219. * Since: 2.22
  220. */
  221. gboolean
  222. g_socket_listener_add_socket (GSocketListener *listener,
  223. GSocket *socket,
  224. GObject *source_object,
  225. GError **error)
  226. {
  227. if (!check_listener (listener, error))
  228. return FALSE;
  229. /* TODO: Check that socket it is bound & not closed? */
  230. if (g_socket_is_closed (socket))
  231. {
  232. g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
  233. _("Added socket is closed"));
  234. return FALSE;
  235. }
  236. g_object_ref (socket);
  237. g_ptr_array_add (listener->priv->sockets, socket);
  238. if (source_object)
  239. g_object_set_qdata_full (G_OBJECT (socket), source_quark,
  240. g_object_ref (source_object), g_object_unref);
  241. if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
  242. G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
  243. return TRUE;
  244. }
  245. /**
  246. * g_socket_listener_add_address:
  247. * @listener: a #GSocketListener
  248. * @address: a #GSocketAddress
  249. * @type: a #GSocketType
  250. * @protocol: a #GSocketProtocol
  251. * @source_object: (nullable): Optional #GObject identifying this source
  252. * @effective_address: (out) (optional): location to store the address that was bound to, or %NULL.
  253. * @error: #GError for error reporting, or %NULL to ignore.
  254. *
  255. * Creates a socket of type @type and protocol @protocol, binds
  256. * it to @address and adds it to the set of sockets we're accepting
  257. * sockets from.
  258. *
  259. * Note that adding an IPv6 address, depending on the platform,
  260. * may or may not result in a listener that also accepts IPv4
  261. * connections. For more deterministic behavior, see
  262. * g_socket_listener_add_inet_port().
  263. *
  264. * @source_object will be passed out in the various calls
  265. * to accept to identify this particular source, which is
  266. * useful if you're listening on multiple addresses and do
  267. * different things depending on what address is connected to.
  268. *
  269. * If successful and @effective_address is non-%NULL then it will
  270. * be set to the address that the binding actually occurred at. This
  271. * is helpful for determining the port number that was used for when
  272. * requesting a binding to port 0 (ie: "any port"). This address, if
  273. * requested, belongs to the caller and must be freed.
  274. *
  275. * Returns: %TRUE on success, %FALSE on error.
  276. *
  277. * Since: 2.22
  278. */
  279. gboolean
  280. g_socket_listener_add_address (GSocketListener *listener,
  281. GSocketAddress *address,
  282. GSocketType type,
  283. GSocketProtocol protocol,
  284. GObject *source_object,
  285. GSocketAddress **effective_address,
  286. GError **error)
  287. {
  288. GSocketAddress *local_address;
  289. GSocketFamily family;
  290. GSocket *socket;
  291. if (!check_listener (listener, error))
  292. return FALSE;
  293. family = g_socket_address_get_family (address);
  294. socket = g_socket_new (family, type, protocol, error);
  295. if (socket == NULL)
  296. return FALSE;
  297. g_socket_set_listen_backlog (socket, listener->priv->listen_backlog);
  298. g_signal_emit (listener, signals[EVENT], 0,
  299. G_SOCKET_LISTENER_BINDING, socket);
  300. if (!g_socket_bind (socket, address, TRUE, error))
  301. {
  302. g_object_unref (socket);
  303. return FALSE;
  304. }
  305. g_signal_emit (listener, signals[EVENT], 0,
  306. G_SOCKET_LISTENER_BOUND, socket);
  307. g_signal_emit (listener, signals[EVENT], 0,
  308. G_SOCKET_LISTENER_LISTENING, socket);
  309. if (!g_socket_listen (socket, error))
  310. {
  311. g_object_unref (socket);
  312. return FALSE;
  313. }
  314. g_signal_emit (listener, signals[EVENT], 0,
  315. G_SOCKET_LISTENER_LISTENED, socket);
  316. local_address = NULL;
  317. if (effective_address)
  318. {
  319. local_address = g_socket_get_local_address (socket, error);
  320. if (local_address == NULL)
  321. {
  322. g_object_unref (socket);
  323. return FALSE;
  324. }
  325. }
  326. if (!g_socket_listener_add_socket (listener, socket,
  327. source_object,
  328. error))
  329. {
  330. if (local_address)
  331. g_object_unref (local_address);
  332. g_object_unref (socket);
  333. return FALSE;
  334. }
  335. if (effective_address)
  336. *effective_address = local_address;
  337. g_object_unref (socket); /* add_socket refs this */
  338. return TRUE;
  339. }
  340. /**
  341. * g_socket_listener_add_inet_port:
  342. * @listener: a #GSocketListener
  343. * @port: an IP port number (non-zero)
  344. * @source_object: (nullable): Optional #GObject identifying this source
  345. * @error: #GError for error reporting, or %NULL to ignore.
  346. *
  347. * Helper function for g_socket_listener_add_address() that
  348. * creates a TCP/IP socket listening on IPv4 and IPv6 (if
  349. * supported) on the specified port on all interfaces.
  350. *
  351. * @source_object will be passed out in the various calls
  352. * to accept to identify this particular source, which is
  353. * useful if you're listening on multiple addresses and do
  354. * different things depending on what address is connected to.
  355. *
  356. * Returns: %TRUE on success, %FALSE on error.
  357. *
  358. * Since: 2.22
  359. */
  360. gboolean
  361. g_socket_listener_add_inet_port (GSocketListener *listener,
  362. guint16 port,
  363. GObject *source_object,
  364. GError **error)
  365. {
  366. gboolean need_ipv4_socket = TRUE;
  367. GSocket *socket4 = NULL;
  368. GSocket *socket6;
  369. g_return_val_if_fail (listener != NULL, FALSE);
  370. g_return_val_if_fail (port != 0, FALSE);
  371. if (!check_listener (listener, error))
  372. return FALSE;
  373. /* first try to create an IPv6 socket */
  374. socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
  375. G_SOCKET_TYPE_STREAM,
  376. G_SOCKET_PROTOCOL_DEFAULT,
  377. NULL);
  378. if (socket6 != NULL)
  379. /* IPv6 is supported on this platform, so if we fail now it is
  380. * a result of being unable to bind to our port. Don't fail
  381. * silently as a result of this!
  382. */
  383. {
  384. GInetAddress *inet_address;
  385. GSocketAddress *address;
  386. inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
  387. address = g_inet_socket_address_new (inet_address, port);
  388. g_object_unref (inet_address);
  389. g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
  390. g_signal_emit (listener, signals[EVENT], 0,
  391. G_SOCKET_LISTENER_BINDING, socket6);
  392. if (!g_socket_bind (socket6, address, TRUE, error))
  393. {
  394. g_object_unref (address);
  395. g_object_unref (socket6);
  396. return FALSE;
  397. }
  398. g_object_unref (address);
  399. g_signal_emit (listener, signals[EVENT], 0,
  400. G_SOCKET_LISTENER_BOUND, socket6);
  401. g_signal_emit (listener, signals[EVENT], 0,
  402. G_SOCKET_LISTENER_LISTENING, socket6);
  403. if (!g_socket_listen (socket6, error))
  404. {
  405. g_object_unref (socket6);
  406. return FALSE;
  407. }
  408. g_signal_emit (listener, signals[EVENT], 0,
  409. G_SOCKET_LISTENER_LISTENED, socket6);
  410. if (source_object)
  411. g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
  412. g_object_ref (source_object),
  413. g_object_unref);
  414. /* If this socket already speaks IPv4 then we are done. */
  415. if (g_socket_speaks_ipv4 (socket6))
  416. need_ipv4_socket = FALSE;
  417. }
  418. if (need_ipv4_socket)
  419. /* We are here for exactly one of the following reasons:
  420. *
  421. * - our platform doesn't support IPv6
  422. * - we successfully created an IPv6 socket but it's V6ONLY
  423. *
  424. * In either case, we need to go ahead and create an IPv4 socket
  425. * and fail the call if we can't bind to it.
  426. */
  427. {
  428. socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
  429. G_SOCKET_TYPE_STREAM,
  430. G_SOCKET_PROTOCOL_DEFAULT,
  431. error);
  432. if (socket4 != NULL)
  433. /* IPv4 is supported on this platform, so if we fail now it is
  434. * a result of being unable to bind to our port. Don't fail
  435. * silently as a result of this!
  436. */
  437. {
  438. GInetAddress *inet_address;
  439. GSocketAddress *address;
  440. inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
  441. address = g_inet_socket_address_new (inet_address, port);
  442. g_object_unref (inet_address);
  443. g_socket_set_listen_backlog (socket4,
  444. listener->priv->listen_backlog);
  445. g_signal_emit (listener, signals[EVENT], 0,
  446. G_SOCKET_LISTENER_BINDING, socket4);
  447. if (!g_socket_bind (socket4, address, TRUE, error))
  448. {
  449. g_object_unref (address);
  450. g_object_unref (socket4);
  451. if (socket6 != NULL)
  452. g_object_unref (socket6);
  453. return FALSE;
  454. }
  455. g_object_unref (address);
  456. g_signal_emit (listener, signals[EVENT], 0,
  457. G_SOCKET_LISTENER_BOUND, socket4);
  458. g_signal_emit (listener, signals[EVENT], 0,
  459. G_SOCKET_LISTENER_LISTENING, socket4);
  460. if (!g_socket_listen (socket4, error))
  461. {
  462. g_object_unref (socket4);
  463. if (socket6 != NULL)
  464. g_object_unref (socket6);
  465. return FALSE;
  466. }
  467. g_signal_emit (listener, signals[EVENT], 0,
  468. G_SOCKET_LISTENER_LISTENED, socket4);
  469. if (source_object)
  470. g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
  471. g_object_ref (source_object),
  472. g_object_unref);
  473. }
  474. else
  475. /* Ok. So IPv4 is not supported on this platform. If we
  476. * succeeded at creating an IPv6 socket then that's OK, but
  477. * otherwise we need to tell the user we failed.
  478. */
  479. {
  480. if (socket6 != NULL)
  481. g_clear_error (error);
  482. else
  483. return FALSE;
  484. }
  485. }
  486. g_assert (socket6 != NULL || socket4 != NULL);
  487. if (socket6 != NULL)
  488. g_ptr_array_add (listener->priv->sockets, socket6);
  489. if (socket4 != NULL)
  490. g_ptr_array_add (listener->priv->sockets, socket4);
  491. if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
  492. G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
  493. return TRUE;
  494. }
  495. static GList *
  496. add_sources (GSocketListener *listener,
  497. GSocketSourceFunc callback,
  498. gpointer callback_data,
  499. GCancellable *cancellable,
  500. GMainContext *context)
  501. {
  502. GSocket *socket;
  503. GSource *source;
  504. GList *sources;
  505. int i;
  506. sources = NULL;
  507. for (i = 0; i < listener->priv->sockets->len; i++)
  508. {
  509. socket = listener->priv->sockets->pdata[i];
  510. source = g_socket_create_source (socket, G_IO_IN, cancellable);
  511. g_source_set_callback (source,
  512. (GSourceFunc) callback,
  513. callback_data, NULL);
  514. g_source_attach (source, context);
  515. sources = g_list_prepend (sources, source);
  516. }
  517. return sources;
  518. }
  519. static void
  520. free_sources (GList *sources)
  521. {
  522. GSource *source;
  523. while (sources != NULL)
  524. {
  525. source = sources->data;
  526. sources = g_list_delete_link (sources, sources);
  527. g_source_destroy (source);
  528. g_source_unref (source);
  529. }
  530. }
  531. struct AcceptData {
  532. GMainLoop *loop;
  533. GSocket *socket;
  534. };
  535. static gboolean
  536. accept_callback (GSocket *socket,
  537. GIOCondition condition,
  538. gpointer user_data)
  539. {
  540. struct AcceptData *data = user_data;
  541. data->socket = socket;
  542. g_main_loop_quit (data->loop);
  543. return TRUE;
  544. }
  545. /**
  546. * g_socket_listener_accept_socket:
  547. * @listener: a #GSocketListener
  548. * @source_object: (out) (transfer none) (optional) (nullable): location where #GObject pointer will be stored, or %NULL.
  549. * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
  550. * @error: #GError for error reporting, or %NULL to ignore.
  551. *
  552. * Blocks waiting for a client to connect to any of the sockets added
  553. * to the listener. Returns the #GSocket that was accepted.
  554. *
  555. * If you want to accept the high-level #GSocketConnection, not a #GSocket,
  556. * which is often the case, then you should use g_socket_listener_accept()
  557. * instead.
  558. *
  559. * If @source_object is not %NULL it will be filled out with the source
  560. * object specified when the corresponding socket or address was added
  561. * to the listener.
  562. *
  563. * If @cancellable is not %NULL, then the operation can be cancelled by
  564. * triggering the cancellable object from another thread. If the operation
  565. * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
  566. *
  567. * Returns: (transfer full): a #GSocket on success, %NULL on error.
  568. *
  569. * Since: 2.22
  570. */
  571. GSocket *
  572. g_socket_listener_accept_socket (GSocketListener *listener,
  573. GObject **source_object,
  574. GCancellable *cancellable,
  575. GError **error)
  576. {
  577. GSocket *accept_socket, *socket;
  578. g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
  579. if (!check_listener (listener, error))
  580. return NULL;
  581. if (listener->priv->sockets->len == 1)
  582. {
  583. accept_socket = listener->priv->sockets->pdata[0];
  584. if (!g_socket_condition_wait (accept_socket, G_IO_IN,
  585. cancellable, error))
  586. return NULL;
  587. }
  588. else
  589. {
  590. GList *sources;
  591. struct AcceptData data;
  592. GMainLoop *loop;
  593. if (listener->priv->main_context == NULL)
  594. listener->priv->main_context = g_main_context_new ();
  595. loop = g_main_loop_new (listener->priv->main_context, FALSE);
  596. data.loop = loop;
  597. sources = add_sources (listener,
  598. accept_callback,
  599. &data,
  600. cancellable,
  601. listener->priv->main_context);
  602. g_main_loop_run (loop);
  603. accept_socket = data.socket;
  604. free_sources (sources);
  605. g_main_loop_unref (loop);
  606. }
  607. if (!(socket = g_socket_accept (accept_socket, cancellable, error)))
  608. return NULL;
  609. if (source_object)
  610. *source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
  611. return socket;
  612. }
  613. /**
  614. * g_socket_listener_accept:
  615. * @listener: a #GSocketListener
  616. * @source_object: (out) (transfer none) (optional) (nullable): location where #GObject pointer will be stored, or %NULL
  617. * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
  618. * @error: #GError for error reporting, or %NULL to ignore.
  619. *
  620. * Blocks waiting for a client to connect to any of the sockets added
  621. * to the listener. Returns a #GSocketConnection for the socket that was
  622. * accepted.
  623. *
  624. * If @source_object is not %NULL it will be filled out with the source
  625. * object specified when the corresponding socket or address was added
  626. * to the listener.
  627. *
  628. * If @cancellable is not %NULL, then the operation can be cancelled by
  629. * triggering the cancellable object from another thread. If the operation
  630. * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
  631. *
  632. * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
  633. *
  634. * Since: 2.22
  635. */
  636. GSocketConnection *
  637. g_socket_listener_accept (GSocketListener *listener,
  638. GObject **source_object,
  639. GCancellable *cancellable,
  640. GError **error)
  641. {
  642. GSocketConnection *connection;
  643. GSocket *socket;
  644. socket = g_socket_listener_accept_socket (listener,
  645. source_object,
  646. cancellable,
  647. error);
  648. if (socket == NULL)
  649. return NULL;
  650. connection = g_socket_connection_factory_create_connection (socket);
  651. g_object_unref (socket);
  652. return connection;
  653. }
  654. static gboolean
  655. accept_ready (GSocket *accept_socket,
  656. GIOCondition condition,
  657. gpointer user_data)
  658. {
  659. GTask *task = user_data;
  660. GError *error = NULL;
  661. GSocket *socket;
  662. GObject *source_object;
  663. socket = g_socket_accept (accept_socket, g_task_get_cancellable (task), &error);
  664. if (socket)
  665. {
  666. source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
  667. if (source_object)
  668. g_object_set_qdata_full (G_OBJECT (task),
  669. source_quark,
  670. g_object_ref (source_object), g_object_unref);
  671. g_task_return_pointer (task, socket, g_object_unref);
  672. }
  673. else
  674. {
  675. g_task_return_error (task, error);
  676. }
  677. g_object_unref (task);
  678. return FALSE;
  679. }
  680. /**
  681. * g_socket_listener_accept_socket_async:
  682. * @listener: a #GSocketListener
  683. * @cancellable: (nullable): a #GCancellable, or %NULL
  684. * @callback: (scope async): a #GAsyncReadyCallback
  685. * @user_data: (closure): user data for the callback
  686. *
  687. * This is the asynchronous version of g_socket_listener_accept_socket().
  688. *
  689. * When the operation is finished @callback will be
  690. * called. You can then call g_socket_listener_accept_socket_finish()
  691. * to get the result of the operation.
  692. *
  693. * Since: 2.22
  694. */
  695. void
  696. g_socket_listener_accept_socket_async (GSocketListener *listener,
  697. GCancellable *cancellable,
  698. GAsyncReadyCallback callback,
  699. gpointer user_data)
  700. {
  701. GTask *task;
  702. GList *sources;
  703. GError *error = NULL;
  704. task = g_task_new (listener, cancellable, callback, user_data);
  705. g_task_set_source_tag (task, g_socket_listener_accept_socket_async);
  706. if (!check_listener (listener, &error))
  707. {
  708. g_task_return_error (task, error);
  709. g_object_unref (task);
  710. return;
  711. }
  712. sources = add_sources (listener,
  713. accept_ready,
  714. task,
  715. cancellable,
  716. g_main_context_get_thread_default ());
  717. g_task_set_task_data (task, sources, (GDestroyNotify) free_sources);
  718. }
  719. /**
  720. * g_socket_listener_accept_socket_finish:
  721. * @listener: a #GSocketListener
  722. * @result: a #GAsyncResult.
  723. * @source_object: (out) (transfer none) (optional) (nullable): Optional #GObject identifying this source
  724. * @error: a #GError location to store the error occurring, or %NULL to
  725. * ignore.
  726. *
  727. * Finishes an async accept operation. See g_socket_listener_accept_socket_async()
  728. *
  729. * Returns: (transfer full): a #GSocket on success, %NULL on error.
  730. *
  731. * Since: 2.22
  732. */
  733. GSocket *
  734. g_socket_listener_accept_socket_finish (GSocketListener *listener,
  735. GAsyncResult *result,
  736. GObject **source_object,
  737. GError **error)
  738. {
  739. g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
  740. g_return_val_if_fail (g_task_is_valid (result, listener), NULL);
  741. if (source_object)
  742. *source_object = g_object_get_qdata (G_OBJECT (result), source_quark);
  743. return g_task_propagate_pointer (G_TASK (result), error);
  744. }
  745. /**
  746. * g_socket_listener_accept_async:
  747. * @listener: a #GSocketListener
  748. * @cancellable: (nullable): a #GCancellable, or %NULL
  749. * @callback: (scope async): a #GAsyncReadyCallback
  750. * @user_data: (closure): user data for the callback
  751. *
  752. * This is the asynchronous version of g_socket_listener_accept().
  753. *
  754. * When the operation is finished @callback will be
  755. * called. You can then call g_socket_listener_accept_socket()
  756. * to get the result of the operation.
  757. *
  758. * Since: 2.22
  759. */
  760. void
  761. g_socket_listener_accept_async (GSocketListener *listener,
  762. GCancellable *cancellable,
  763. GAsyncReadyCallback callback,
  764. gpointer user_data)
  765. {
  766. g_socket_listener_accept_socket_async (listener,
  767. cancellable,
  768. callback,
  769. user_data);
  770. }
  771. /**
  772. * g_socket_listener_accept_finish:
  773. * @listener: a #GSocketListener
  774. * @result: a #GAsyncResult.
  775. * @source_object: (out) (transfer none) (optional) (nullable): Optional #GObject identifying this source
  776. * @error: a #GError location to store the error occurring, or %NULL to
  777. * ignore.
  778. *
  779. * Finishes an async accept operation. See g_socket_listener_accept_async()
  780. *
  781. * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
  782. *
  783. * Since: 2.22
  784. */
  785. GSocketConnection *
  786. g_socket_listener_accept_finish (GSocketListener *listener,
  787. GAsyncResult *result,
  788. GObject **source_object,
  789. GError **error)
  790. {
  791. GSocket *socket;
  792. GSocketConnection *connection;
  793. socket = g_socket_listener_accept_socket_finish (listener,
  794. result,
  795. source_object,
  796. error);
  797. if (socket == NULL)
  798. return NULL;
  799. connection = g_socket_connection_factory_create_connection (socket);
  800. g_object_unref (socket);
  801. return connection;
  802. }
  803. /**
  804. * g_socket_listener_set_backlog:
  805. * @listener: a #GSocketListener
  806. * @listen_backlog: an integer
  807. *
  808. * Sets the listen backlog on the sockets in the listener.
  809. *
  810. * See g_socket_set_listen_backlog() for details
  811. *
  812. * Since: 2.22
  813. */
  814. void
  815. g_socket_listener_set_backlog (GSocketListener *listener,
  816. int listen_backlog)
  817. {
  818. GSocket *socket;
  819. int i;
  820. if (listener->priv->closed)
  821. return;
  822. listener->priv->listen_backlog = listen_backlog;
  823. for (i = 0; i < listener->priv->sockets->len; i++)
  824. {
  825. socket = listener->priv->sockets->pdata[i];
  826. g_socket_set_listen_backlog (socket, listen_backlog);
  827. }
  828. }
  829. /**
  830. * g_socket_listener_close:
  831. * @listener: a #GSocketListener
  832. *
  833. * Closes all the sockets in the listener.
  834. *
  835. * Since: 2.22
  836. */
  837. void
  838. g_socket_listener_close (GSocketListener *listener)
  839. {
  840. GSocket *socket;
  841. int i;
  842. g_return_if_fail (G_IS_SOCKET_LISTENER (listener));
  843. if (listener->priv->closed)
  844. return;
  845. for (i = 0; i < listener->priv->sockets->len; i++)
  846. {
  847. socket = listener->priv->sockets->pdata[i];
  848. g_socket_close (socket, NULL);
  849. }
  850. listener->priv->closed = TRUE;
  851. }
  852. /**
  853. * g_socket_listener_add_any_inet_port:
  854. * @listener: a #GSocketListener
  855. * @source_object: (nullable): Optional #GObject identifying this source
  856. * @error: a #GError location to store the error occurring, or %NULL to
  857. * ignore.
  858. *
  859. * Listens for TCP connections on any available port number for both
  860. * IPv6 and IPv4 (if each is available).
  861. *
  862. * This is useful if you need to have a socket for incoming connections
  863. * but don't care about the specific port number.
  864. *
  865. * @source_object will be passed out in the various calls
  866. * to accept to identify this particular source, which is
  867. * useful if you're listening on multiple addresses and do
  868. * different things depending on what address is connected to.
  869. *
  870. * Returns: the port number, or 0 in case of failure.
  871. *
  872. * Since: 2.24
  873. **/
  874. guint16
  875. g_socket_listener_add_any_inet_port (GSocketListener *listener,
  876. GObject *source_object,
  877. GError **error)
  878. {
  879. GSList *sockets_to_close = NULL;
  880. guint16 candidate_port = 0;
  881. GSocket *socket6 = NULL;
  882. GSocket *socket4 = NULL;
  883. gint attempts = 37;
  884. /*
  885. * multi-step process:
  886. * - first, create an IPv6 socket.
  887. * - if that fails, create an IPv4 socket and bind it to port 0 and
  888. * that's it. no retries if that fails (why would it?).
  889. * - if our IPv6 socket also speaks IPv4 then we are done.
  890. * - if not, then we need to create a IPv4 socket with the same port
  891. * number. this might fail, of course. so we try this a bunch of
  892. * times -- leaving the old IPv6 sockets open so that we get a
  893. * different port number to try each time.
  894. * - if all that fails then just give up.
  895. */
  896. while (attempts--)
  897. {
  898. GInetAddress *inet_address;
  899. GSocketAddress *address;
  900. gboolean result;
  901. g_assert (socket6 == NULL);
  902. socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
  903. G_SOCKET_TYPE_STREAM,
  904. G_SOCKET_PROTOCOL_DEFAULT,
  905. NULL);
  906. if (socket6 != NULL)
  907. {
  908. inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
  909. address = g_inet_socket_address_new (inet_address, 0);
  910. g_object_unref (inet_address);
  911. g_signal_emit (listener, signals[EVENT], 0,
  912. G_SOCKET_LISTENER_BINDING, socket6);
  913. result = g_socket_bind (socket6, address, TRUE, error);
  914. g_object_unref (address);
  915. if (!result ||
  916. !(address = g_socket_get_local_address (socket6, error)))
  917. {
  918. g_object_unref (socket6);
  919. socket6 = NULL;
  920. break;
  921. }
  922. g_signal_emit (listener, signals[EVENT], 0,
  923. G_SOCKET_LISTENER_BOUND, socket6);
  924. g_assert (G_IS_INET_SOCKET_ADDRESS (address));
  925. candidate_port =
  926. g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
  927. g_assert (candidate_port != 0);
  928. g_object_unref (address);
  929. if (g_socket_speaks_ipv4 (socket6))
  930. break;
  931. }
  932. g_assert (socket4 == NULL);
  933. socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
  934. G_SOCKET_TYPE_STREAM,
  935. G_SOCKET_PROTOCOL_DEFAULT,
  936. socket6 ? NULL : error);
  937. if (socket4 == NULL)
  938. /* IPv4 not supported.
  939. * if IPv6 is supported then candidate_port will be non-zero
  940. * (and the error parameter above will have been NULL)
  941. * if IPv6 is unsupported then candidate_port will be zero
  942. * (and error will have been set by the above call)
  943. */
  944. break;
  945. inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
  946. address = g_inet_socket_address_new (inet_address, candidate_port);
  947. g_object_unref (inet_address);
  948. g_signal_emit (listener, signals[EVENT], 0,
  949. G_SOCKET_LISTENER_BINDING, socket4);
  950. /* a note on the 'error' clause below:
  951. *
  952. * if candidate_port is 0 then we report the error right away
  953. * since it is strange that this binding would fail at all.
  954. * otherwise, we ignore the error message (ie: NULL).
  955. *
  956. * the exception to this rule is the last time through the loop
  957. * (ie: attempts == 0) in which case we want to set the error
  958. * because failure here means that the entire call will fail and
  959. * we need something to show to the user.
  960. *
  961. * an english summary of the situation: "if we gave a candidate
  962. * port number AND we have more attempts to try, then ignore the
  963. * error for now".
  964. */
  965. result = g_socket_bind (socket4, address, TRUE,
  966. (candidate_port && attempts) ? NULL : error);
  967. g_object_unref (address);
  968. if (candidate_port)
  969. {
  970. g_assert (socket6 != NULL);
  971. if (result)
  972. /* got our candidate port successfully */
  973. {
  974. g_signal_emit (listener, signals[EVENT], 0,
  975. G_SOCKET_LISTENER_BOUND, socket4);
  976. break;
  977. }
  978. else
  979. /* we failed to bind to the specified port. try again. */
  980. {
  981. g_object_unref (socket4);
  982. socket4 = NULL;
  983. /* keep this open so we get a different port number */
  984. sockets_to_close = g_slist_prepend (sockets_to_close,
  985. socket6);
  986. candidate_port = 0;
  987. socket6 = NULL;
  988. }
  989. }
  990. else
  991. /* we didn't tell it a port. this means two things.
  992. * - if we failed, then something really bad happened.
  993. * - if we succeeded, then we need to find out the port number.
  994. */
  995. {
  996. g_assert (socket6 == NULL);
  997. if (!result ||
  998. !(address = g_socket_get_local_address (socket4, error)))
  999. {
  1000. g_object_unref (socket4);
  1001. socket4 = NULL;
  1002. break;
  1003. }
  1004. g_signal_emit (listener, signals[EVENT], 0,
  1005. G_SOCKET_LISTENER_BOUND, socket4);
  1006. g_assert (G_IS_INET_SOCKET_ADDRESS (address));
  1007. candidate_port =
  1008. g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
  1009. g_assert (candidate_port != 0);
  1010. g_object_unref (address);
  1011. break;
  1012. }
  1013. }
  1014. /* should only be non-zero if we have a socket */
  1015. g_assert ((candidate_port != 0) == (socket4 || socket6));
  1016. while (sockets_to_close)
  1017. {
  1018. g_object_unref (sockets_to_close->data);
  1019. sockets_to_close = g_slist_delete_link (sockets_to_close,
  1020. sockets_to_close);
  1021. }
  1022. /* now we actually listen() the sockets and add them to the listener */
  1023. if (socket6 != NULL)
  1024. {
  1025. g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
  1026. g_signal_emit (listener, signals[EVENT], 0,
  1027. G_SOCKET_LISTENER_LISTENING, socket6);
  1028. if (!g_socket_listen (socket6, error))
  1029. {
  1030. g_object_unref (socket6);
  1031. if (socket4)
  1032. g_object_unref (socket4);
  1033. return 0;
  1034. }
  1035. g_signal_emit (listener, signals[EVENT], 0,
  1036. G_SOCKET_LISTENER_LISTENED, socket6);
  1037. if (source_object)
  1038. g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
  1039. g_object_ref (source_object),
  1040. g_object_unref);
  1041. g_ptr_array_add (listener->priv->sockets, socket6);
  1042. }
  1043. if (socket4 != NULL)
  1044. {
  1045. g_socket_set_listen_backlog (socket4, listener->priv->listen_backlog);
  1046. g_signal_emit (listener, signals[EVENT], 0,
  1047. G_SOCKET_LISTENER_LISTENING, socket4);
  1048. if (!g_socket_listen (socket4, error))
  1049. {
  1050. g_object_unref (socket4);
  1051. if (socket6)
  1052. g_object_unref (socket6);
  1053. return 0;
  1054. }
  1055. g_signal_emit (listener, signals[EVENT], 0,
  1056. G_SOCKET_LISTENER_LISTENED, socket4);
  1057. if (source_object)
  1058. g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
  1059. g_object_ref (source_object),
  1060. g_object_unref);
  1061. g_ptr_array_add (listener->priv->sockets, socket4);
  1062. }
  1063. if ((socket4 != NULL || socket6 != NULL) &&
  1064. G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
  1065. G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
  1066. return candidate_port;
  1067. }