1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 codethink
5 * Copyright © 2009 Red Hat, Inc
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.
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.
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.
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>
29 #include "gsocketlistener.h"
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>
44 * SECTION: gsocketlistener
45 * @title: GSocketListener
46 * @short_description: Helper for accepting network client connections
47 * @see_also: #GThreadedSocketService, #GSocketService.
49 * A #GSocketListener is an object that keeps track of a set
50 * of server sockets and helps you accept sockets from any of the
51 * socket, either sync or async.
53 * If you want to implement a network server, also look at #GSocketService
54 * and #GThreadedSocketService which are subclass of #GSocketListener
55 * that makes this even easier.
60 G_DEFINE_TYPE (GSocketListener, g_socket_listener, G_TYPE_OBJECT);
69 static GQuark source_quark = 0;
71 struct _GSocketListenerPrivate
74 GMainContext *main_context;
80 g_socket_listener_finalize (GObject *object)
82 GSocketListener *listener = G_SOCKET_LISTENER (object);
84 if (listener->priv->main_context)
85 g_main_context_unref (listener->priv->main_context);
87 if (!listener->priv->closed)
88 g_socket_listener_close (listener);
90 g_ptr_array_free (listener->priv->sockets, TRUE);
92 G_OBJECT_CLASS (g_socket_listener_parent_class)
97 g_socket_listener_get_property (GObject *object,
102 GSocketListener *listener = G_SOCKET_LISTENER (object);
106 case PROP_LISTEN_BACKLOG:
107 g_value_set_int (value, listener->priv->listen_backlog);
111 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
116 g_socket_listener_set_property (GObject *object,
121 GSocketListener *listener = G_SOCKET_LISTENER (object);
125 case PROP_LISTEN_BACKLOG:
126 g_socket_listener_set_backlog (listener, g_value_get_int (value));
130 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
136 g_socket_listener_class_init (GSocketListenerClass *klass)
138 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
140 g_type_class_add_private (klass, sizeof (GSocketListenerPrivate));
142 gobject_class->finalize = g_socket_listener_finalize;
143 gobject_class->set_property = g_socket_listener_set_property;
144 gobject_class->get_property = g_socket_listener_get_property;
145 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
146 g_param_spec_int ("listen-backlog",
147 P_("Listen backlog"),
148 P_("outstanding connections in the listen queue"),
152 G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
154 source_quark = g_quark_from_static_string ("g-socket-listener-source");
158 g_socket_listener_init (GSocketListener *listener)
160 listener->priv = G_TYPE_INSTANCE_GET_PRIVATE (listener,
161 G_TYPE_SOCKET_LISTENER,
162 GSocketListenerPrivate);
163 listener->priv->sockets =
164 g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
165 listener->priv->listen_backlog = 10;
169 * g_socket_listener_new:
171 * Creates a new #GSocketListener with no sockets to listen for.
172 * New listeners can be added with e.g. g_socket_listener_add_address()
173 * or g_socket_listener_add_inet_port().
175 * Returns: a new #GSocketListener.
180 g_socket_listener_new (void)
182 return g_object_new (G_TYPE_SOCKET_LISTENER, NULL);
186 check_listener (GSocketListener *listener,
189 if (listener->priv->closed)
191 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
192 _("Listener is already closed"));
200 * g_socket_listener_add_socket:
201 * @listener: a #GSocketListener
202 * @socket: a listening #GSocket
203 * @source_object: Optional #GObject identifying this source
204 * @error: #GError for error reporting, or %NULL to ignore.
206 * Adds @socket to the set of sockets that we try to accept
207 * new clients from. The socket must be bound to a local
208 * address and listened to.
210 * @source_object will be passed out in the various calls
211 * to accept to identify this particular source, which is
212 * useful if you're listening on multiple addresses and do
213 * different things depending on what address is connected to.
215 * Returns: %TRUE on success, %FALSE on error.
220 g_socket_listener_add_socket (GSocketListener *listener,
222 GObject *source_object,
225 if (!check_listener (listener, error))
228 /* TODO: Check that socket it is bound & not closed? */
230 if (g_socket_is_closed (socket))
232 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
233 _("Added socket is closed"));
237 g_ptr_array_add (listener->priv->sockets, socket);
240 g_object_set_qdata_full (G_OBJECT (socket), source_quark,
241 g_object_ref (source_object), g_object_unref);
247 * g_socket_listener_add_address:
248 * @listener: a #GSocketListener
249 * @address: a #GSocketAddress
250 * @type: a #GSocketType
251 * @protocol: a #GSocketProtocol
252 * @source_object: Optional #GObject identifying this source
253 * @effective_address: location to store the address that was bound to, or %NULL.
254 * @error: #GError for error reporting, or %NULL to ignore.
256 * Creates a socket of type @type and protocol @protocol, binds
257 * it to @address and adds it to the set of sockets we're accepting
260 * Note that adding an IPv6 address, depending on the platform,
261 * may or may not result in a listener that also accepts IPv4
262 * connections. For more determinstic behaviour, see
263 * g_socket_listener_add_inet_port().
265 * @source_object will be passed out in the various calls
266 * to accept to identify this particular source, which is
267 * useful if you're listening on multiple addresses and do
268 * different things depending on what address is connected to.
270 * If successful and @effective_address is non-%NULL then it will
271 * be set to the address that the binding actually occured at. This
272 * is helpful for determining the port number that was used for when
273 * requesting a binding to port 0 (ie: "any port"). This address, if
274 * requested, belongs to the caller and must be freed.
276 * Returns: %TRUE on success, %FALSE on error.
281 g_socket_listener_add_address (GSocketListener *listener,
282 GSocketAddress *address,
284 GSocketProtocol protocol,
285 GObject *source_object,
286 GSocketAddress **effective_address,
289 GSocketAddress *local_address;
290 GSocketFamily family;
293 if (!check_listener (listener, error))
296 family = g_socket_address_get_family (address);
297 socket = g_socket_new (family, type, protocol, error);
301 g_socket_set_listen_backlog (socket, listener->priv->listen_backlog);
303 if (!g_socket_bind (socket, address, TRUE, error) ||
304 !g_socket_listen (socket, error) ||
305 !g_socket_listener_add_socket (listener, socket,
309 g_object_unref (socket);
313 if (effective_address)
315 local_address = g_socket_get_local_address (socket, error);
316 if (local_address == NULL)
318 g_object_unref (socket);
321 *effective_address = local_address;
324 if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
325 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
331 * g_socket_listener_add_inet_port:
332 * @listener: a #GSocketListener
333 * @port: an IP port number (non-zero)
334 * @source_object: Optional #GObject identifying this source
335 * @error: #GError for error reporting, or %NULL to ignore.
337 * Helper function for g_socket_listener_add_address() that
338 * creates a TCP/IP socket listening on IPv4 and IPv6 (if
339 * supported) on the specified port on all interfaces.
341 * @source_object will be passed out in the various calls
342 * to accept to identify this particular source, which is
343 * useful if you're listening on multiple addresses and do
344 * different things depending on what address is connected to.
346 * Returns: %TRUE on success, %FALSE on error.
351 g_socket_listener_add_inet_port (GSocketListener *listener,
353 GObject *source_object,
356 gboolean need_ipv4_socket = TRUE;
357 GSocket *socket4 = NULL;
360 g_return_val_if_fail (listener != NULL, FALSE);
361 g_return_val_if_fail (port != 0, FALSE);
363 if (!check_listener (listener, error))
366 /* first try to create an IPv6 socket */
367 socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
368 G_SOCKET_TYPE_STREAM,
369 G_SOCKET_PROTOCOL_DEFAULT,
373 /* IPv6 is supported on this platform, so if we fail now it is
374 * a result of being unable to bind to our port. Don't fail
375 * silently as a result of this!
378 GInetAddress *inet_address;
379 GSocketAddress *address;
382 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
383 address = g_inet_socket_address_new (inet_address, port);
384 g_object_unref (inet_address);
386 g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
388 result = g_socket_bind (socket6, address, TRUE, error) &&
389 g_socket_listen (socket6, error);
391 g_object_unref (address);
395 g_object_unref (socket6);
401 g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
402 g_object_ref (source_object),
405 /* If this socket already speaks IPv4 then we are done. */
406 if (g_socket_speaks_ipv4 (socket6))
407 need_ipv4_socket = FALSE;
410 if (need_ipv4_socket)
411 /* We are here for exactly one of the following reasons:
413 * - our platform doesn't support IPv6
414 * - we successfully created an IPv6 socket but it's V6ONLY
416 * In either case, we need to go ahead and create an IPv4 socket
417 * and fail the call if we can't bind to it.
420 socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
421 G_SOCKET_TYPE_STREAM,
422 G_SOCKET_PROTOCOL_DEFAULT,
426 /* IPv4 is supported on this platform, so if we fail now it is
427 * a result of being unable to bind to our port. Don't fail
428 * silently as a result of this!
431 GInetAddress *inet_address;
432 GSocketAddress *address;
435 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
436 address = g_inet_socket_address_new (inet_address, port);
437 g_object_unref (inet_address);
439 g_socket_set_listen_backlog (socket4,
440 listener->priv->listen_backlog);
442 result = g_socket_bind (socket4, address, TRUE, error) &&
443 g_socket_listen (socket4, error);
445 g_object_unref (address);
449 g_object_unref (socket4);
452 g_object_unref (socket6);
458 g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
459 g_object_ref (source_object),
463 /* Ok. So IPv4 is not supported on this platform. If we
464 * succeeded at creating an IPv6 socket then that's OK, but
465 * otherwise we need to tell the user we failed.
469 g_clear_error (error);
475 g_assert (socket6 != NULL || socket4 != NULL);
478 g_ptr_array_add (listener->priv->sockets, socket6);
481 g_ptr_array_add (listener->priv->sockets, socket4);
483 if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
484 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
490 add_sources (GSocketListener *listener,
491 GSocketSourceFunc callback,
492 gpointer callback_data,
493 GCancellable *cancellable,
494 GMainContext *context)
502 for (i = 0; i < listener->priv->sockets->len; i++)
504 socket = listener->priv->sockets->pdata[i];
506 source = g_socket_create_source (socket, G_IO_IN, cancellable);
507 g_source_set_callback (source,
508 (GSourceFunc) callback,
509 callback_data, NULL);
510 g_source_attach (source, context);
512 sources = g_list_prepend (sources, source);
519 free_sources (GList *sources)
522 while (sources != NULL)
524 source = sources->data;
525 sources = g_list_delete_link (sources, sources);
526 g_source_destroy (source);
527 g_source_unref (source);
537 accept_callback (GSocket *socket,
538 GIOCondition condition,
541 struct AcceptData *data = user_data;
543 data->socket = socket;
544 g_main_loop_quit (data->loop);
550 * g_socket_listener_accept_socket:
551 * @listener: a #GSocketListener
552 * @source_object: location where #GObject pointer will be stored, or %NULL
553 * @cancellable: optional #GCancellable object, %NULL to ignore.
554 * @error: #GError for error reporting, or %NULL to ignore.
556 * Blocks waiting for a client to connect to any of the sockets added
557 * to the listener. Returns the #GSocket that was accepted.
559 * If you want to accept the high-level #GSocketConnection, not a #GSocket,
560 * which is often the case, then you should use g_socket_listener_accept()
563 * If @source_object is not %NULL it will be filled out with the source
564 * object specified when the corresponding socket or address was added
567 * If @cancellable is not %NULL, then the operation can be cancelled by
568 * triggering the cancellable object from another thread. If the operation
569 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
571 * Returns: a #GSocket on success, %NULL on error.
576 g_socket_listener_accept_socket (GSocketListener *listener,
577 GObject **source_object,
578 GCancellable *cancellable,
581 GSocket *accept_socket, *socket;
583 g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
585 if (!check_listener (listener, error))
588 if (listener->priv->sockets->len == 1)
590 accept_socket = listener->priv->sockets->pdata[0];
591 if (!g_socket_condition_wait (accept_socket, G_IO_IN,
598 struct AcceptData data;
601 if (listener->priv->main_context == NULL)
602 listener->priv->main_context = g_main_context_new ();
604 loop = g_main_loop_new (listener->priv->main_context, FALSE);
606 sources = add_sources (listener,
610 listener->priv->main_context);
611 g_main_loop_run (loop);
612 accept_socket = data.socket;
613 free_sources (sources);
614 g_main_loop_unref (loop);
617 if (!(socket = g_socket_accept (accept_socket, error)))
621 *source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
627 * g_socket_listener_accept:
628 * @listener: a #GSocketListener
629 * @source_object: location where #GObject pointer will be stored, or %NULL
630 * @cancellable: optional #GCancellable object, %NULL to ignore.
631 * @error: #GError for error reporting, or %NULL to ignore.
633 * Blocks waiting for a client to connect to any of the sockets added
634 * to the listener. Returns a #GSocketConnection for the socket that was
637 * If @source_object is not %NULL it will be filled out with the source
638 * object specified when the corresponding socket or address was added
641 * If @cancellable is not %NULL, then the operation can be cancelled by
642 * triggering the cancellable object from another thread. If the operation
643 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
645 * Returns: a #GSocketConnection on success, %NULL on error.
650 g_socket_listener_accept (GSocketListener *listener,
651 GObject **source_object,
652 GCancellable *cancellable,
655 GSocketConnection *connection;
658 socket = g_socket_listener_accept_socket (listener,
665 connection = g_socket_connection_factory_create_connection (socket);
666 g_object_unref (socket);
671 struct AcceptAsyncData {
672 GSimpleAsyncResult *simple;
673 GCancellable *cancellable;
678 accept_ready (GSocket *accept_socket,
679 GIOCondition condition,
682 struct AcceptAsyncData *data = _data;
683 GError *error = NULL;
685 if (!g_cancellable_set_error_if_cancelled (data->cancellable,
689 GObject *source_object;
691 socket = g_socket_accept (accept_socket, &error);
694 g_simple_async_result_set_op_res_gpointer (data->simple, socket,
696 source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
698 g_object_set_qdata_full (G_OBJECT (data->simple),
700 g_object_ref (source_object), g_object_unref);
706 g_simple_async_result_set_from_error (data->simple, error);
707 g_error_free (error);
710 g_simple_async_result_complete_in_idle (data->simple);
711 g_object_unref (data->simple);
712 free_sources (data->sources);
719 * g_socket_listener_accept_socket_async:
720 * @listener: a #GSocketListener
721 * @cancellable: a #GCancellable, or %NULL
722 * @callback: a #GAsyncReadyCallback
723 * @user_data: user data for the callback
725 * This is the asynchronous version of g_socket_listener_accept_socket().
727 * When the operation is finished @callback will be
728 * called. You can then call g_socket_listener_accept_socket_finish()
729 * to get the result of the operation.
734 g_socket_listener_accept_socket_async (GSocketListener *listener,
735 GCancellable *cancellable,
736 GAsyncReadyCallback callback,
739 struct AcceptAsyncData *data;
740 GError *error = NULL;
742 if (!check_listener (listener, &error))
744 g_simple_async_report_gerror_in_idle (G_OBJECT (listener),
747 g_error_free (error);
751 data = g_new0 (struct AcceptAsyncData, 1);
752 data->simple = g_simple_async_result_new (G_OBJECT (listener),
754 g_socket_listener_accept_socket_async);
755 data->cancellable = cancellable;
756 data->sources = add_sources (listener,
764 * g_socket_listener_accept_socket_finish:
765 * @listener: a #GSocketListener
766 * @result: a #GAsyncResult.
767 * @source_object: Optional #GObject identifying this source
768 * @error: a #GError location to store the error occuring, or %NULL to
771 * Finishes an async accept operation. See g_socket_listener_accept_socket_async()
773 * Returns: a #GSocket on success, %NULL on error.
778 g_socket_listener_accept_socket_finish (GSocketListener *listener,
779 GAsyncResult *result,
780 GObject **source_object,
784 GSimpleAsyncResult *simple;
786 g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), FALSE);
788 simple = G_SIMPLE_ASYNC_RESULT (result);
790 if (g_simple_async_result_propagate_error (simple, error))
793 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_socket_listener_accept_socket_async);
795 socket = g_simple_async_result_get_op_res_gpointer (simple);
798 *source_object = g_object_get_qdata (G_OBJECT (result), source_quark);
800 return g_object_ref (socket);
804 * g_socket_listener_accept_async:
805 * @listener: a #GSocketListener
806 * @cancellable: a #GCancellable, or %NULL
807 * @callback: a #GAsyncReadyCallback
808 * @user_data: user data for the callback
810 * This is the asynchronous version of g_socket_listener_accept().
812 * When the operation is finished @callback will be
813 * called. You can then call g_socket_listener_accept_socket()
814 * to get the result of the operation.
819 g_socket_listener_accept_async (GSocketListener *listener,
820 GCancellable *cancellable,
821 GAsyncReadyCallback callback,
824 g_socket_listener_accept_socket_async (listener,
831 * g_socket_listener_accept_finish:
832 * @listener: a #GSocketListener
833 * @result: a #GAsyncResult.
834 * @source_object: Optional #GObject identifying this source
835 * @error: a #GError location to store the error occuring, or %NULL to
838 * Finishes an async accept operation. See g_socket_listener_accept_async()
840 * Returns: a #GSocketConnection on success, %NULL on error.
845 g_socket_listener_accept_finish (GSocketListener *listener,
846 GAsyncResult *result,
847 GObject **source_object,
851 GSocketConnection *connection;
853 socket = g_socket_listener_accept_socket_finish (listener,
860 connection = g_socket_connection_factory_create_connection (socket);
861 g_object_unref (socket);
866 * g_socket_listener_set_backlog:
867 * @listener: a #GSocketListener
868 * @listen_backlog: an integer
870 * Sets the listen backlog on the sockets in the listener.
872 * See g_socket_set_listen_backlog() for details
877 g_socket_listener_set_backlog (GSocketListener *listener,
883 if (listener->priv->closed)
886 listener->priv->listen_backlog = listen_backlog;
888 for (i = 0; i < listener->priv->sockets->len; i++)
890 socket = listener->priv->sockets->pdata[i];
891 g_socket_set_listen_backlog (socket, listen_backlog);
896 * g_socket_listener_close:
897 * @listener: a #GSocketListener
899 * Closes all the sockets in the listener.
904 g_socket_listener_close (GSocketListener *listener)
909 g_return_if_fail (G_IS_SOCKET_LISTENER (listener));
911 if (listener->priv->closed)
914 for (i = 0; i < listener->priv->sockets->len; i++)
916 socket = listener->priv->sockets->pdata[i];
917 g_socket_close (socket, NULL);
919 listener->priv->closed = TRUE;
922 #define __G_SOCKET_LISTENER_C__
923 #include "gioaliasdef.c"