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