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