gkdbus: Fix underflow and unreachable code bug
[platform/upstream/glib.git] / gio / gsocketlistener.c
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  * SPDX-License-Identifier: LGPL-2.1-or-later
8  *
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.
13  *
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.
18  *
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/>.
21  *
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>
26  */
27
28 #include "config.h"
29 #include "gsocketlistener.h"
30
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>
40 #include "glibintl.h"
41 #include "gmarshal-internal.h"
42
43
44 /**
45  * SECTION:gsocketlistener
46  * @title: GSocketListener
47  * @short_description: Helper for accepting network client connections
48  * @include: gio/gio.h
49  * @see_also: #GThreadedSocketService, #GSocketService.
50  *
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.
54  *
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
60  * internally.
61  *
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.
65  *
66  * Since: 2.22
67  */
68
69 enum
70 {
71   PROP_0,
72   PROP_LISTEN_BACKLOG
73 };
74
75 enum
76 {
77   EVENT,
78   LAST_SIGNAL
79 };
80
81 static guint signals[LAST_SIGNAL] = { 0 };
82
83 static GQuark source_quark = 0;
84
85 struct _GSocketListenerPrivate
86 {
87   GPtrArray           *sockets;
88   GMainContext        *main_context;
89   int                 listen_backlog;
90   guint               closed : 1;
91 };
92
93 G_DEFINE_TYPE_WITH_PRIVATE (GSocketListener, g_socket_listener, G_TYPE_OBJECT)
94
95 static void
96 g_socket_listener_finalize (GObject *object)
97 {
98   GSocketListener *listener = G_SOCKET_LISTENER (object);
99
100   if (listener->priv->main_context)
101     g_main_context_unref (listener->priv->main_context);
102
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).
107    */
108   g_ptr_array_free (listener->priv->sockets, TRUE);
109
110   G_OBJECT_CLASS (g_socket_listener_parent_class)
111     ->finalize (object);
112 }
113
114 static void
115 g_socket_listener_get_property (GObject    *object,
116                                 guint       prop_id,
117                                 GValue     *value,
118                                 GParamSpec *pspec)
119 {
120   GSocketListener *listener = G_SOCKET_LISTENER (object);
121
122   switch (prop_id)
123     {
124       case PROP_LISTEN_BACKLOG:
125         g_value_set_int (value, listener->priv->listen_backlog);
126         break;
127
128       default:
129         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
130     }
131 }
132
133 static void
134 g_socket_listener_set_property (GObject      *object,
135                                 guint         prop_id,
136                                 const GValue *value,
137                                 GParamSpec   *pspec)
138 {
139   GSocketListener *listener = G_SOCKET_LISTENER (object);
140
141   switch (prop_id)
142     {
143       case PROP_LISTEN_BACKLOG:
144         g_socket_listener_set_backlog (listener, g_value_get_int (value));
145         break;
146
147       default:
148         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
149     }
150 }
151
152 static void
153 g_socket_listener_class_init (GSocketListenerClass *klass)
154 {
155   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
156
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"),
164                                                      0,
165                                                      2000,
166                                                      10,
167                                                      G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
168
169   /**
170    * GSocketListener::event:
171    * @listener: the #GSocketListener
172    * @event: the event that is occurring
173    * @socket: the #GSocket the event is occurring on
174    *
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.
179    *
180    * Since: 2.46
181    */
182   signals[EVENT] =
183     g_signal_new (I_("event"),
184                   G_TYPE_FROM_CLASS (gobject_class),
185                   G_SIGNAL_RUN_LAST,
186                   G_STRUCT_OFFSET (GSocketListenerClass, event),
187                   NULL, NULL,
188                   _g_cclosure_marshal_VOID__ENUM_OBJECT,
189                   G_TYPE_NONE, 2,
190                   G_TYPE_SOCKET_LISTENER_EVENT,
191                   G_TYPE_SOCKET);
192   g_signal_set_va_marshaller (signals[EVENT],
193                               G_TYPE_FROM_CLASS (gobject_class),
194                               _g_cclosure_marshal_VOID__ENUM_OBJECTv);
195
196   source_quark = g_quark_from_static_string ("g-socket-listener-source");
197 }
198
199 static void
200 g_socket_listener_init (GSocketListener *listener)
201 {
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;
206 }
207
208 /**
209  * g_socket_listener_new:
210  *
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().
214  *
215  * Returns: a new #GSocketListener.
216  *
217  * Since: 2.22
218  */
219 GSocketListener *
220 g_socket_listener_new (void)
221 {
222   return g_object_new (G_TYPE_SOCKET_LISTENER, NULL);
223 }
224
225 static gboolean
226 check_listener (GSocketListener *listener,
227                 GError **error)
228 {
229   if (listener->priv->closed)
230     {
231       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
232                            _("Listener is already closed"));
233       return FALSE;
234     }
235
236   return TRUE;
237 }
238
239 /**
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.
245  *
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.
249  *
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.
254  *
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.
259  *
260  * Returns: %TRUE on success, %FALSE on error.
261  *
262  * Since: 2.22
263  */
264 gboolean
265 g_socket_listener_add_socket (GSocketListener  *listener,
266                               GSocket          *socket,
267                               GObject          *source_object,
268                               GError          **error)
269 {
270   if (!check_listener (listener, error))
271     return FALSE;
272
273   /* TODO: Check that socket it is bound & not closed? */
274
275   if (g_socket_is_closed (socket))
276     {
277       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
278                            _("Added socket is closed"));
279       return FALSE;
280     }
281
282   g_object_ref (socket);
283   g_ptr_array_add (listener->priv->sockets, socket);
284
285   if (source_object)
286     g_object_set_qdata_full (G_OBJECT (socket), source_quark,
287                              g_object_ref (source_object), g_object_unref);
288
289
290   if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
291     G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
292
293   return TRUE;
294 }
295
296 /**
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.
305  *
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
308  * sockets from.
309  *
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().
314  *
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.
319  *
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.
325  *
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.
329  *
330  * Returns: %TRUE on success, %FALSE on error.
331  *
332  * Since: 2.22
333  */
334 gboolean
335 g_socket_listener_add_address (GSocketListener  *listener,
336                                GSocketAddress   *address,
337                                GSocketType       type,
338                                GSocketProtocol   protocol,
339                                GObject          *source_object,
340                                GSocketAddress  **effective_address,
341                                GError          **error)
342 {
343   GSocketAddress *local_address;
344   GSocketFamily family;
345   GSocket *socket;
346
347   if (!check_listener (listener, error))
348     return FALSE;
349
350   family = g_socket_address_get_family (address);
351   socket = g_socket_new (family, type, protocol, error);
352   if (socket == NULL)
353     return FALSE;
354
355   g_socket_set_listen_backlog (socket, listener->priv->listen_backlog);
356
357   g_signal_emit (listener, signals[EVENT], 0,
358                  G_SOCKET_LISTENER_BINDING, socket);
359
360   if (!g_socket_bind (socket, address, TRUE, error))
361     {
362       g_object_unref (socket);
363       return FALSE;
364     }
365
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);
370
371   if (!g_socket_listen (socket, error))
372     {
373       g_object_unref (socket);
374       return FALSE;
375     }
376
377   g_signal_emit (listener, signals[EVENT], 0,
378                  G_SOCKET_LISTENER_LISTENED, socket);
379
380   local_address = NULL;
381   if (effective_address)
382     {
383       local_address = g_socket_get_local_address (socket, error);
384       if (local_address == NULL)
385         {
386           g_object_unref (socket);
387           return FALSE;
388         }
389     }
390
391   if (!g_socket_listener_add_socket (listener, socket,
392                                      source_object,
393                                      error))
394     {
395       if (local_address)
396         g_object_unref (local_address);
397       g_object_unref (socket);
398       return FALSE;
399     }
400
401   if (effective_address)
402     *effective_address = local_address;
403
404   g_object_unref (socket); /* add_socket refs this */
405
406   return TRUE;
407 }
408
409 /**
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.
415  *
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.
419  *
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.
424  *
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.
428  *
429  * Returns: %TRUE on success, %FALSE on error.
430  *
431  * Since: 2.22
432  */
433 gboolean
434 g_socket_listener_add_inet_port (GSocketListener  *listener,
435                                  guint16           port,
436                                  GObject          *source_object,
437                                  GError          **error)
438 {
439   gboolean need_ipv4_socket = TRUE;
440   GSocket *socket4 = NULL;
441   GSocket *socket6;
442
443   g_return_val_if_fail (listener != NULL, FALSE);
444   g_return_val_if_fail (port != 0, FALSE);
445
446   if (!check_listener (listener, error))
447     return FALSE;
448
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,
453                           NULL);
454
455   if (socket6 != NULL)
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!
459      */
460     {
461       GInetAddress *inet_address;
462       GSocketAddress *address;
463
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);
467
468       g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
469
470       g_signal_emit (listener, signals[EVENT], 0,
471                      G_SOCKET_LISTENER_BINDING, socket6);
472
473       if (!g_socket_bind (socket6, address, TRUE, error))
474         {
475           g_object_unref (address);
476           g_object_unref (socket6);
477           return FALSE;
478         }
479
480       g_object_unref (address);
481
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);
486
487       if (!g_socket_listen (socket6, error))
488         {
489           g_object_unref (socket6);
490           return FALSE;
491         }
492
493       g_signal_emit (listener, signals[EVENT], 0,
494                      G_SOCKET_LISTENER_LISTENED, socket6);
495
496       if (source_object)
497         g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
498                                  g_object_ref (source_object),
499                                  g_object_unref);
500
501       /* If this socket already speaks IPv4 then we are done. */
502       if (g_socket_speaks_ipv4 (socket6))
503         need_ipv4_socket = FALSE;
504     }
505
506   if (need_ipv4_socket)
507     /* We are here for exactly one of the following reasons:
508      *
509      *   - our platform doesn't support IPv6
510      *   - we successfully created an IPv6 socket but it's V6ONLY
511      *
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.
514      */
515     {
516       socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
517                               G_SOCKET_TYPE_STREAM,
518                               G_SOCKET_PROTOCOL_DEFAULT,
519                               error);
520
521       if (socket4 != NULL)
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!
525          */
526         {
527           GInetAddress *inet_address;
528           GSocketAddress *address;
529
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);
533
534           g_socket_set_listen_backlog (socket4,
535                                        listener->priv->listen_backlog);
536
537           g_signal_emit (listener, signals[EVENT], 0,
538                          G_SOCKET_LISTENER_BINDING, socket4);
539
540           if (!g_socket_bind (socket4, address, TRUE, error))
541             {
542               g_object_unref (address);
543               g_object_unref (socket4);
544               if (socket6 != NULL)
545                 g_object_unref (socket6);
546
547               return FALSE;
548             }
549
550           g_object_unref (address);
551
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);
556
557           if (!g_socket_listen (socket4, error))
558             {
559               g_object_unref (socket4);
560               if (socket6 != NULL)
561                 g_object_unref (socket6);
562
563               return FALSE;
564             }
565
566           g_signal_emit (listener, signals[EVENT], 0,
567                          G_SOCKET_LISTENER_LISTENED, socket4);
568
569           if (source_object)
570             g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
571                                      g_object_ref (source_object),
572                                      g_object_unref);
573         }
574       else
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.
578          */
579         {
580           if (socket6 != NULL)
581             g_clear_error (error);
582           else
583             return FALSE;
584         }
585     }
586
587   g_assert (socket6 != NULL || socket4 != NULL);
588
589   if (socket6 != NULL)
590     g_ptr_array_add (listener->priv->sockets, socket6);
591
592   if (socket4 != NULL)
593     g_ptr_array_add (listener->priv->sockets, socket4);
594
595   if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
596     G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
597
598   return TRUE;
599 }
600
601 static GList *
602 add_sources (GSocketListener   *listener,
603              GSocketSourceFunc  callback,
604              gpointer           callback_data,
605              GCancellable      *cancellable,
606              GMainContext      *context)
607 {
608   GSocket *socket;
609   GSource *source;
610   GList *sources;
611   guint i;
612
613   sources = NULL;
614   for (i = 0; i < listener->priv->sockets->len; i++)
615     {
616       socket = listener->priv->sockets->pdata[i];
617
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);
623
624       sources = g_list_prepend (sources, source);
625     }
626
627   return sources;
628 }
629
630 static void
631 free_sources (GList *sources)
632 {
633   GSource *source;
634   while (sources != NULL)
635     {
636       source = sources->data;
637       sources = g_list_delete_link (sources, sources);
638       g_source_destroy (source);
639       g_source_unref (source);
640     }
641 }
642
643 struct AcceptData {
644   GMainLoop *loop;
645   GSocket *socket;
646 };
647
648 static gboolean
649 accept_callback (GSocket      *socket,
650                  GIOCondition  condition,
651                  gpointer      user_data)
652 {
653   struct AcceptData *data = user_data;
654
655   data->socket = socket;
656   g_main_loop_quit (data->loop);
657
658   return TRUE;
659 }
660
661 /**
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.
667  *
668  * Blocks waiting for a client to connect to any of the sockets added
669  * to the listener. Returns the #GSocket that was accepted.
670  *
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()
673  * instead.
674  *
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
677  * to the listener.
678  *
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.
682  *
683  * Returns: (transfer full): a #GSocket on success, %NULL on error.
684  *
685  * Since: 2.22
686  */
687 GSocket *
688 g_socket_listener_accept_socket (GSocketListener  *listener,
689                                  GObject         **source_object,
690                                  GCancellable     *cancellable,
691                                  GError          **error)
692 {
693   GSocket *accept_socket, *socket;
694
695   g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
696
697   if (!check_listener (listener, error))
698     return NULL;
699
700   if (listener->priv->sockets->len == 1)
701     {
702       accept_socket = listener->priv->sockets->pdata[0];
703       if (!g_socket_condition_wait (accept_socket, G_IO_IN,
704                                     cancellable, error))
705         return NULL;
706     }
707   else
708     {
709       GList *sources;
710       struct AcceptData data;
711       GMainLoop *loop;
712
713       if (listener->priv->main_context == NULL)
714         listener->priv->main_context = g_main_context_new ();
715
716       loop = g_main_loop_new (listener->priv->main_context, FALSE);
717       data.loop = loop;
718       sources = add_sources (listener,
719                              accept_callback,
720                              &data,
721                              cancellable,
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);
727     }
728
729   if (!(socket = g_socket_accept (accept_socket, cancellable, error)))
730     return NULL;
731
732   if (source_object)
733     *source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
734
735   return socket;
736 }
737
738 /**
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.
744  *
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
747  * accepted.
748  *
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
751  * to the listener.
752  *
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.
756  *
757  * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
758  *
759  * Since: 2.22
760  */
761 GSocketConnection *
762 g_socket_listener_accept (GSocketListener  *listener,
763                           GObject         **source_object,
764                           GCancellable     *cancellable,
765                           GError          **error)
766 {
767   GSocketConnection *connection;
768   GSocket *socket;
769
770   socket = g_socket_listener_accept_socket (listener,
771                                             source_object,
772                                             cancellable,
773                                             error);
774   if (socket == NULL)
775     return NULL;
776
777   connection = g_socket_connection_factory_create_connection (socket);
778   g_object_unref (socket);
779
780   return connection;
781 }
782
783 typedef struct
784 {
785   GList *sources;  /* (element-type GSource) */
786   gboolean returned_yet;
787 } AcceptSocketAsyncData;
788
789 static void
790 accept_socket_async_data_free (AcceptSocketAsyncData *data)
791 {
792   free_sources (data->sources);
793   g_free (data);
794 }
795
796 static gboolean
797 accept_ready (GSocket      *accept_socket,
798               GIOCondition  condition,
799               gpointer      user_data)
800 {
801   GTask *task = user_data;
802   GError *error = NULL;
803   GSocket *socket;
804   GObject *source_object;
805   AcceptSocketAsyncData *data = g_task_get_task_data (task);
806
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;
811
812   socket = g_socket_accept (accept_socket, g_task_get_cancellable (task), &error);
813   if (socket)
814     {
815       source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
816       if (source_object)
817         g_object_set_qdata_full (G_OBJECT (task),
818                                  source_quark,
819                                  g_object_ref (source_object), g_object_unref);
820       g_task_return_pointer (task, socket, g_object_unref);
821     }
822   else
823     {
824       g_task_return_error (task, error);
825     }
826
827   data->returned_yet = TRUE;
828   g_object_unref (task);
829
830   return G_SOURCE_REMOVE;
831 }
832
833 /**
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
839  *
840  * This is the asynchronous version of g_socket_listener_accept_socket().
841  *
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.
845  *
846  * Since: 2.22
847  */
848 void
849 g_socket_listener_accept_socket_async (GSocketListener     *listener,
850                                        GCancellable        *cancellable,
851                                        GAsyncReadyCallback  callback,
852                                        gpointer             user_data)
853 {
854   GTask *task;
855   GError *error = NULL;
856   AcceptSocketAsyncData *data = NULL;
857
858   task = g_task_new (listener, cancellable, callback, user_data);
859   g_task_set_source_tag (task, g_socket_listener_accept_socket_async);
860
861   if (!check_listener (listener, &error))
862     {
863       g_task_return_error (task, error);
864       g_object_unref (task);
865       return;
866     }
867
868   data = g_new0 (AcceptSocketAsyncData, 1);
869   data->returned_yet = FALSE;
870   data->sources = add_sources (listener,
871                          accept_ready,
872                          task,
873                          cancellable,
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);
877 }
878
879 /**
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
885  * ignore.
886  *
887  * Finishes an async accept operation. See g_socket_listener_accept_socket_async()
888  *
889  * Returns: (transfer full): a #GSocket on success, %NULL on error.
890  *
891  * Since: 2.22
892  */
893 GSocket *
894 g_socket_listener_accept_socket_finish (GSocketListener  *listener,
895                                         GAsyncResult     *result,
896                                         GObject         **source_object,
897                                         GError          **error)
898 {
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);
901
902   if (source_object)
903     *source_object = g_object_get_qdata (G_OBJECT (result), source_quark);
904
905   return g_task_propagate_pointer (G_TASK (result), error);
906 }
907
908 /**
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
914  *
915  * This is the asynchronous version of g_socket_listener_accept().
916  *
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.
920  *
921  * Since: 2.22
922  */
923 void
924 g_socket_listener_accept_async (GSocketListener     *listener,
925                                 GCancellable        *cancellable,
926                                 GAsyncReadyCallback  callback,
927                                 gpointer             user_data)
928 {
929   g_socket_listener_accept_socket_async (listener,
930                                          cancellable,
931                                          callback,
932                                          user_data);
933 }
934
935 /**
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
941  * ignore.
942  *
943  * Finishes an async accept operation. See g_socket_listener_accept_async()
944  *
945  * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
946  *
947  * Since: 2.22
948  */
949 GSocketConnection *
950 g_socket_listener_accept_finish (GSocketListener  *listener,
951                                  GAsyncResult     *result,
952                                  GObject         **source_object,
953                                  GError          **error)
954 {
955   GSocket *socket;
956   GSocketConnection *connection;
957
958   socket = g_socket_listener_accept_socket_finish (listener,
959                                                    result,
960                                                    source_object,
961                                                    error);
962   if (socket == NULL)
963     return NULL;
964
965   connection = g_socket_connection_factory_create_connection (socket);
966   g_object_unref (socket);
967   return connection;
968 }
969
970 /**
971  * g_socket_listener_set_backlog:
972  * @listener: a #GSocketListener
973  * @listen_backlog: an integer
974  *
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.
978  *
979  * See g_socket_set_listen_backlog() for details
980  *
981  * Since: 2.22
982  */
983 void
984 g_socket_listener_set_backlog (GSocketListener *listener,
985                                int              listen_backlog)
986 {
987   GSocket *socket;
988   guint i;
989
990   if (listener->priv->closed)
991     return;
992
993   listener->priv->listen_backlog = listen_backlog;
994
995   for (i = 0; i < listener->priv->sockets->len; i++)
996     {
997       socket = listener->priv->sockets->pdata[i];
998       g_socket_set_listen_backlog (socket, listen_backlog);
999     }
1000 }
1001
1002 /**
1003  * g_socket_listener_close:
1004  * @listener: a #GSocketListener
1005  *
1006  * Closes all the sockets in the listener.
1007  *
1008  * Since: 2.22
1009  */
1010 void
1011 g_socket_listener_close (GSocketListener *listener)
1012 {
1013   GSocket *socket;
1014   guint i;
1015
1016   g_return_if_fail (G_IS_SOCKET_LISTENER (listener));
1017
1018   if (listener->priv->closed)
1019     return;
1020
1021   for (i = 0; i < listener->priv->sockets->len; i++)
1022     {
1023       socket = listener->priv->sockets->pdata[i];
1024       g_socket_close (socket, NULL);
1025     }
1026   listener->priv->closed = TRUE;
1027 }
1028
1029 /**
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
1034  * ignore.
1035  *
1036  * Listens for TCP connections on any available port number for both
1037  * IPv6 and IPv4 (if each is available).
1038  *
1039  * This is useful if you need to have a socket for incoming connections
1040  * but don't care about the specific port number.
1041  *
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.
1046  *
1047  * Returns: the port number, or 0 in case of failure.
1048  *
1049  * Since: 2.24
1050  **/
1051 guint16
1052 g_socket_listener_add_any_inet_port (GSocketListener  *listener,
1053                                      GObject          *source_object,
1054                                      GError          **error)
1055 {
1056   GSList *sockets_to_close = NULL;
1057   guint16 candidate_port = 0;
1058   GSocket *socket6 = NULL;
1059   GSocket *socket4 = NULL;
1060   gint attempts = 37;
1061
1062   /*
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.
1073    */
1074
1075   while (attempts--)
1076     {
1077       GInetAddress *inet_address;
1078       GSocketAddress *address;
1079       gboolean result;
1080
1081       g_assert (socket6 == NULL);
1082       socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
1083                               G_SOCKET_TYPE_STREAM,
1084                               G_SOCKET_PROTOCOL_DEFAULT,
1085                               NULL);
1086
1087       if (socket6 != NULL)
1088         {
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);
1092
1093           g_signal_emit (listener, signals[EVENT], 0,
1094                          G_SOCKET_LISTENER_BINDING, socket6);
1095
1096           result = g_socket_bind (socket6, address, TRUE, error);
1097           g_object_unref (address);
1098
1099           if (!result ||
1100               !(address = g_socket_get_local_address (socket6, error)))
1101             {
1102               g_object_unref (socket6);
1103               socket6 = NULL;
1104               break;
1105             }
1106
1107           g_signal_emit (listener, signals[EVENT], 0,
1108                          G_SOCKET_LISTENER_BOUND, socket6);
1109
1110           g_assert (G_IS_INET_SOCKET_ADDRESS (address));
1111           candidate_port =
1112             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
1113           g_assert (candidate_port != 0);
1114           g_object_unref (address);
1115
1116           if (g_socket_speaks_ipv4 (socket6))
1117             break;
1118         }
1119
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);
1125
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)
1132          */
1133         break;
1134
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);
1138
1139       g_signal_emit (listener, signals[EVENT], 0,
1140                      G_SOCKET_LISTENER_BINDING, socket4);
1141
1142       /* a note on the 'error' clause below:
1143        *
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).
1147        *
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.
1152        *
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
1155        * error for now".
1156        */
1157       result = g_socket_bind (socket4, address, TRUE,
1158                               (candidate_port && attempts) ? NULL : error);
1159       g_object_unref (address);
1160
1161       if (candidate_port)
1162         {
1163           g_assert (socket6 != NULL);
1164
1165           if (result)
1166             /* got our candidate port successfully */
1167             {
1168               g_signal_emit (listener, signals[EVENT], 0,
1169                              G_SOCKET_LISTENER_BOUND, socket4);
1170               break;
1171             }
1172           else
1173             /* we failed to bind to the specified port.  try again. */
1174             {
1175               g_object_unref (socket4);
1176               socket4 = NULL;
1177
1178               /* keep this open so we get a different port number */
1179               sockets_to_close = g_slist_prepend (sockets_to_close,
1180                                                   socket6);
1181               candidate_port = 0;
1182               socket6 = NULL;
1183             }
1184         }
1185       else
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.
1189          */
1190         {
1191           g_assert (socket6 == NULL);
1192
1193           if (!result ||
1194               !(address = g_socket_get_local_address (socket4, error)))
1195             {
1196               g_object_unref (socket4);
1197               socket4 = NULL;
1198               break;
1199             }
1200
1201             g_signal_emit (listener, signals[EVENT], 0,
1202                            G_SOCKET_LISTENER_BOUND, socket4);
1203
1204             g_assert (G_IS_INET_SOCKET_ADDRESS (address));
1205             candidate_port =
1206               g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
1207             g_assert (candidate_port != 0);
1208             g_object_unref (address);
1209             break;
1210         }
1211     }
1212
1213   /* should only be non-zero if we have a socket */
1214   g_assert ((candidate_port != 0) == (socket4 || socket6));
1215
1216   while (sockets_to_close)
1217     {
1218       g_object_unref (sockets_to_close->data);
1219       sockets_to_close = g_slist_delete_link (sockets_to_close,
1220                                               sockets_to_close);
1221     }
1222
1223   /* now we actually listen() the sockets and add them to the listener */
1224   if (socket6 != NULL)
1225     {
1226       g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
1227
1228       g_signal_emit (listener, signals[EVENT], 0,
1229                      G_SOCKET_LISTENER_LISTENING, socket6);
1230
1231       if (!g_socket_listen (socket6, error))
1232         {
1233           g_object_unref (socket6);
1234           if (socket4)
1235             g_object_unref (socket4);
1236
1237           return 0;
1238         }
1239
1240       g_signal_emit (listener, signals[EVENT], 0,
1241                      G_SOCKET_LISTENER_LISTENED, socket6);
1242
1243       if (source_object)
1244         g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
1245                                  g_object_ref (source_object),
1246                                  g_object_unref);
1247
1248       g_ptr_array_add (listener->priv->sockets, socket6);
1249     }
1250
1251    if (socket4 != NULL)
1252     {
1253       g_socket_set_listen_backlog (socket4, listener->priv->listen_backlog);
1254
1255       g_signal_emit (listener, signals[EVENT], 0,
1256                      G_SOCKET_LISTENER_LISTENING, socket4);
1257
1258       if (!g_socket_listen (socket4, error))
1259         {
1260           g_object_unref (socket4);
1261           if (socket6)
1262             g_object_unref (socket6);
1263
1264           return 0;
1265         }
1266
1267       g_signal_emit (listener, signals[EVENT], 0,
1268                      G_SOCKET_LISTENER_LISTENED, socket4);
1269
1270       if (source_object)
1271         g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
1272                                  g_object_ref (source_object),
1273                                  g_object_unref);
1274
1275       g_ptr_array_add (listener->priv->sockets, socket4);
1276     }
1277
1278   if ((socket4 != NULL || socket6 != NULL) &&
1279       G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
1280     G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
1281
1282   return candidate_port;
1283 }