Merge branch 'fix-gdbus-unix-address' into 'master'
[glib.git] / gio / gsocketlistener.c
blobab17678a9f87e135614b9f3c9f14360d8741c531
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 * 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.
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.
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/>.
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>
26 #include "config.h"
27 #include "gsocketlistener.h"
29 #include <gio/gioenumtypes.h>
30 #include <gio/gtask.h>
31 #include <gio/gcancellable.h>
32 #include <gio/gsocketaddress.h>
33 #include <gio/ginetaddress.h>
34 #include <gio/gioerror.h>
35 #include <gio/gsocket.h>
36 #include <gio/gsocketconnection.h>
37 #include <gio/ginetsocketaddress.h>
38 #include "glibintl.h"
41 /**
42 * SECTION:gsocketlistener
43 * @title: GSocketListener
44 * @short_description: Helper for accepting network client connections
45 * @include: gio/gio.h
46 * @see_also: #GThreadedSocketService, #GSocketService.
48 * A #GSocketListener is an object that keeps track of a set
49 * of server sockets and helps you accept sockets from any of the
50 * socket, either sync or async.
52 * Add addresses and ports to listen on using g_socket_listener_add_address()
53 * and g_socket_listener_add_inet_port(). These will be listened on until
54 * g_socket_listener_close() is called. Dropping your final reference to the
55 * #GSocketListener will not cause g_socket_listener_close() to be called
56 * implicitly, as some references to the #GSocketListener may be held
57 * internally.
59 * If you want to implement a network server, also look at #GSocketService
60 * and #GThreadedSocketService which are subclasses of #GSocketListener
61 * that make this even easier.
63 * Since: 2.22
66 enum
68 PROP_0,
69 PROP_LISTEN_BACKLOG
72 enum
74 EVENT,
75 LAST_SIGNAL
78 static guint signals[LAST_SIGNAL] = { 0 };
80 static GQuark source_quark = 0;
82 struct _GSocketListenerPrivate
84 GPtrArray *sockets;
85 GMainContext *main_context;
86 int listen_backlog;
87 guint closed : 1;
90 G_DEFINE_TYPE_WITH_PRIVATE (GSocketListener, g_socket_listener, G_TYPE_OBJECT)
92 static void
93 g_socket_listener_finalize (GObject *object)
95 GSocketListener *listener = G_SOCKET_LISTENER (object);
97 if (listener->priv->main_context)
98 g_main_context_unref (listener->priv->main_context);
100 /* Do not explicitly close the sockets. Instead, let them close themselves if
101 * their final reference is dropped, but keep them open if a reference is
102 * held externally to the GSocketListener (which is possible if
103 * g_socket_listener_add_socket() was used).
105 g_ptr_array_free (listener->priv->sockets, TRUE);
107 G_OBJECT_CLASS (g_socket_listener_parent_class)
108 ->finalize (object);
111 static void
112 g_socket_listener_get_property (GObject *object,
113 guint prop_id,
114 GValue *value,
115 GParamSpec *pspec)
117 GSocketListener *listener = G_SOCKET_LISTENER (object);
119 switch (prop_id)
121 case PROP_LISTEN_BACKLOG:
122 g_value_set_int (value, listener->priv->listen_backlog);
123 break;
125 default:
126 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
130 static void
131 g_socket_listener_set_property (GObject *object,
132 guint prop_id,
133 const GValue *value,
134 GParamSpec *pspec)
136 GSocketListener *listener = G_SOCKET_LISTENER (object);
138 switch (prop_id)
140 case PROP_LISTEN_BACKLOG:
141 g_socket_listener_set_backlog (listener, g_value_get_int (value));
142 break;
144 default:
145 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
149 static void
150 g_socket_listener_class_init (GSocketListenerClass *klass)
152 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
154 gobject_class->finalize = g_socket_listener_finalize;
155 gobject_class->set_property = g_socket_listener_set_property;
156 gobject_class->get_property = g_socket_listener_get_property;
157 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
158 g_param_spec_int ("listen-backlog",
159 P_("Listen backlog"),
160 P_("outstanding connections in the listen queue"),
162 2000,
164 G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
167 * GSocketListener::event:
168 * @listener: the #GSocketListener
169 * @event: the event that is occurring
170 * @socket: the #GSocket the event is occurring on
172 * Emitted when @listener's activity on @socket changes state.
173 * Note that when @listener is used to listen on both IPv4 and
174 * IPv6, a separate set of signals will be emitted for each, and
175 * the order they happen in is undefined.
177 * Since: 2.46
179 signals[EVENT] =
180 g_signal_new (I_("event"),
181 G_TYPE_FROM_CLASS (gobject_class),
182 G_SIGNAL_RUN_LAST,
183 G_STRUCT_OFFSET (GSocketListenerClass, event),
184 NULL, NULL, NULL,
185 G_TYPE_NONE, 2,
186 G_TYPE_SOCKET_LISTENER_EVENT,
187 G_TYPE_SOCKET);
189 source_quark = g_quark_from_static_string ("g-socket-listener-source");
192 static void
193 g_socket_listener_init (GSocketListener *listener)
195 listener->priv = g_socket_listener_get_instance_private (listener);
196 listener->priv->sockets =
197 g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
198 listener->priv->listen_backlog = 10;
202 * g_socket_listener_new:
204 * Creates a new #GSocketListener with no sockets to listen for.
205 * New listeners can be added with e.g. g_socket_listener_add_address()
206 * or g_socket_listener_add_inet_port().
208 * Returns: a new #GSocketListener.
210 * Since: 2.22
212 GSocketListener *
213 g_socket_listener_new (void)
215 return g_object_new (G_TYPE_SOCKET_LISTENER, NULL);
218 static gboolean
219 check_listener (GSocketListener *listener,
220 GError **error)
222 if (listener->priv->closed)
224 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
225 _("Listener is already closed"));
226 return FALSE;
229 return TRUE;
233 * g_socket_listener_add_socket:
234 * @listener: a #GSocketListener
235 * @socket: a listening #GSocket
236 * @source_object: (nullable): Optional #GObject identifying this source
237 * @error: #GError for error reporting, or %NULL to ignore.
239 * Adds @socket to the set of sockets that we try to accept
240 * new clients from. The socket must be bound to a local
241 * address and listened to.
243 * @source_object will be passed out in the various calls
244 * to accept to identify this particular source, which is
245 * useful if you're listening on multiple addresses and do
246 * different things depending on what address is connected to.
248 * The @socket will not be automatically closed when the @listener is finalized
249 * unless the listener held the final reference to the socket. Before GLib 2.42,
250 * the @socket was automatically closed on finalization of the @listener, even
251 * if references to it were held elsewhere.
253 * Returns: %TRUE on success, %FALSE on error.
255 * Since: 2.22
257 gboolean
258 g_socket_listener_add_socket (GSocketListener *listener,
259 GSocket *socket,
260 GObject *source_object,
261 GError **error)
263 if (!check_listener (listener, error))
264 return FALSE;
266 /* TODO: Check that socket it is bound & not closed? */
268 if (g_socket_is_closed (socket))
270 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
271 _("Added socket is closed"));
272 return FALSE;
275 g_object_ref (socket);
276 g_ptr_array_add (listener->priv->sockets, socket);
278 if (source_object)
279 g_object_set_qdata_full (G_OBJECT (socket), source_quark,
280 g_object_ref (source_object), g_object_unref);
283 if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
284 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
286 return TRUE;
290 * g_socket_listener_add_address:
291 * @listener: a #GSocketListener
292 * @address: a #GSocketAddress
293 * @type: a #GSocketType
294 * @protocol: a #GSocketProtocol
295 * @source_object: (nullable): Optional #GObject identifying this source
296 * @effective_address: (out) (optional): location to store the address that was bound to, or %NULL.
297 * @error: #GError for error reporting, or %NULL to ignore.
299 * Creates a socket of type @type and protocol @protocol, binds
300 * it to @address and adds it to the set of sockets we're accepting
301 * sockets from.
303 * Note that adding an IPv6 address, depending on the platform,
304 * may or may not result in a listener that also accepts IPv4
305 * connections. For more deterministic behavior, see
306 * g_socket_listener_add_inet_port().
308 * @source_object will be passed out in the various calls
309 * to accept to identify this particular source, which is
310 * useful if you're listening on multiple addresses and do
311 * different things depending on what address is connected to.
313 * If successful and @effective_address is non-%NULL then it will
314 * be set to the address that the binding actually occurred at. This
315 * is helpful for determining the port number that was used for when
316 * requesting a binding to port 0 (ie: "any port"). This address, if
317 * requested, belongs to the caller and must be freed.
319 * Call g_socket_listener_close() to stop listening on @address; this will not
320 * be done automatically when you drop your final reference to @listener, as
321 * references may be held internally.
323 * Returns: %TRUE on success, %FALSE on error.
325 * Since: 2.22
327 gboolean
328 g_socket_listener_add_address (GSocketListener *listener,
329 GSocketAddress *address,
330 GSocketType type,
331 GSocketProtocol protocol,
332 GObject *source_object,
333 GSocketAddress **effective_address,
334 GError **error)
336 GSocketAddress *local_address;
337 GSocketFamily family;
338 GSocket *socket;
340 if (!check_listener (listener, error))
341 return FALSE;
343 family = g_socket_address_get_family (address);
344 socket = g_socket_new (family, type, protocol, error);
345 if (socket == NULL)
346 return FALSE;
348 g_socket_set_listen_backlog (socket, listener->priv->listen_backlog);
350 g_signal_emit (listener, signals[EVENT], 0,
351 G_SOCKET_LISTENER_BINDING, socket);
353 if (!g_socket_bind (socket, address, TRUE, error))
355 g_object_unref (socket);
356 return FALSE;
359 g_signal_emit (listener, signals[EVENT], 0,
360 G_SOCKET_LISTENER_BOUND, socket);
361 g_signal_emit (listener, signals[EVENT], 0,
362 G_SOCKET_LISTENER_LISTENING, socket);
364 if (!g_socket_listen (socket, error))
366 g_object_unref (socket);
367 return FALSE;
370 g_signal_emit (listener, signals[EVENT], 0,
371 G_SOCKET_LISTENER_LISTENED, socket);
373 local_address = NULL;
374 if (effective_address)
376 local_address = g_socket_get_local_address (socket, error);
377 if (local_address == NULL)
379 g_object_unref (socket);
380 return FALSE;
384 if (!g_socket_listener_add_socket (listener, socket,
385 source_object,
386 error))
388 if (local_address)
389 g_object_unref (local_address);
390 g_object_unref (socket);
391 return FALSE;
394 if (effective_address)
395 *effective_address = local_address;
397 g_object_unref (socket); /* add_socket refs this */
399 return TRUE;
403 * g_socket_listener_add_inet_port:
404 * @listener: a #GSocketListener
405 * @port: an IP port number (non-zero)
406 * @source_object: (nullable): Optional #GObject identifying this source
407 * @error: #GError for error reporting, or %NULL to ignore.
409 * Helper function for g_socket_listener_add_address() that
410 * creates a TCP/IP socket listening on IPv4 and IPv6 (if
411 * supported) on the specified port on all interfaces.
413 * @source_object will be passed out in the various calls
414 * to accept to identify this particular source, which is
415 * useful if you're listening on multiple addresses and do
416 * different things depending on what address is connected to.
418 * Call g_socket_listener_close() to stop listening on @port; this will not
419 * be done automatically when you drop your final reference to @listener, as
420 * references may be held internally.
422 * Returns: %TRUE on success, %FALSE on error.
424 * Since: 2.22
426 gboolean
427 g_socket_listener_add_inet_port (GSocketListener *listener,
428 guint16 port,
429 GObject *source_object,
430 GError **error)
432 gboolean need_ipv4_socket = TRUE;
433 GSocket *socket4 = NULL;
434 GSocket *socket6;
436 g_return_val_if_fail (listener != NULL, FALSE);
437 g_return_val_if_fail (port != 0, FALSE);
439 if (!check_listener (listener, error))
440 return FALSE;
442 /* first try to create an IPv6 socket */
443 socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
444 G_SOCKET_TYPE_STREAM,
445 G_SOCKET_PROTOCOL_DEFAULT,
446 NULL);
448 if (socket6 != NULL)
449 /* IPv6 is supported on this platform, so if we fail now it is
450 * a result of being unable to bind to our port. Don't fail
451 * silently as a result of this!
454 GInetAddress *inet_address;
455 GSocketAddress *address;
457 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
458 address = g_inet_socket_address_new (inet_address, port);
459 g_object_unref (inet_address);
461 g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
463 g_signal_emit (listener, signals[EVENT], 0,
464 G_SOCKET_LISTENER_BINDING, socket6);
466 if (!g_socket_bind (socket6, address, TRUE, error))
468 g_object_unref (address);
469 g_object_unref (socket6);
470 return FALSE;
473 g_object_unref (address);
475 g_signal_emit (listener, signals[EVENT], 0,
476 G_SOCKET_LISTENER_BOUND, socket6);
477 g_signal_emit (listener, signals[EVENT], 0,
478 G_SOCKET_LISTENER_LISTENING, socket6);
480 if (!g_socket_listen (socket6, error))
482 g_object_unref (socket6);
483 return FALSE;
486 g_signal_emit (listener, signals[EVENT], 0,
487 G_SOCKET_LISTENER_LISTENED, socket6);
489 if (source_object)
490 g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
491 g_object_ref (source_object),
492 g_object_unref);
494 /* If this socket already speaks IPv4 then we are done. */
495 if (g_socket_speaks_ipv4 (socket6))
496 need_ipv4_socket = FALSE;
499 if (need_ipv4_socket)
500 /* We are here for exactly one of the following reasons:
502 * - our platform doesn't support IPv6
503 * - we successfully created an IPv6 socket but it's V6ONLY
505 * In either case, we need to go ahead and create an IPv4 socket
506 * and fail the call if we can't bind to it.
509 socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
510 G_SOCKET_TYPE_STREAM,
511 G_SOCKET_PROTOCOL_DEFAULT,
512 error);
514 if (socket4 != NULL)
515 /* IPv4 is supported on this platform, so if we fail now it is
516 * a result of being unable to bind to our port. Don't fail
517 * silently as a result of this!
520 GInetAddress *inet_address;
521 GSocketAddress *address;
523 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
524 address = g_inet_socket_address_new (inet_address, port);
525 g_object_unref (inet_address);
527 g_socket_set_listen_backlog (socket4,
528 listener->priv->listen_backlog);
530 g_signal_emit (listener, signals[EVENT], 0,
531 G_SOCKET_LISTENER_BINDING, socket4);
533 if (!g_socket_bind (socket4, address, TRUE, error))
535 g_object_unref (address);
536 g_object_unref (socket4);
537 if (socket6 != NULL)
538 g_object_unref (socket6);
540 return FALSE;
543 g_object_unref (address);
545 g_signal_emit (listener, signals[EVENT], 0,
546 G_SOCKET_LISTENER_BOUND, socket4);
547 g_signal_emit (listener, signals[EVENT], 0,
548 G_SOCKET_LISTENER_LISTENING, socket4);
550 if (!g_socket_listen (socket4, error))
552 g_object_unref (socket4);
553 if (socket6 != NULL)
554 g_object_unref (socket6);
556 return FALSE;
559 g_signal_emit (listener, signals[EVENT], 0,
560 G_SOCKET_LISTENER_LISTENED, socket4);
562 if (source_object)
563 g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
564 g_object_ref (source_object),
565 g_object_unref);
567 else
568 /* Ok. So IPv4 is not supported on this platform. If we
569 * succeeded at creating an IPv6 socket then that's OK, but
570 * otherwise we need to tell the user we failed.
573 if (socket6 != NULL)
574 g_clear_error (error);
575 else
576 return FALSE;
580 g_assert (socket6 != NULL || socket4 != NULL);
582 if (socket6 != NULL)
583 g_ptr_array_add (listener->priv->sockets, socket6);
585 if (socket4 != NULL)
586 g_ptr_array_add (listener->priv->sockets, socket4);
588 if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
589 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
591 return TRUE;
594 static GList *
595 add_sources (GSocketListener *listener,
596 GSocketSourceFunc callback,
597 gpointer callback_data,
598 GCancellable *cancellable,
599 GMainContext *context)
601 GSocket *socket;
602 GSource *source;
603 GList *sources;
604 int i;
606 sources = NULL;
607 for (i = 0; i < listener->priv->sockets->len; i++)
609 socket = listener->priv->sockets->pdata[i];
611 source = g_socket_create_source (socket, G_IO_IN, cancellable);
612 g_source_set_callback (source,
613 (GSourceFunc) callback,
614 callback_data, NULL);
615 g_source_attach (source, context);
617 sources = g_list_prepend (sources, source);
620 return sources;
623 static void
624 free_sources (GList *sources)
626 GSource *source;
627 while (sources != NULL)
629 source = sources->data;
630 sources = g_list_delete_link (sources, sources);
631 g_source_destroy (source);
632 g_source_unref (source);
636 struct AcceptData {
637 GMainLoop *loop;
638 GSocket *socket;
641 static gboolean
642 accept_callback (GSocket *socket,
643 GIOCondition condition,
644 gpointer user_data)
646 struct AcceptData *data = user_data;
648 data->socket = socket;
649 g_main_loop_quit (data->loop);
651 return TRUE;
655 * g_socket_listener_accept_socket:
656 * @listener: a #GSocketListener
657 * @source_object: (out) (transfer none) (optional) (nullable): location where #GObject pointer will be stored, or %NULL.
658 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
659 * @error: #GError for error reporting, or %NULL to ignore.
661 * Blocks waiting for a client to connect to any of the sockets added
662 * to the listener. Returns the #GSocket that was accepted.
664 * If you want to accept the high-level #GSocketConnection, not a #GSocket,
665 * which is often the case, then you should use g_socket_listener_accept()
666 * instead.
668 * If @source_object is not %NULL it will be filled out with the source
669 * object specified when the corresponding socket or address was added
670 * to the listener.
672 * If @cancellable is not %NULL, then the operation can be cancelled by
673 * triggering the cancellable object from another thread. If the operation
674 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
676 * Returns: (transfer full): a #GSocket on success, %NULL on error.
678 * Since: 2.22
680 GSocket *
681 g_socket_listener_accept_socket (GSocketListener *listener,
682 GObject **source_object,
683 GCancellable *cancellable,
684 GError **error)
686 GSocket *accept_socket, *socket;
688 g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
690 if (!check_listener (listener, error))
691 return NULL;
693 if (listener->priv->sockets->len == 1)
695 accept_socket = listener->priv->sockets->pdata[0];
696 if (!g_socket_condition_wait (accept_socket, G_IO_IN,
697 cancellable, error))
698 return NULL;
700 else
702 GList *sources;
703 struct AcceptData data;
704 GMainLoop *loop;
706 if (listener->priv->main_context == NULL)
707 listener->priv->main_context = g_main_context_new ();
709 loop = g_main_loop_new (listener->priv->main_context, FALSE);
710 data.loop = loop;
711 sources = add_sources (listener,
712 accept_callback,
713 &data,
714 cancellable,
715 listener->priv->main_context);
716 g_main_loop_run (loop);
717 accept_socket = data.socket;
718 free_sources (sources);
719 g_main_loop_unref (loop);
722 if (!(socket = g_socket_accept (accept_socket, cancellable, error)))
723 return NULL;
725 if (source_object)
726 *source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
728 return socket;
732 * g_socket_listener_accept:
733 * @listener: a #GSocketListener
734 * @source_object: (out) (transfer none) (optional) (nullable): location where #GObject pointer will be stored, or %NULL
735 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
736 * @error: #GError for error reporting, or %NULL to ignore.
738 * Blocks waiting for a client to connect to any of the sockets added
739 * to the listener. Returns a #GSocketConnection for the socket that was
740 * accepted.
742 * If @source_object is not %NULL it will be filled out with the source
743 * object specified when the corresponding socket or address was added
744 * to the listener.
746 * If @cancellable is not %NULL, then the operation can be cancelled by
747 * triggering the cancellable object from another thread. If the operation
748 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
750 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
752 * Since: 2.22
754 GSocketConnection *
755 g_socket_listener_accept (GSocketListener *listener,
756 GObject **source_object,
757 GCancellable *cancellable,
758 GError **error)
760 GSocketConnection *connection;
761 GSocket *socket;
763 socket = g_socket_listener_accept_socket (listener,
764 source_object,
765 cancellable,
766 error);
767 if (socket == NULL)
768 return NULL;
770 connection = g_socket_connection_factory_create_connection (socket);
771 g_object_unref (socket);
773 return connection;
776 static gboolean
777 accept_ready (GSocket *accept_socket,
778 GIOCondition condition,
779 gpointer user_data)
781 GTask *task = user_data;
782 GError *error = NULL;
783 GSocket *socket;
784 GObject *source_object;
786 socket = g_socket_accept (accept_socket, g_task_get_cancellable (task), &error);
787 if (socket)
789 source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
790 if (source_object)
791 g_object_set_qdata_full (G_OBJECT (task),
792 source_quark,
793 g_object_ref (source_object), g_object_unref);
794 g_task_return_pointer (task, socket, g_object_unref);
796 else
798 g_task_return_error (task, error);
801 g_object_unref (task);
802 return FALSE;
806 * g_socket_listener_accept_socket_async:
807 * @listener: a #GSocketListener
808 * @cancellable: (nullable): a #GCancellable, or %NULL
809 * @callback: (scope async): a #GAsyncReadyCallback
810 * @user_data: (closure): user data for the callback
812 * This is the asynchronous version of g_socket_listener_accept_socket().
814 * When the operation is finished @callback will be
815 * called. You can then call g_socket_listener_accept_socket_finish()
816 * to get the result of the operation.
818 * Since: 2.22
820 void
821 g_socket_listener_accept_socket_async (GSocketListener *listener,
822 GCancellable *cancellable,
823 GAsyncReadyCallback callback,
824 gpointer user_data)
826 GTask *task;
827 GList *sources;
828 GError *error = NULL;
830 task = g_task_new (listener, cancellable, callback, user_data);
831 g_task_set_source_tag (task, g_socket_listener_accept_socket_async);
833 if (!check_listener (listener, &error))
835 g_task_return_error (task, error);
836 g_object_unref (task);
837 return;
840 sources = add_sources (listener,
841 accept_ready,
842 task,
843 cancellable,
844 g_main_context_get_thread_default ());
845 g_task_set_task_data (task, sources, (GDestroyNotify) free_sources);
849 * g_socket_listener_accept_socket_finish:
850 * @listener: a #GSocketListener
851 * @result: a #GAsyncResult.
852 * @source_object: (out) (transfer none) (optional) (nullable): Optional #GObject identifying this source
853 * @error: a #GError location to store the error occurring, or %NULL to
854 * ignore.
856 * Finishes an async accept operation. See g_socket_listener_accept_socket_async()
858 * Returns: (transfer full): a #GSocket on success, %NULL on error.
860 * Since: 2.22
862 GSocket *
863 g_socket_listener_accept_socket_finish (GSocketListener *listener,
864 GAsyncResult *result,
865 GObject **source_object,
866 GError **error)
868 g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
869 g_return_val_if_fail (g_task_is_valid (result, listener), NULL);
871 if (source_object)
872 *source_object = g_object_get_qdata (G_OBJECT (result), source_quark);
874 return g_task_propagate_pointer (G_TASK (result), error);
878 * g_socket_listener_accept_async:
879 * @listener: a #GSocketListener
880 * @cancellable: (nullable): a #GCancellable, or %NULL
881 * @callback: (scope async): a #GAsyncReadyCallback
882 * @user_data: (closure): user data for the callback
884 * This is the asynchronous version of g_socket_listener_accept().
886 * When the operation is finished @callback will be
887 * called. You can then call g_socket_listener_accept_socket()
888 * to get the result of the operation.
890 * Since: 2.22
892 void
893 g_socket_listener_accept_async (GSocketListener *listener,
894 GCancellable *cancellable,
895 GAsyncReadyCallback callback,
896 gpointer user_data)
898 g_socket_listener_accept_socket_async (listener,
899 cancellable,
900 callback,
901 user_data);
905 * g_socket_listener_accept_finish:
906 * @listener: a #GSocketListener
907 * @result: a #GAsyncResult.
908 * @source_object: (out) (transfer none) (optional) (nullable): Optional #GObject identifying this source
909 * @error: a #GError location to store the error occurring, or %NULL to
910 * ignore.
912 * Finishes an async accept operation. See g_socket_listener_accept_async()
914 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
916 * Since: 2.22
918 GSocketConnection *
919 g_socket_listener_accept_finish (GSocketListener *listener,
920 GAsyncResult *result,
921 GObject **source_object,
922 GError **error)
924 GSocket *socket;
925 GSocketConnection *connection;
927 socket = g_socket_listener_accept_socket_finish (listener,
928 result,
929 source_object,
930 error);
931 if (socket == NULL)
932 return NULL;
934 connection = g_socket_connection_factory_create_connection (socket);
935 g_object_unref (socket);
936 return connection;
940 * g_socket_listener_set_backlog:
941 * @listener: a #GSocketListener
942 * @listen_backlog: an integer
944 * Sets the listen backlog on the sockets in the listener.
946 * See g_socket_set_listen_backlog() for details
948 * Since: 2.22
950 void
951 g_socket_listener_set_backlog (GSocketListener *listener,
952 int listen_backlog)
954 GSocket *socket;
955 int i;
957 if (listener->priv->closed)
958 return;
960 listener->priv->listen_backlog = listen_backlog;
962 for (i = 0; i < listener->priv->sockets->len; i++)
964 socket = listener->priv->sockets->pdata[i];
965 g_socket_set_listen_backlog (socket, listen_backlog);
970 * g_socket_listener_close:
971 * @listener: a #GSocketListener
973 * Closes all the sockets in the listener.
975 * Since: 2.22
977 void
978 g_socket_listener_close (GSocketListener *listener)
980 GSocket *socket;
981 int i;
983 g_return_if_fail (G_IS_SOCKET_LISTENER (listener));
985 if (listener->priv->closed)
986 return;
988 for (i = 0; i < listener->priv->sockets->len; i++)
990 socket = listener->priv->sockets->pdata[i];
991 g_socket_close (socket, NULL);
993 listener->priv->closed = TRUE;
997 * g_socket_listener_add_any_inet_port:
998 * @listener: a #GSocketListener
999 * @source_object: (nullable): Optional #GObject identifying this source
1000 * @error: a #GError location to store the error occurring, or %NULL to
1001 * ignore.
1003 * Listens for TCP connections on any available port number for both
1004 * IPv6 and IPv4 (if each is available).
1006 * This is useful if you need to have a socket for incoming connections
1007 * but don't care about the specific port number.
1009 * @source_object will be passed out in the various calls
1010 * to accept to identify this particular source, which is
1011 * useful if you're listening on multiple addresses and do
1012 * different things depending on what address is connected to.
1014 * Returns: the port number, or 0 in case of failure.
1016 * Since: 2.24
1018 guint16
1019 g_socket_listener_add_any_inet_port (GSocketListener *listener,
1020 GObject *source_object,
1021 GError **error)
1023 GSList *sockets_to_close = NULL;
1024 guint16 candidate_port = 0;
1025 GSocket *socket6 = NULL;
1026 GSocket *socket4 = NULL;
1027 gint attempts = 37;
1030 * multi-step process:
1031 * - first, create an IPv6 socket.
1032 * - if that fails, create an IPv4 socket and bind it to port 0 and
1033 * that's it. no retries if that fails (why would it?).
1034 * - if our IPv6 socket also speaks IPv4 then we are done.
1035 * - if not, then we need to create a IPv4 socket with the same port
1036 * number. this might fail, of course. so we try this a bunch of
1037 * times -- leaving the old IPv6 sockets open so that we get a
1038 * different port number to try each time.
1039 * - if all that fails then just give up.
1042 while (attempts--)
1044 GInetAddress *inet_address;
1045 GSocketAddress *address;
1046 gboolean result;
1048 g_assert (socket6 == NULL);
1049 socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
1050 G_SOCKET_TYPE_STREAM,
1051 G_SOCKET_PROTOCOL_DEFAULT,
1052 NULL);
1054 if (socket6 != NULL)
1056 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
1057 address = g_inet_socket_address_new (inet_address, 0);
1058 g_object_unref (inet_address);
1060 g_signal_emit (listener, signals[EVENT], 0,
1061 G_SOCKET_LISTENER_BINDING, socket6);
1063 result = g_socket_bind (socket6, address, TRUE, error);
1064 g_object_unref (address);
1066 if (!result ||
1067 !(address = g_socket_get_local_address (socket6, error)))
1069 g_object_unref (socket6);
1070 socket6 = NULL;
1071 break;
1074 g_signal_emit (listener, signals[EVENT], 0,
1075 G_SOCKET_LISTENER_BOUND, socket6);
1077 g_assert (G_IS_INET_SOCKET_ADDRESS (address));
1078 candidate_port =
1079 g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
1080 g_assert (candidate_port != 0);
1081 g_object_unref (address);
1083 if (g_socket_speaks_ipv4 (socket6))
1084 break;
1087 g_assert (socket4 == NULL);
1088 socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
1089 G_SOCKET_TYPE_STREAM,
1090 G_SOCKET_PROTOCOL_DEFAULT,
1091 socket6 ? NULL : error);
1093 if (socket4 == NULL)
1094 /* IPv4 not supported.
1095 * if IPv6 is supported then candidate_port will be non-zero
1096 * (and the error parameter above will have been NULL)
1097 * if IPv6 is unsupported then candidate_port will be zero
1098 * (and error will have been set by the above call)
1100 break;
1102 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
1103 address = g_inet_socket_address_new (inet_address, candidate_port);
1104 g_object_unref (inet_address);
1106 g_signal_emit (listener, signals[EVENT], 0,
1107 G_SOCKET_LISTENER_BINDING, socket4);
1109 /* a note on the 'error' clause below:
1111 * if candidate_port is 0 then we report the error right away
1112 * since it is strange that this binding would fail at all.
1113 * otherwise, we ignore the error message (ie: NULL).
1115 * the exception to this rule is the last time through the loop
1116 * (ie: attempts == 0) in which case we want to set the error
1117 * because failure here means that the entire call will fail and
1118 * we need something to show to the user.
1120 * an english summary of the situation: "if we gave a candidate
1121 * port number AND we have more attempts to try, then ignore the
1122 * error for now".
1124 result = g_socket_bind (socket4, address, TRUE,
1125 (candidate_port && attempts) ? NULL : error);
1126 g_object_unref (address);
1128 if (candidate_port)
1130 g_assert (socket6 != NULL);
1132 if (result)
1133 /* got our candidate port successfully */
1135 g_signal_emit (listener, signals[EVENT], 0,
1136 G_SOCKET_LISTENER_BOUND, socket4);
1137 break;
1139 else
1140 /* we failed to bind to the specified port. try again. */
1142 g_object_unref (socket4);
1143 socket4 = NULL;
1145 /* keep this open so we get a different port number */
1146 sockets_to_close = g_slist_prepend (sockets_to_close,
1147 socket6);
1148 candidate_port = 0;
1149 socket6 = NULL;
1152 else
1153 /* we didn't tell it a port. this means two things.
1154 * - if we failed, then something really bad happened.
1155 * - if we succeeded, then we need to find out the port number.
1158 g_assert (socket6 == NULL);
1160 if (!result ||
1161 !(address = g_socket_get_local_address (socket4, error)))
1163 g_object_unref (socket4);
1164 socket4 = NULL;
1165 break;
1168 g_signal_emit (listener, signals[EVENT], 0,
1169 G_SOCKET_LISTENER_BOUND, socket4);
1171 g_assert (G_IS_INET_SOCKET_ADDRESS (address));
1172 candidate_port =
1173 g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
1174 g_assert (candidate_port != 0);
1175 g_object_unref (address);
1176 break;
1180 /* should only be non-zero if we have a socket */
1181 g_assert ((candidate_port != 0) == (socket4 || socket6));
1183 while (sockets_to_close)
1185 g_object_unref (sockets_to_close->data);
1186 sockets_to_close = g_slist_delete_link (sockets_to_close,
1187 sockets_to_close);
1190 /* now we actually listen() the sockets and add them to the listener */
1191 if (socket6 != NULL)
1193 g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
1195 g_signal_emit (listener, signals[EVENT], 0,
1196 G_SOCKET_LISTENER_LISTENING, socket6);
1198 if (!g_socket_listen (socket6, error))
1200 g_object_unref (socket6);
1201 if (socket4)
1202 g_object_unref (socket4);
1204 return 0;
1207 g_signal_emit (listener, signals[EVENT], 0,
1208 G_SOCKET_LISTENER_LISTENED, socket6);
1210 if (source_object)
1211 g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
1212 g_object_ref (source_object),
1213 g_object_unref);
1215 g_ptr_array_add (listener->priv->sockets, socket6);
1218 if (socket4 != NULL)
1220 g_socket_set_listen_backlog (socket4, listener->priv->listen_backlog);
1222 g_signal_emit (listener, signals[EVENT], 0,
1223 G_SOCKET_LISTENER_LISTENING, socket4);
1225 if (!g_socket_listen (socket4, error))
1227 g_object_unref (socket4);
1228 if (socket6)
1229 g_object_unref (socket6);
1231 return 0;
1234 g_signal_emit (listener, signals[EVENT], 0,
1235 G_SOCKET_LISTENER_LISTENED, socket4);
1237 if (source_object)
1238 g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
1239 g_object_ref (source_object),
1240 g_object_unref);
1242 g_ptr_array_add (listener->priv->sockets, socket4);
1245 if ((socket4 != NULL || socket6 != NULL) &&
1246 G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
1247 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
1249 return candidate_port;