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