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