Change LGPL-2.1+ to LGPL-2.1-or-later
[platform/upstream/glib.git] / gio / gthreadedsocketservice.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright © 2009 Codethink Limited
4  * Copyright © 2009 Red Hat, Inc
5  *
6  * SPDX-License-Identifier: LGPL-2.1-or-later
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General
19  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20  *
21  * Authors: Ryan Lortie <desrt@desrt.ca>
22  *          Alexander Larsson <alexl@redhat.com>
23  */
24
25 /**
26  * SECTION:gthreadedsocketservice
27  * @title: GThreadedSocketService
28  * @short_description: A threaded GSocketService
29  * @include: gio/gio.h
30  * @see_also: #GSocketService.
31  *
32  * A #GThreadedSocketService is a simple subclass of #GSocketService
33  * that handles incoming connections by creating a worker thread and
34  * dispatching the connection to it by emitting the
35  * #GThreadedSocketService::run signal in the new thread.
36  *
37  * The signal handler may perform blocking IO and need not return
38  * until the connection is closed.
39  *
40  * The service is implemented using a thread pool, so there is a
41  * limited amount of threads available to serve incoming requests.
42  * The service automatically stops the #GSocketService from accepting
43  * new connections when all threads are busy.
44  *
45  * As with #GSocketService, you may connect to #GThreadedSocketService::run,
46  * or subclass and override the default handler.
47  */
48
49 #include "config.h"
50 #include "gsocketconnection.h"
51 #include "gthreadedsocketservice.h"
52 #include "glibintl.h"
53 #include "gmarshal-internal.h"
54
55 struct _GThreadedSocketServicePrivate
56 {
57   GThreadPool *thread_pool;
58   int max_threads;
59   gint job_count;
60 };
61
62 static guint g_threaded_socket_service_run_signal;
63
64 G_DEFINE_TYPE_WITH_PRIVATE (GThreadedSocketService,
65                             g_threaded_socket_service,
66                             G_TYPE_SOCKET_SERVICE)
67
68 typedef enum
69 {
70   PROP_MAX_THREADS = 1,
71 } GThreadedSocketServiceProperty;
72
73 G_LOCK_DEFINE_STATIC(job_count);
74
75 typedef struct
76 {
77   GThreadedSocketService *service;  /* (owned) */
78   GSocketConnection *connection;  /* (owned) */
79   GObject *source_object;  /* (owned) (nullable) */
80 } GThreadedSocketServiceData;
81
82 static void
83 g_threaded_socket_service_data_free (GThreadedSocketServiceData *data)
84 {
85   g_clear_object (&data->service);
86   g_clear_object (&data->connection);
87   g_clear_object (&data->source_object);
88   g_slice_free (GThreadedSocketServiceData, data);
89 }
90
91 static void
92 g_threaded_socket_service_func (gpointer job_data,
93                                 gpointer user_data)
94 {
95   GThreadedSocketServiceData *data = job_data;
96   gboolean result;
97
98   g_signal_emit (data->service, g_threaded_socket_service_run_signal,
99                  0, data->connection, data->source_object, &result);
100
101   G_LOCK (job_count);
102   if (data->service->priv->job_count-- == data->service->priv->max_threads)
103     g_socket_service_start (G_SOCKET_SERVICE (data->service));
104   G_UNLOCK (job_count);
105
106   g_threaded_socket_service_data_free (data);
107 }
108
109 static gboolean
110 g_threaded_socket_service_incoming (GSocketService    *service,
111                                     GSocketConnection *connection,
112                                     GObject           *source_object)
113 {
114   GThreadedSocketService *threaded;
115   GThreadedSocketServiceData *data;
116   GError *local_error = NULL;
117
118   threaded = G_THREADED_SOCKET_SERVICE (service);
119
120   data = g_slice_new0 (GThreadedSocketServiceData);
121   data->service = g_object_ref (threaded);
122   data->connection = g_object_ref (connection);
123   data->source_object = (source_object != NULL) ? g_object_ref (source_object) : NULL;
124
125   G_LOCK (job_count);
126   if (++threaded->priv->job_count == threaded->priv->max_threads)
127     g_socket_service_stop (service);
128   G_UNLOCK (job_count);
129
130   if (!g_thread_pool_push (threaded->priv->thread_pool, data, &local_error))
131     {
132       g_warning ("Error handling incoming socket: %s", local_error->message);
133       g_threaded_socket_service_data_free (data);
134     }
135
136   g_clear_error (&local_error);
137
138   return FALSE;
139 }
140
141 static void
142 g_threaded_socket_service_init (GThreadedSocketService *service)
143 {
144   service->priv = g_threaded_socket_service_get_instance_private (service);
145   service->priv->max_threads = 10;
146 }
147
148 static void
149 g_threaded_socket_service_constructed (GObject *object)
150 {
151   GThreadedSocketService *service = G_THREADED_SOCKET_SERVICE (object);
152
153   service->priv->thread_pool =
154     g_thread_pool_new  (g_threaded_socket_service_func,
155                         NULL,
156                         service->priv->max_threads,
157                         FALSE,
158                         NULL);
159 }
160
161
162 static void
163 g_threaded_socket_service_finalize (GObject *object)
164 {
165   GThreadedSocketService *service = G_THREADED_SOCKET_SERVICE (object);
166
167   /* All jobs in the pool hold a reference to this #GThreadedSocketService, so
168    * this should only be called once the pool is empty: */
169   g_thread_pool_free (service->priv->thread_pool, FALSE, FALSE);
170
171   G_OBJECT_CLASS (g_threaded_socket_service_parent_class)
172     ->finalize (object);
173 }
174
175 static void
176 g_threaded_socket_service_get_property (GObject    *object,
177                                         guint       prop_id,
178                                         GValue     *value,
179                                         GParamSpec *pspec)
180 {
181   GThreadedSocketService *service = G_THREADED_SOCKET_SERVICE (object);
182
183   switch ((GThreadedSocketServiceProperty) prop_id)
184     {
185       case PROP_MAX_THREADS:
186         g_value_set_int (value, service->priv->max_threads);
187         break;
188
189       default:
190         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
191     }
192 }
193
194 static void
195 g_threaded_socket_service_set_property (GObject      *object,
196                                         guint         prop_id,
197                                         const GValue *value,
198                                         GParamSpec   *pspec)
199 {
200   GThreadedSocketService *service = G_THREADED_SOCKET_SERVICE (object);
201
202   switch ((GThreadedSocketServiceProperty) prop_id)
203     {
204       case PROP_MAX_THREADS:
205         service->priv->max_threads = g_value_get_int (value);
206         break;
207
208       default:
209         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
210     }
211 }
212
213
214 static void
215 g_threaded_socket_service_class_init (GThreadedSocketServiceClass *class)
216 {
217   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
218   GSocketServiceClass *ss_class = &class->parent_class;
219
220   gobject_class->constructed = g_threaded_socket_service_constructed;
221   gobject_class->finalize = g_threaded_socket_service_finalize;
222   gobject_class->set_property = g_threaded_socket_service_set_property;
223   gobject_class->get_property = g_threaded_socket_service_get_property;
224
225   ss_class->incoming = g_threaded_socket_service_incoming;
226
227   /**
228    * GThreadedSocketService::run:
229    * @service: the #GThreadedSocketService.
230    * @connection: a new #GSocketConnection object.
231    * @source_object: (nullable): the source_object passed to g_socket_listener_add_address().
232    *
233    * The ::run signal is emitted in a worker thread in response to an
234    * incoming connection. This thread is dedicated to handling
235    * @connection and may perform blocking IO. The signal handler need
236    * not return until the connection is closed.
237    *
238    * Returns: %TRUE to stop further signal handlers from being called
239    */
240   g_threaded_socket_service_run_signal =
241     g_signal_new (I_("run"), G_TYPE_FROM_CLASS (class), G_SIGNAL_RUN_LAST,
242                   G_STRUCT_OFFSET (GThreadedSocketServiceClass, run),
243                   g_signal_accumulator_true_handled, NULL,
244                   _g_cclosure_marshal_BOOLEAN__OBJECT_OBJECT,
245                   G_TYPE_BOOLEAN,
246                   2, G_TYPE_SOCKET_CONNECTION, G_TYPE_OBJECT);
247   g_signal_set_va_marshaller (g_threaded_socket_service_run_signal,
248                               G_TYPE_FROM_CLASS (class),
249                               _g_cclosure_marshal_BOOLEAN__OBJECT_OBJECTv);
250
251   g_object_class_install_property (gobject_class, PROP_MAX_THREADS,
252                                    g_param_spec_int ("max-threads",
253                                                      P_("Max threads"),
254                                                      P_("The max number of threads handling clients for this service"),
255                                                      -1,
256                                                      G_MAXINT,
257                                                      10,
258                                                      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
259 }
260
261 /**
262  * g_threaded_socket_service_new:
263  * @max_threads: the maximal number of threads to execute concurrently
264  *   handling incoming clients, -1 means no limit
265  *
266  * Creates a new #GThreadedSocketService with no listeners. Listeners
267  * must be added with one of the #GSocketListener "add" methods.
268  *
269  * Returns: a new #GSocketService.
270  *
271  * Since: 2.22
272  */
273 GSocketService *
274 g_threaded_socket_service_new (int max_threads)
275 {
276   return g_object_new (G_TYPE_THREADED_SOCKET_SERVICE,
277                        "max-threads", max_threads,
278                        NULL);
279 }