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 * @error: #GError for error reporting, or %NULL to ignore.
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
259 * @source_object will be passed out in the various calls
260 * to accept to identify this particular source, which is
261 * useful if you're listening on multiple addresses and do
262 * different things depending on what address is connected to.
264 * Returns: %TRUE on success, %FALSE on error.
269 g_socket_listener_add_address (GSocketListener *listener,
270 GSocketAddress *address,
272 GSocketProtocol protocol,
273 GObject *source_object,
276 GSocketFamily family;
279 if (!check_listener (listener, error))
282 family = g_socket_address_get_family (address);
283 socket = g_socket_new (family, type, protocol, error);
287 g_socket_set_listen_backlog (socket, listener->priv->listen_backlog);
289 if (!g_socket_bind (socket, address, TRUE, error) ||
290 !g_socket_listen (socket, error) ||
291 !g_socket_listener_add_socket (listener, socket,
295 g_object_unref (socket);
299 if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
300 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
306 * g_socket_listener_add_inet_port:
307 * @listener: a #GSocketListener
308 * @port: an ip port number
309 * @source_object: Optional #GObject identifying this source
310 * @error: #GError for error reporting, or %NULL to ignore.
312 * Helper function for g_socket_listener_add_address() that
313 * creates a TCP/IP socket listening on IPv4 and IPv6 (if
314 * supported) on the specified port on all interfaces.
316 * @source_object will be passed out in the various calls
317 * to accept to identify this particular source, which is
318 * useful if you're listening on multiple addresses and do
319 * different things depending on what address is connected to.
321 * Returns: %TRUE on success, %FALSE on error.
326 g_socket_listener_add_inet_port (GSocketListener *listener,
328 GObject *source_object,
331 GSocketAddress *address4, *address6;
332 GInetAddress *inet_address;
335 if (!check_listener (listener, error))
338 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
339 address4 = g_inet_socket_address_new (inet_address, port);
340 g_object_unref (inet_address);
342 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
343 address6 = g_inet_socket_address_new (inet_address, port);
344 g_object_unref (inet_address);
346 if (!g_socket_listener_add_address (listener,
348 G_SOCKET_TYPE_STREAM,
349 G_SOCKET_PROTOCOL_DEFAULT,
353 /* Failed, to create ipv6, socket, just use ipv4,
355 res = g_socket_listener_add_address (listener,
357 G_SOCKET_TYPE_STREAM,
358 G_SOCKET_PROTOCOL_DEFAULT,
364 /* Succeeded with ipv6, also try ipv4 in case its ipv6 only,
365 but ignore errors here */
367 g_socket_listener_add_address (listener,
369 G_SOCKET_TYPE_STREAM,
370 G_SOCKET_PROTOCOL_DEFAULT,
375 g_object_unref (address4);
376 g_object_unref (address6);
382 add_sources (GSocketListener *listener,
383 GSocketSourceFunc callback,
384 gpointer callback_data,
385 GCancellable *cancellable,
386 GMainContext *context)
394 for (i = 0; i < listener->priv->sockets->len; i++)
396 socket = listener->priv->sockets->pdata[i];
398 source = g_socket_create_source (socket, G_IO_IN, cancellable);
399 g_source_set_callback (source,
400 (GSourceFunc) callback,
401 callback_data, NULL);
402 g_source_attach (source, context);
404 sources = g_list_prepend (sources, source);
411 free_sources (GList *sources)
414 while (sources != NULL)
416 source = sources->data;
417 sources = g_list_delete_link (sources, sources);
418 g_source_destroy (source);
419 g_source_unref (source);
429 accept_callback (GSocket *socket,
430 GIOCondition condition,
433 struct AcceptData *data = user_data;
435 data->socket = socket;
436 g_main_loop_quit (data->loop);
442 * g_socket_listener_accept_socket:
443 * @listener: a #GSocketListener
444 * @source_object: location where #GObject pointer will be stored, or %NULL
445 * @cancellable: optional #GCancellable object, %NULL to ignore.
446 * @error: #GError for error reporting, or %NULL to ignore.
448 * Blocks waiting for a client to connect to any of the sockets added
449 * to the listener. Returns the #GSocket that was accepted.
451 * If you want to accept the high-level #GSocketConnection, not a #GSocket,
452 * which is often the case, then you should use g_socket_listener_accept()
455 * If @source_object is not %NULL it will be filled out with the source
456 * object specified when the corresponding socket or address was added
459 * If @cancellable is not %NULL, then the operation can be cancelled by
460 * triggering the cancellable object from another thread. If the operation
461 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
463 * Returns: a #GSocket on success, %NULL on error.
468 g_socket_listener_accept_socket (GSocketListener *listener,
469 GObject **source_object,
470 GCancellable *cancellable,
473 GSocket *accept_socket, *socket;
475 g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
477 if (!check_listener (listener, error))
480 if (listener->priv->sockets->len == 1)
482 accept_socket = listener->priv->sockets->pdata[0];
483 if (!g_socket_condition_wait (accept_socket, G_IO_IN,
490 struct AcceptData data;
493 if (listener->priv->main_context == NULL)
494 listener->priv->main_context = g_main_context_new ();
496 loop = g_main_loop_new (listener->priv->main_context, FALSE);
498 sources = add_sources (listener,
502 listener->priv->main_context);
503 g_main_loop_run (loop);
504 accept_socket = data.socket;
505 free_sources (sources);
506 g_main_loop_unref (loop);
509 if (!(socket = g_socket_accept (accept_socket, error)))
513 *source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
519 * g_socket_listener_accept:
520 * @listener: a #GSocketListener
521 * @source_object: location where #GObject pointer will be stored, or %NULL
522 * @cancellable: optional #GCancellable object, %NULL to ignore.
523 * @error: #GError for error reporting, or %NULL to ignore.
525 * Blocks waiting for a client to connect to any of the sockets added
526 * to the listener. Returns a #GSocketConnection for the socket that was
529 * If @source_object is not %NULL it will be filled out with the source
530 * object specified when the corresponding socket or address was added
533 * If @cancellable is not %NULL, then the operation can be cancelled by
534 * triggering the cancellable object from another thread. If the operation
535 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
537 * Returns: a #GSocketConnection on success, %NULL on error.
542 g_socket_listener_accept (GSocketListener *listener,
543 GObject **source_object,
544 GCancellable *cancellable,
547 GSocketConnection *connection;
550 socket = g_socket_listener_accept_socket (listener,
557 connection = g_socket_connection_factory_create_connection (socket);
558 g_object_unref (socket);
563 struct AcceptAsyncData {
564 GSimpleAsyncResult *simple;
565 GCancellable *cancellable;
570 accept_ready (GSocket *accept_socket,
571 GIOCondition condition,
574 struct AcceptAsyncData *data = _data;
575 GError *error = NULL;
577 if (!g_cancellable_set_error_if_cancelled (data->cancellable,
581 GObject *source_object;
583 socket = g_socket_accept (accept_socket, &error);
586 g_simple_async_result_set_op_res_gpointer (data->simple, socket,
588 source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
590 g_object_set_qdata_full (G_OBJECT (data->simple),
592 g_object_ref (source_object), g_object_unref);
598 g_simple_async_result_set_from_error (data->simple, error);
599 g_error_free (error);
602 g_simple_async_result_complete_in_idle (data->simple);
603 g_object_unref (data->simple);
604 free_sources (data->sources);
611 * g_socket_listener_accept_socket_async:
612 * @listener: a #GSocketListener
613 * @cancellable: a #GCancellable, or %NULL
614 * @callback: a #GAsyncReadyCallback
615 * @user_data: user data for the callback
617 * This is the asynchronous version of g_socket_listener_accept_socket().
619 * When the operation is finished @callback will be
620 * called. You can then call g_socket_listener_accept_socket_finish()
621 * to get the result of the operation.
626 g_socket_listener_accept_socket_async (GSocketListener *listener,
627 GCancellable *cancellable,
628 GAsyncReadyCallback callback,
631 struct AcceptAsyncData *data;
632 GError *error = NULL;
634 if (!check_listener (listener, &error))
636 g_simple_async_report_gerror_in_idle (G_OBJECT (listener),
639 g_error_free (error);
643 data = g_new0 (struct AcceptAsyncData, 1);
644 data->simple = g_simple_async_result_new (G_OBJECT (listener),
646 g_socket_listener_accept_socket_async);
647 data->cancellable = cancellable;
648 data->sources = add_sources (listener,
656 * g_socket_listener_accept_socket_finish:
657 * @listener: a #GSocketListener
658 * @result: a #GAsyncResult.
659 * @source_object: Optional #GObject identifying this source
660 * @error: a #GError location to store the error occuring, or %NULL to
663 * Finishes an async accept operation. See g_socket_listener_accept_socket_async()
665 * Returns: a #GSocket on success, %NULL on error.
670 g_socket_listener_accept_socket_finish (GSocketListener *listener,
671 GAsyncResult *result,
672 GObject **source_object,
676 GSimpleAsyncResult *simple;
678 g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), FALSE);
680 simple = G_SIMPLE_ASYNC_RESULT (result);
682 if (g_simple_async_result_propagate_error (simple, error))
685 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_socket_listener_accept_socket_async);
687 socket = g_simple_async_result_get_op_res_gpointer (simple);
690 *source_object = g_object_get_qdata (G_OBJECT (result), source_quark);
692 return g_object_ref (socket);
696 * g_socket_listener_accept_async:
697 * @listener: a #GSocketListener
698 * @cancellable: a #GCancellable, or %NULL
699 * @callback: a #GAsyncReadyCallback
700 * @user_data: user data for the callback
702 * This is the asynchronous version of g_socket_listener_accept().
704 * When the operation is finished @callback will be
705 * called. You can then call g_socket_listener_accept_socket()
706 * to get the result of the operation.
711 g_socket_listener_accept_async (GSocketListener *listener,
712 GCancellable *cancellable,
713 GAsyncReadyCallback callback,
716 g_socket_listener_accept_socket_async (listener,
723 * g_socket_listener_accept_finish:
724 * @listener: a #GSocketListener
725 * @result: a #GAsyncResult.
726 * @source_object: Optional #GObject identifying this source
727 * @error: a #GError location to store the error occuring, or %NULL to
730 * Finishes an async accept operation. See g_socket_listener_accept_async()
732 * Returns: a #GSocketConnection on success, %NULL on error.
737 g_socket_listener_accept_finish (GSocketListener *listener,
738 GAsyncResult *result,
739 GObject **source_object,
743 GSocketConnection *connection;
745 socket = g_socket_listener_accept_socket_finish (listener,
752 connection = g_socket_connection_factory_create_connection (socket);
753 g_object_unref (socket);
758 * g_socket_listener_set_backlog:
759 * @listener: a #GSocketListener
760 * @listen_backlog: an integer
762 * Sets the listen backlog on the sockets in the listener.
764 * See g_socket_set_listen_backlog() for details
769 g_socket_listener_set_backlog (GSocketListener *listener,
775 if (listener->priv->closed)
778 listener->priv->listen_backlog = listen_backlog;
780 for (i = 0; i < listener->priv->sockets->len; i++)
782 socket = listener->priv->sockets->pdata[i];
783 g_socket_set_listen_backlog (socket, listen_backlog);
788 * g_socket_listener_close:
789 * @listener: a #GSocketListener
791 * Closes all the sockets in the listener.
796 g_socket_listener_close (GSocketListener *listener)
801 g_return_if_fail (G_IS_SOCKET_LISTENER (listener));
803 if (listener->priv->closed)
806 for (i = 0; i < listener->priv->sockets->len; i++)
808 socket = listener->priv->sockets->pdata[i];
809 g_socket_close (socket, NULL);
811 listener->priv->closed = TRUE;
814 #define __G_SOCKET_LISTENER_C__
815 #include "gioaliasdef.c"