1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 codethink
5 * Copyright © 2009 Red Hat, Inc
7 * SPDX-License-Identifier: LGPL-2.1-or-later
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General
20 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
22 * Authors: Christian Kellner <gicmo@gnome.org>
23 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
24 * Ryan Lortie <desrt@desrt.ca>
25 * Alexander Larsson <alexl@redhat.com>
29 #include "gsocketlistener.h"
31 #include <gio/gioenumtypes.h>
32 #include <gio/gtask.h>
33 #include <gio/gcancellable.h>
34 #include <gio/gsocketaddress.h>
35 #include <gio/ginetaddress.h>
36 #include <gio/gioerror.h>
37 #include <gio/gsocket.h>
38 #include <gio/gsocketconnection.h>
39 #include <gio/ginetsocketaddress.h>
41 #include "gmarshal-internal.h"
45 * SECTION:gsocketlistener
46 * @title: GSocketListener
47 * @short_description: Helper for accepting network client connections
49 * @see_also: #GThreadedSocketService, #GSocketService.
51 * A #GSocketListener is an object that keeps track of a set
52 * of server sockets and helps you accept sockets from any of the
53 * socket, either sync or async.
55 * Add addresses and ports to listen on using g_socket_listener_add_address()
56 * and g_socket_listener_add_inet_port(). These will be listened on until
57 * g_socket_listener_close() is called. Dropping your final reference to the
58 * #GSocketListener will not cause g_socket_listener_close() to be called
59 * implicitly, as some references to the #GSocketListener may be held
62 * If you want to implement a network server, also look at #GSocketService
63 * and #GThreadedSocketService which are subclasses of #GSocketListener
64 * that make this even easier.
81 static guint signals[LAST_SIGNAL] = { 0 };
83 static GQuark source_quark = 0;
85 struct _GSocketListenerPrivate
88 GMainContext *main_context;
93 G_DEFINE_TYPE_WITH_PRIVATE (GSocketListener, g_socket_listener, G_TYPE_OBJECT)
96 g_socket_listener_finalize (GObject *object)
98 GSocketListener *listener = G_SOCKET_LISTENER (object);
100 if (listener->priv->main_context)
101 g_main_context_unref (listener->priv->main_context);
103 /* Do not explicitly close the sockets. Instead, let them close themselves if
104 * their final reference is dropped, but keep them open if a reference is
105 * held externally to the GSocketListener (which is possible if
106 * g_socket_listener_add_socket() was used).
108 g_ptr_array_free (listener->priv->sockets, TRUE);
110 G_OBJECT_CLASS (g_socket_listener_parent_class)
115 g_socket_listener_get_property (GObject *object,
120 GSocketListener *listener = G_SOCKET_LISTENER (object);
124 case PROP_LISTEN_BACKLOG:
125 g_value_set_int (value, listener->priv->listen_backlog);
129 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
134 g_socket_listener_set_property (GObject *object,
139 GSocketListener *listener = G_SOCKET_LISTENER (object);
143 case PROP_LISTEN_BACKLOG:
144 g_socket_listener_set_backlog (listener, g_value_get_int (value));
148 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
153 g_socket_listener_class_init (GSocketListenerClass *klass)
155 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
157 gobject_class->finalize = g_socket_listener_finalize;
158 gobject_class->set_property = g_socket_listener_set_property;
159 gobject_class->get_property = g_socket_listener_get_property;
160 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
161 g_param_spec_int ("listen-backlog",
162 P_("Listen backlog"),
163 P_("outstanding connections in the listen queue"),
167 G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
170 * GSocketListener::event:
171 * @listener: the #GSocketListener
172 * @event: the event that is occurring
173 * @socket: the #GSocket the event is occurring on
175 * Emitted when @listener's activity on @socket changes state.
176 * Note that when @listener is used to listen on both IPv4 and
177 * IPv6, a separate set of signals will be emitted for each, and
178 * the order they happen in is undefined.
183 g_signal_new (I_("event"),
184 G_TYPE_FROM_CLASS (gobject_class),
186 G_STRUCT_OFFSET (GSocketListenerClass, event),
188 _g_cclosure_marshal_VOID__ENUM_OBJECT,
190 G_TYPE_SOCKET_LISTENER_EVENT,
192 g_signal_set_va_marshaller (signals[EVENT],
193 G_TYPE_FROM_CLASS (gobject_class),
194 _g_cclosure_marshal_VOID__ENUM_OBJECTv);
196 source_quark = g_quark_from_static_string ("g-socket-listener-source");
200 g_socket_listener_init (GSocketListener *listener)
202 listener->priv = g_socket_listener_get_instance_private (listener);
203 listener->priv->sockets =
204 g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
205 listener->priv->listen_backlog = 10;
209 * g_socket_listener_new:
211 * Creates a new #GSocketListener with no sockets to listen for.
212 * New listeners can be added with e.g. g_socket_listener_add_address()
213 * or g_socket_listener_add_inet_port().
215 * Returns: a new #GSocketListener.
220 g_socket_listener_new (void)
222 return g_object_new (G_TYPE_SOCKET_LISTENER, NULL);
226 check_listener (GSocketListener *listener,
229 if (listener->priv->closed)
231 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
232 _("Listener is already closed"));
240 * g_socket_listener_add_socket:
241 * @listener: a #GSocketListener
242 * @socket: a listening #GSocket
243 * @source_object: (nullable): Optional #GObject identifying this source
244 * @error: #GError for error reporting, or %NULL to ignore.
246 * Adds @socket to the set of sockets that we try to accept
247 * new clients from. The socket must be bound to a local
248 * address and listened to.
250 * @source_object will be passed out in the various calls
251 * to accept to identify this particular source, which is
252 * useful if you're listening on multiple addresses and do
253 * different things depending on what address is connected to.
255 * The @socket will not be automatically closed when the @listener is finalized
256 * unless the listener held the final reference to the socket. Before GLib 2.42,
257 * the @socket was automatically closed on finalization of the @listener, even
258 * if references to it were held elsewhere.
260 * Returns: %TRUE on success, %FALSE on error.
265 g_socket_listener_add_socket (GSocketListener *listener,
267 GObject *source_object,
270 if (!check_listener (listener, error))
273 /* TODO: Check that socket it is bound & not closed? */
275 if (g_socket_is_closed (socket))
277 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
278 _("Added socket is closed"));
282 g_object_ref (socket);
283 g_ptr_array_add (listener->priv->sockets, socket);
286 g_object_set_qdata_full (G_OBJECT (socket), source_quark,
287 g_object_ref (source_object), g_object_unref);
290 if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
291 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
297 * g_socket_listener_add_address:
298 * @listener: a #GSocketListener
299 * @address: a #GSocketAddress
300 * @type: a #GSocketType
301 * @protocol: a #GSocketProtocol
302 * @source_object: (nullable): Optional #GObject identifying this source
303 * @effective_address: (out) (optional): location to store the address that was bound to, or %NULL.
304 * @error: #GError for error reporting, or %NULL to ignore.
306 * Creates a socket of type @type and protocol @protocol, binds
307 * it to @address and adds it to the set of sockets we're accepting
310 * Note that adding an IPv6 address, depending on the platform,
311 * may or may not result in a listener that also accepts IPv4
312 * connections. For more deterministic behavior, see
313 * g_socket_listener_add_inet_port().
315 * @source_object will be passed out in the various calls
316 * to accept to identify this particular source, which is
317 * useful if you're listening on multiple addresses and do
318 * different things depending on what address is connected to.
320 * If successful and @effective_address is non-%NULL then it will
321 * be set to the address that the binding actually occurred at. This
322 * is helpful for determining the port number that was used for when
323 * requesting a binding to port 0 (ie: "any port"). This address, if
324 * requested, belongs to the caller and must be freed.
326 * Call g_socket_listener_close() to stop listening on @address; this will not
327 * be done automatically when you drop your final reference to @listener, as
328 * references may be held internally.
330 * Returns: %TRUE on success, %FALSE on error.
335 g_socket_listener_add_address (GSocketListener *listener,
336 GSocketAddress *address,
338 GSocketProtocol protocol,
339 GObject *source_object,
340 GSocketAddress **effective_address,
343 GSocketAddress *local_address;
344 GSocketFamily family;
347 if (!check_listener (listener, error))
350 family = g_socket_address_get_family (address);
351 socket = g_socket_new (family, type, protocol, error);
355 g_socket_set_listen_backlog (socket, listener->priv->listen_backlog);
357 g_signal_emit (listener, signals[EVENT], 0,
358 G_SOCKET_LISTENER_BINDING, socket);
360 if (!g_socket_bind (socket, address, TRUE, error))
362 g_object_unref (socket);
366 g_signal_emit (listener, signals[EVENT], 0,
367 G_SOCKET_LISTENER_BOUND, socket);
368 g_signal_emit (listener, signals[EVENT], 0,
369 G_SOCKET_LISTENER_LISTENING, socket);
371 if (!g_socket_listen (socket, error))
373 g_object_unref (socket);
377 g_signal_emit (listener, signals[EVENT], 0,
378 G_SOCKET_LISTENER_LISTENED, socket);
380 local_address = NULL;
381 if (effective_address)
383 local_address = g_socket_get_local_address (socket, error);
384 if (local_address == NULL)
386 g_object_unref (socket);
391 if (!g_socket_listener_add_socket (listener, socket,
396 g_object_unref (local_address);
397 g_object_unref (socket);
401 if (effective_address)
402 *effective_address = local_address;
404 g_object_unref (socket); /* add_socket refs this */
410 * g_socket_listener_add_inet_port:
411 * @listener: a #GSocketListener
412 * @port: an IP port number (non-zero)
413 * @source_object: (nullable): Optional #GObject identifying this source
414 * @error: #GError for error reporting, or %NULL to ignore.
416 * Helper function for g_socket_listener_add_address() that
417 * creates a TCP/IP socket listening on IPv4 and IPv6 (if
418 * supported) on the specified port on all interfaces.
420 * @source_object will be passed out in the various calls
421 * to accept to identify this particular source, which is
422 * useful if you're listening on multiple addresses and do
423 * different things depending on what address is connected to.
425 * Call g_socket_listener_close() to stop listening on @port; this will not
426 * be done automatically when you drop your final reference to @listener, as
427 * references may be held internally.
429 * Returns: %TRUE on success, %FALSE on error.
434 g_socket_listener_add_inet_port (GSocketListener *listener,
436 GObject *source_object,
439 gboolean need_ipv4_socket = TRUE;
440 GSocket *socket4 = NULL;
443 g_return_val_if_fail (listener != NULL, FALSE);
444 g_return_val_if_fail (port != 0, FALSE);
446 if (!check_listener (listener, error))
449 /* first try to create an IPv6 socket */
450 socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
451 G_SOCKET_TYPE_STREAM,
452 G_SOCKET_PROTOCOL_DEFAULT,
456 /* IPv6 is supported on this platform, so if we fail now it is
457 * a result of being unable to bind to our port. Don't fail
458 * silently as a result of this!
461 GInetAddress *inet_address;
462 GSocketAddress *address;
464 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
465 address = g_inet_socket_address_new (inet_address, port);
466 g_object_unref (inet_address);
468 g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
470 g_signal_emit (listener, signals[EVENT], 0,
471 G_SOCKET_LISTENER_BINDING, socket6);
473 if (!g_socket_bind (socket6, address, TRUE, error))
475 g_object_unref (address);
476 g_object_unref (socket6);
480 g_object_unref (address);
482 g_signal_emit (listener, signals[EVENT], 0,
483 G_SOCKET_LISTENER_BOUND, socket6);
484 g_signal_emit (listener, signals[EVENT], 0,
485 G_SOCKET_LISTENER_LISTENING, socket6);
487 if (!g_socket_listen (socket6, error))
489 g_object_unref (socket6);
493 g_signal_emit (listener, signals[EVENT], 0,
494 G_SOCKET_LISTENER_LISTENED, socket6);
497 g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
498 g_object_ref (source_object),
501 /* If this socket already speaks IPv4 then we are done. */
502 if (g_socket_speaks_ipv4 (socket6))
503 need_ipv4_socket = FALSE;
506 if (need_ipv4_socket)
507 /* We are here for exactly one of the following reasons:
509 * - our platform doesn't support IPv6
510 * - we successfully created an IPv6 socket but it's V6ONLY
512 * In either case, we need to go ahead and create an IPv4 socket
513 * and fail the call if we can't bind to it.
516 socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
517 G_SOCKET_TYPE_STREAM,
518 G_SOCKET_PROTOCOL_DEFAULT,
522 /* IPv4 is supported on this platform, so if we fail now it is
523 * a result of being unable to bind to our port. Don't fail
524 * silently as a result of this!
527 GInetAddress *inet_address;
528 GSocketAddress *address;
530 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
531 address = g_inet_socket_address_new (inet_address, port);
532 g_object_unref (inet_address);
534 g_socket_set_listen_backlog (socket4,
535 listener->priv->listen_backlog);
537 g_signal_emit (listener, signals[EVENT], 0,
538 G_SOCKET_LISTENER_BINDING, socket4);
540 if (!g_socket_bind (socket4, address, TRUE, error))
542 g_object_unref (address);
543 g_object_unref (socket4);
545 g_object_unref (socket6);
550 g_object_unref (address);
552 g_signal_emit (listener, signals[EVENT], 0,
553 G_SOCKET_LISTENER_BOUND, socket4);
554 g_signal_emit (listener, signals[EVENT], 0,
555 G_SOCKET_LISTENER_LISTENING, socket4);
557 if (!g_socket_listen (socket4, error))
559 g_object_unref (socket4);
561 g_object_unref (socket6);
566 g_signal_emit (listener, signals[EVENT], 0,
567 G_SOCKET_LISTENER_LISTENED, socket4);
570 g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
571 g_object_ref (source_object),
575 /* Ok. So IPv4 is not supported on this platform. If we
576 * succeeded at creating an IPv6 socket then that's OK, but
577 * otherwise we need to tell the user we failed.
581 g_clear_error (error);
587 g_assert (socket6 != NULL || socket4 != NULL);
590 g_ptr_array_add (listener->priv->sockets, socket6);
593 g_ptr_array_add (listener->priv->sockets, socket4);
595 if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
596 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
602 add_sources (GSocketListener *listener,
603 GSocketSourceFunc callback,
604 gpointer callback_data,
605 GCancellable *cancellable,
606 GMainContext *context)
614 for (i = 0; i < listener->priv->sockets->len; i++)
616 socket = listener->priv->sockets->pdata[i];
618 source = g_socket_create_source (socket, G_IO_IN, cancellable);
619 g_source_set_callback (source,
620 (GSourceFunc) callback,
621 callback_data, NULL);
622 g_source_attach (source, context);
624 sources = g_list_prepend (sources, source);
631 free_sources (GList *sources)
634 while (sources != NULL)
636 source = sources->data;
637 sources = g_list_delete_link (sources, sources);
638 g_source_destroy (source);
639 g_source_unref (source);
649 accept_callback (GSocket *socket,
650 GIOCondition condition,
653 struct AcceptData *data = user_data;
655 data->socket = socket;
656 g_main_loop_quit (data->loop);
662 * g_socket_listener_accept_socket:
663 * @listener: a #GSocketListener
664 * @source_object: (out) (transfer none) (optional) (nullable): location where #GObject pointer will be stored, or %NULL.
665 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
666 * @error: #GError for error reporting, or %NULL to ignore.
668 * Blocks waiting for a client to connect to any of the sockets added
669 * to the listener. Returns the #GSocket that was accepted.
671 * If you want to accept the high-level #GSocketConnection, not a #GSocket,
672 * which is often the case, then you should use g_socket_listener_accept()
675 * If @source_object is not %NULL it will be filled out with the source
676 * object specified when the corresponding socket or address was added
679 * If @cancellable is not %NULL, then the operation can be cancelled by
680 * triggering the cancellable object from another thread. If the operation
681 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
683 * Returns: (transfer full): a #GSocket on success, %NULL on error.
688 g_socket_listener_accept_socket (GSocketListener *listener,
689 GObject **source_object,
690 GCancellable *cancellable,
693 GSocket *accept_socket, *socket;
695 g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
697 if (!check_listener (listener, error))
700 if (listener->priv->sockets->len == 1)
702 accept_socket = listener->priv->sockets->pdata[0];
703 if (!g_socket_condition_wait (accept_socket, G_IO_IN,
710 struct AcceptData data;
713 if (listener->priv->main_context == NULL)
714 listener->priv->main_context = g_main_context_new ();
716 loop = g_main_loop_new (listener->priv->main_context, FALSE);
718 sources = add_sources (listener,
722 listener->priv->main_context);
723 g_main_loop_run (loop);
724 accept_socket = data.socket;
725 free_sources (sources);
726 g_main_loop_unref (loop);
729 if (!(socket = g_socket_accept (accept_socket, cancellable, error)))
733 *source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
739 * g_socket_listener_accept:
740 * @listener: a #GSocketListener
741 * @source_object: (out) (transfer none) (optional) (nullable): location where #GObject pointer will be stored, or %NULL
742 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
743 * @error: #GError for error reporting, or %NULL to ignore.
745 * Blocks waiting for a client to connect to any of the sockets added
746 * to the listener. Returns a #GSocketConnection for the socket that was
749 * If @source_object is not %NULL it will be filled out with the source
750 * object specified when the corresponding socket or address was added
753 * If @cancellable is not %NULL, then the operation can be cancelled by
754 * triggering the cancellable object from another thread. If the operation
755 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
757 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
762 g_socket_listener_accept (GSocketListener *listener,
763 GObject **source_object,
764 GCancellable *cancellable,
767 GSocketConnection *connection;
770 socket = g_socket_listener_accept_socket (listener,
777 connection = g_socket_connection_factory_create_connection (socket);
778 g_object_unref (socket);
785 GList *sources; /* (element-type GSource) */
786 gboolean returned_yet;
787 } AcceptSocketAsyncData;
790 accept_socket_async_data_free (AcceptSocketAsyncData *data)
792 free_sources (data->sources);
797 accept_ready (GSocket *accept_socket,
798 GIOCondition condition,
801 GTask *task = user_data;
802 GError *error = NULL;
804 GObject *source_object;
805 AcceptSocketAsyncData *data = g_task_get_task_data (task);
807 /* Don’t call g_task_return_*() multiple times if we have multiple incoming
808 * connections in the same #GMainContext iteration. */
809 if (data->returned_yet)
810 return G_SOURCE_REMOVE;
812 socket = g_socket_accept (accept_socket, g_task_get_cancellable (task), &error);
815 source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
817 g_object_set_qdata_full (G_OBJECT (task),
819 g_object_ref (source_object), g_object_unref);
820 g_task_return_pointer (task, socket, g_object_unref);
824 g_task_return_error (task, error);
827 data->returned_yet = TRUE;
828 g_object_unref (task);
830 return G_SOURCE_REMOVE;
834 * g_socket_listener_accept_socket_async:
835 * @listener: a #GSocketListener
836 * @cancellable: (nullable): a #GCancellable, or %NULL
837 * @callback: (scope async): a #GAsyncReadyCallback
838 * @user_data: user data for the callback
840 * This is the asynchronous version of g_socket_listener_accept_socket().
842 * When the operation is finished @callback will be
843 * called. You can then call g_socket_listener_accept_socket_finish()
844 * to get the result of the operation.
849 g_socket_listener_accept_socket_async (GSocketListener *listener,
850 GCancellable *cancellable,
851 GAsyncReadyCallback callback,
855 GError *error = NULL;
856 AcceptSocketAsyncData *data = NULL;
858 task = g_task_new (listener, cancellable, callback, user_data);
859 g_task_set_source_tag (task, g_socket_listener_accept_socket_async);
861 if (!check_listener (listener, &error))
863 g_task_return_error (task, error);
864 g_object_unref (task);
868 data = g_new0 (AcceptSocketAsyncData, 1);
869 data->returned_yet = FALSE;
870 data->sources = add_sources (listener,
874 g_main_context_get_thread_default ());
875 g_task_set_task_data (task, g_steal_pointer (&data),
876 (GDestroyNotify) accept_socket_async_data_free);
880 * g_socket_listener_accept_socket_finish:
881 * @listener: a #GSocketListener
882 * @result: a #GAsyncResult.
883 * @source_object: (out) (transfer none) (optional) (nullable): Optional #GObject identifying this source
884 * @error: a #GError location to store the error occurring, or %NULL to
887 * Finishes an async accept operation. See g_socket_listener_accept_socket_async()
889 * Returns: (transfer full): a #GSocket on success, %NULL on error.
894 g_socket_listener_accept_socket_finish (GSocketListener *listener,
895 GAsyncResult *result,
896 GObject **source_object,
899 g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
900 g_return_val_if_fail (g_task_is_valid (result, listener), NULL);
903 *source_object = g_object_get_qdata (G_OBJECT (result), source_quark);
905 return g_task_propagate_pointer (G_TASK (result), error);
909 * g_socket_listener_accept_async:
910 * @listener: a #GSocketListener
911 * @cancellable: (nullable): a #GCancellable, or %NULL
912 * @callback: (scope async): a #GAsyncReadyCallback
913 * @user_data: user data for the callback
915 * This is the asynchronous version of g_socket_listener_accept().
917 * When the operation is finished @callback will be
918 * called. You can then call g_socket_listener_accept_finish()
919 * to get the result of the operation.
924 g_socket_listener_accept_async (GSocketListener *listener,
925 GCancellable *cancellable,
926 GAsyncReadyCallback callback,
929 g_socket_listener_accept_socket_async (listener,
936 * g_socket_listener_accept_finish:
937 * @listener: a #GSocketListener
938 * @result: a #GAsyncResult.
939 * @source_object: (out) (transfer none) (optional) (nullable): Optional #GObject identifying this source
940 * @error: a #GError location to store the error occurring, or %NULL to
943 * Finishes an async accept operation. See g_socket_listener_accept_async()
945 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
950 g_socket_listener_accept_finish (GSocketListener *listener,
951 GAsyncResult *result,
952 GObject **source_object,
956 GSocketConnection *connection;
958 socket = g_socket_listener_accept_socket_finish (listener,
965 connection = g_socket_connection_factory_create_connection (socket);
966 g_object_unref (socket);
971 * g_socket_listener_set_backlog:
972 * @listener: a #GSocketListener
973 * @listen_backlog: an integer
975 * Sets the listen backlog on the sockets in the listener. This must be called
976 * before adding any sockets, addresses or ports to the #GSocketListener (for
977 * example, by calling g_socket_listener_add_inet_port()) to be effective.
979 * See g_socket_set_listen_backlog() for details
984 g_socket_listener_set_backlog (GSocketListener *listener,
990 if (listener->priv->closed)
993 listener->priv->listen_backlog = listen_backlog;
995 for (i = 0; i < listener->priv->sockets->len; i++)
997 socket = listener->priv->sockets->pdata[i];
998 g_socket_set_listen_backlog (socket, listen_backlog);
1003 * g_socket_listener_close:
1004 * @listener: a #GSocketListener
1006 * Closes all the sockets in the listener.
1011 g_socket_listener_close (GSocketListener *listener)
1016 g_return_if_fail (G_IS_SOCKET_LISTENER (listener));
1018 if (listener->priv->closed)
1021 for (i = 0; i < listener->priv->sockets->len; i++)
1023 socket = listener->priv->sockets->pdata[i];
1024 g_socket_close (socket, NULL);
1026 listener->priv->closed = TRUE;
1030 * g_socket_listener_add_any_inet_port:
1031 * @listener: a #GSocketListener
1032 * @source_object: (nullable): Optional #GObject identifying this source
1033 * @error: a #GError location to store the error occurring, or %NULL to
1036 * Listens for TCP connections on any available port number for both
1037 * IPv6 and IPv4 (if each is available).
1039 * This is useful if you need to have a socket for incoming connections
1040 * but don't care about the specific port number.
1042 * @source_object will be passed out in the various calls
1043 * to accept to identify this particular source, which is
1044 * useful if you're listening on multiple addresses and do
1045 * different things depending on what address is connected to.
1047 * Returns: the port number, or 0 in case of failure.
1052 g_socket_listener_add_any_inet_port (GSocketListener *listener,
1053 GObject *source_object,
1056 GSList *sockets_to_close = NULL;
1057 guint16 candidate_port = 0;
1058 GSocket *socket6 = NULL;
1059 GSocket *socket4 = NULL;
1063 * multi-step process:
1064 * - first, create an IPv6 socket.
1065 * - if that fails, create an IPv4 socket and bind it to port 0 and
1066 * that's it. no retries if that fails (why would it?).
1067 * - if our IPv6 socket also speaks IPv4 then we are done.
1068 * - if not, then we need to create a IPv4 socket with the same port
1069 * number. this might fail, of course. so we try this a bunch of
1070 * times -- leaving the old IPv6 sockets open so that we get a
1071 * different port number to try each time.
1072 * - if all that fails then just give up.
1077 GInetAddress *inet_address;
1078 GSocketAddress *address;
1081 g_assert (socket6 == NULL);
1082 socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
1083 G_SOCKET_TYPE_STREAM,
1084 G_SOCKET_PROTOCOL_DEFAULT,
1087 if (socket6 != NULL)
1089 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
1090 address = g_inet_socket_address_new (inet_address, 0);
1091 g_object_unref (inet_address);
1093 g_signal_emit (listener, signals[EVENT], 0,
1094 G_SOCKET_LISTENER_BINDING, socket6);
1096 result = g_socket_bind (socket6, address, TRUE, error);
1097 g_object_unref (address);
1100 !(address = g_socket_get_local_address (socket6, error)))
1102 g_object_unref (socket6);
1107 g_signal_emit (listener, signals[EVENT], 0,
1108 G_SOCKET_LISTENER_BOUND, socket6);
1110 g_assert (G_IS_INET_SOCKET_ADDRESS (address));
1112 g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
1113 g_assert (candidate_port != 0);
1114 g_object_unref (address);
1116 if (g_socket_speaks_ipv4 (socket6))
1120 g_assert (socket4 == NULL);
1121 socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
1122 G_SOCKET_TYPE_STREAM,
1123 G_SOCKET_PROTOCOL_DEFAULT,
1124 socket6 ? NULL : error);
1126 if (socket4 == NULL)
1127 /* IPv4 not supported.
1128 * if IPv6 is supported then candidate_port will be non-zero
1129 * (and the error parameter above will have been NULL)
1130 * if IPv6 is unsupported then candidate_port will be zero
1131 * (and error will have been set by the above call)
1135 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
1136 address = g_inet_socket_address_new (inet_address, candidate_port);
1137 g_object_unref (inet_address);
1139 g_signal_emit (listener, signals[EVENT], 0,
1140 G_SOCKET_LISTENER_BINDING, socket4);
1142 /* a note on the 'error' clause below:
1144 * if candidate_port is 0 then we report the error right away
1145 * since it is strange that this binding would fail at all.
1146 * otherwise, we ignore the error message (ie: NULL).
1148 * the exception to this rule is the last time through the loop
1149 * (ie: attempts == 0) in which case we want to set the error
1150 * because failure here means that the entire call will fail and
1151 * we need something to show to the user.
1153 * an english summary of the situation: "if we gave a candidate
1154 * port number AND we have more attempts to try, then ignore the
1157 result = g_socket_bind (socket4, address, TRUE,
1158 (candidate_port && attempts) ? NULL : error);
1159 g_object_unref (address);
1163 g_assert (socket6 != NULL);
1166 /* got our candidate port successfully */
1168 g_signal_emit (listener, signals[EVENT], 0,
1169 G_SOCKET_LISTENER_BOUND, socket4);
1173 /* we failed to bind to the specified port. try again. */
1175 g_object_unref (socket4);
1178 /* keep this open so we get a different port number */
1179 sockets_to_close = g_slist_prepend (sockets_to_close,
1186 /* we didn't tell it a port. this means two things.
1187 * - if we failed, then something really bad happened.
1188 * - if we succeeded, then we need to find out the port number.
1191 g_assert (socket6 == NULL);
1194 !(address = g_socket_get_local_address (socket4, error)))
1196 g_object_unref (socket4);
1201 g_signal_emit (listener, signals[EVENT], 0,
1202 G_SOCKET_LISTENER_BOUND, socket4);
1204 g_assert (G_IS_INET_SOCKET_ADDRESS (address));
1206 g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
1207 g_assert (candidate_port != 0);
1208 g_object_unref (address);
1213 /* should only be non-zero if we have a socket */
1214 g_assert ((candidate_port != 0) == (socket4 || socket6));
1216 while (sockets_to_close)
1218 g_object_unref (sockets_to_close->data);
1219 sockets_to_close = g_slist_delete_link (sockets_to_close,
1223 /* now we actually listen() the sockets and add them to the listener */
1224 if (socket6 != NULL)
1226 g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
1228 g_signal_emit (listener, signals[EVENT], 0,
1229 G_SOCKET_LISTENER_LISTENING, socket6);
1231 if (!g_socket_listen (socket6, error))
1233 g_object_unref (socket6);
1235 g_object_unref (socket4);
1240 g_signal_emit (listener, signals[EVENT], 0,
1241 G_SOCKET_LISTENER_LISTENED, socket6);
1244 g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
1245 g_object_ref (source_object),
1248 g_ptr_array_add (listener->priv->sockets, socket6);
1251 if (socket4 != NULL)
1253 g_socket_set_listen_backlog (socket4, listener->priv->listen_backlog);
1255 g_signal_emit (listener, signals[EVENT], 0,
1256 G_SOCKET_LISTENER_LISTENING, socket4);
1258 if (!g_socket_listen (socket4, error))
1260 g_object_unref (socket4);
1262 g_object_unref (socket6);
1267 g_signal_emit (listener, signals[EVENT], 0,
1268 G_SOCKET_LISTENER_LISTENED, socket4);
1271 g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
1272 g_object_ref (source_object),
1275 g_ptr_array_add (listener->priv->sockets, socket4);
1278 if ((socket4 != NULL || socket6 != NULL) &&
1279 G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
1280 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
1282 return candidate_port;