multithreaded service
[platform/upstream/libwebsockets.git] / lib / context.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2015 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23
24 #ifndef LWS_BUILD_HASH
25 #define LWS_BUILD_HASH "unknown-build-hash"
26 #endif
27
28 static const char *library_version = LWS_LIBRARY_VERSION " " LWS_BUILD_HASH;
29
30 /**
31  * lws_get_library_version: get version and git hash library built from
32  *
33  *      returns a const char * to a string like "1.1 178d78c"
34  *      representing the library version followed by the git head hash it
35  *      was built from
36  */
37
38 LWS_VISIBLE const char *
39 lws_get_library_version(void)
40 {
41         return library_version;
42 }
43
44 /**
45  * lws_create_context() - Create the websocket handler
46  * @info:       pointer to struct with parameters
47  *
48  *      This function creates the listening socket (if serving) and takes care
49  *      of all initialization in one step.
50  *
51  *      After initialization, it returns a struct lws_context * that
52  *      represents this server.  After calling, user code needs to take care
53  *      of calling lws_service() with the context pointer to get the
54  *      server's sockets serviced.  This must be done in the same process
55  *      context as the initialization call.
56  *
57  *      The protocol callback functions are called for a handful of events
58  *      including http requests coming in, websocket connections becoming
59  *      established, and data arriving; it's also called periodically to allow
60  *      async transmission.
61  *
62  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
63  *      at that time websocket protocol has not been negotiated.  Other
64  *      protocols after the first one never see any HTTP callack activity.
65  *
66  *      The server created is a simple http server by default; part of the
67  *      websocket standard is upgrading this http connection to a websocket one.
68  *
69  *      This allows the same server to provide files like scripts and favicon /
70  *      images or whatever over http and dynamic data over websockets all in
71  *      one place; they're all handled in the user callback.
72  */
73
74 LWS_VISIBLE struct lws_context *
75 lws_create_context(struct lws_context_creation_info *info)
76 {
77         struct lws_context *context = NULL;
78         struct lws wsi;
79 #ifndef LWS_NO_DAEMONIZE
80         int pid_daemon = get_daemonize_pid();
81 #endif
82         char *p;
83         int n;
84
85         lwsl_notice("Initial logging level %d\n", log_level);
86
87         lwsl_notice("Libwebsockets version: %s\n", library_version);
88 #if LWS_POSIX
89 #ifdef LWS_USE_IPV6
90         if (!(info->options & LWS_SERVER_OPTION_DISABLE_IPV6))
91                 lwsl_notice("IPV6 compiled in and enabled\n");
92         else
93                 lwsl_notice("IPV6 compiled in but disabled\n");
94 #else
95         lwsl_notice("IPV6 not compiled in\n");
96 #endif
97         lws_feature_status_libev(info);
98 #endif
99         lwsl_info(" LWS_MAX_HEADER_LEN    : %u\n", LWS_MAX_HEADER_LEN);
100         lwsl_info(" LWS_MAX_PROTOCOLS     : %u\n", LWS_MAX_PROTOCOLS);
101         lwsl_info(" LWS_MAX_SMP           : %u\n", LWS_MAX_SMP);
102         lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
103         lwsl_info(" AWAITING_TIMEOUT      : %u\n", AWAITING_TIMEOUT);
104         lwsl_info(" sizeof (*info)        : %u\n", sizeof(*info));
105 #if LWS_POSIX
106         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
107 #endif
108         if (lws_plat_context_early_init())
109                 return NULL;
110
111         context = lws_zalloc(sizeof(struct lws_context));
112         if (!context) {
113                 lwsl_err("No memory for websocket context\n");
114                 return NULL;
115         }
116 #ifndef LWS_NO_DAEMONIZE
117         if (pid_daemon) {
118                 context->started_with_parent = pid_daemon;
119                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
120         }
121 #endif
122         context->max_fds = getdtablesize();
123
124         if (info->count_threads)
125                 context->count_threads = info->count_threads;
126         else
127                 context->count_threads = 1;
128
129         if (context->count_threads > LWS_MAX_SMP)
130                 context->count_threads = LWS_MAX_SMP;
131
132         context->lserv_seen = 0;
133         context->protocols = info->protocols;
134         context->token_limits = info->token_limits;
135         context->listen_port = info->port;
136         context->http_proxy_port = 0;
137         context->http_proxy_address[0] = '\0';
138         context->options = info->options;
139         context->iface = info->iface;
140         context->ka_time = info->ka_time;
141         context->ka_interval = info->ka_interval;
142         context->ka_probes = info->ka_probes;
143
144         /* we zalloc only the used ones, so the memory is not wasted
145          * allocating for unused threads
146          */
147         for (n = 0; n < context->count_threads; n++) {
148                 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
149                 if (!context->pt[n].serv_buf) {
150                         lwsl_err("OOM\n");
151                         return NULL;
152                 }
153         }
154
155         if (info->fd_limit_per_thread)
156                 context->fd_limit_per_thread = info->fd_limit_per_thread;
157         else
158                 context->fd_limit_per_thread = context->max_fds /
159                                                context->count_threads;
160
161         lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
162                     context->fd_limit_per_thread);
163
164         memset(&wsi, 0, sizeof(wsi));
165         wsi.context = context;
166
167         if (!info->ka_interval && info->ka_time > 0) {
168                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
169                 return NULL;
170         }
171
172 #ifdef LWS_USE_LIBEV
173         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
174          * enable libev mediated SIGINT handling with a default handler of
175          * lws_sigint_cb. The handler can be overridden or disabled
176          * by invoking lws_sigint_cfg after creating the context, but
177          * before invoking lws_initloop:
178          */
179         context->use_ev_sigint = 1;
180         context->lws_ev_sigint_cb = &lws_sigint_cb;
181 #endif /* LWS_USE_LIBEV */
182
183         lwsl_info(" mem: context:         %5u bytes (%d + (%d x %d))\n",
184                   sizeof(struct lws_context) +
185                   (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
186                   sizeof(struct lws_context),
187                   context->count_threads,
188                   LWS_MAX_SOCKET_IO_BUF);
189
190         /*
191          * allocate and initialize the pool of
192          * allocated_header structs + data
193          */
194         if (info->max_http_header_data)
195                 context->max_http_header_data = info->max_http_header_data;
196         else
197                 context->max_http_header_data = LWS_MAX_HEADER_LEN;
198         if (info->max_http_header_pool)
199                 context->max_http_header_pool = info->max_http_header_pool;
200         else
201                 context->max_http_header_pool = LWS_MAX_HEADER_POOL;
202
203         context->http_header_data = lws_malloc(context->max_http_header_data *
204                                                context->max_http_header_pool);
205         if (!context->http_header_data)
206                 goto bail;
207         context->ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
208                                       context->max_http_header_pool);
209         if (!context->ah_pool)
210                 goto bail;
211
212         for (n = 0; n < context->max_http_header_pool; n++)
213                 context->ah_pool[n].data = (char *)context->http_header_data +
214                         (n * context->max_http_header_data);
215
216         /* this is per context */
217         lwsl_info(" mem: http hdr rsvd:   %5u bytes ((%u + %u) x %u)\n",
218                     (context->max_http_header_data +
219                      sizeof(struct allocated_headers)) *
220                     context->max_http_header_pool,
221                     context->max_http_header_data,
222                     sizeof(struct allocated_headers),
223                     context->max_http_header_pool);
224         n = sizeof(struct lws_pollfd) * context->count_threads *
225             context->fd_limit_per_thread;
226         context->pt[0].fds = lws_zalloc(n);
227         if (context->pt[0].fds == NULL) {
228                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
229                 goto bail;
230         }
231         lwsl_info(" mem: pollfd map:      %5u\n", n);
232         /* each thread serves his own chunk of fds */
233         for (n = 1; n < (int)info->count_threads; n++)
234                 context->pt[n].fds = context->pt[0].fds +
235                                   (n * context->fd_limit_per_thread);
236
237         if (lws_plat_init(context, info))
238                 goto bail;
239
240         lws_context_init_extensions(info, context);
241
242         context->user_space = info->user;
243
244         lwsl_notice(" mem: per-conn:        %5u bytes + protocol rx buf\n",
245                     sizeof(struct lws));
246
247         strcpy(context->canonical_hostname, "unknown");
248         lws_server_get_canonical_hostname(context, info);
249
250         /* either use proxy from info, or try get it from env var */
251
252         if (info->http_proxy_address) {
253                 /* override for backwards compatibility */
254                 if (info->http_proxy_port)
255                         context->http_proxy_port = info->http_proxy_port;
256                 lws_set_proxy(context, info->http_proxy_address);
257         } else {
258 #ifdef LWS_HAVE_GETENV
259                 p = getenv("http_proxy");
260                 if (p)
261                         lws_set_proxy(context, p);
262 #endif
263         }
264
265         if (lws_context_init_server_ssl(info, context))
266                 goto bail;
267
268         if (lws_context_init_client_ssl(info, context))
269                 goto bail;
270
271         if (lws_context_init_server(info, context))
272                 goto bail;
273
274         /*
275          * drop any root privs for this process
276          * to listen on port < 1023 we would have needed root, but now we are
277          * listening, we don't want the power for anything else
278          */
279         lws_plat_drop_app_privileges(info);
280
281         /* initialize supported protocols */
282
283         for (context->count_protocols = 0;
284              info->protocols[context->count_protocols].callback;
285              context->count_protocols++)
286                 /*
287                  * inform all the protocols that they are doing their one-time
288                  * initialization if they want to.
289                  *
290                  * NOTE the wsi is all zeros except for the context pointer
291                  * so lws_get_context(wsi) can work in the callback.
292                  */
293                 info->protocols[context->count_protocols].callback(&wsi,
294                                 LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
295
296         /*
297          * give all extensions a chance to create any per-context
298          * allocations they need
299          */
300         if (info->port != CONTEXT_PORT_NO_LISTEN) {
301                 if (lws_ext_cb_all_exts(context, NULL,
302                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
303                         goto bail;
304         } else
305                 if (lws_ext_cb_all_exts(context, NULL,
306                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
307                         goto bail;
308
309         return context;
310
311 bail:
312         lws_context_destroy(context);
313         return NULL;
314 }
315
316 /**
317  * lws_context_destroy() - Destroy the websocket context
318  * @context:    Websocket context
319  *
320  *      This function closes any active connections and then frees the
321  *      context.  After calling this, any further use of the context is
322  *      undefined.
323  */
324 LWS_VISIBLE void
325 lws_context_destroy(struct lws_context *context)
326 {
327         const struct lws_protocols *protocol = NULL;
328         struct lws wsi;
329         int n, m = context->count_threads;
330
331         lwsl_notice("%s\n", __func__);
332
333         if (!context)
334                 return;
335
336         context->being_destroyed = 1;
337
338         memset(&wsi, 0, sizeof(wsi));
339         wsi.context = context;
340
341 #ifdef LWS_LATENCY
342         if (context->worst_latency_info[0])
343                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
344 #endif
345
346         while (m--)
347                 for (n = 0; n < context->pt[m].fds_count; n++) {
348                         struct lws *wsi = wsi_from_fd(context, context->pt[m].fds[n].fd);
349                         if (!wsi)
350                                 continue;
351                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
352                                 /* no protocol close */);
353                         n--;
354                 }
355
356         /*
357          * give all extensions a chance to clean up any per-context
358          * allocations they might have made
359          */
360
361         n = lws_ext_cb_all_exts(context, NULL,
362                         LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
363
364         n = lws_ext_cb_all_exts(context, NULL,
365                         LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
366
367         /*
368          * inform all the protocols that they are done and will have no more
369          * callbacks
370          */
371         protocol = context->protocols;
372         if (protocol) {
373                 while (protocol->callback) {
374                         protocol->callback(&wsi,
375                                            LWS_CALLBACK_PROTOCOL_DESTROY,
376                                            NULL, NULL, 0);
377                         protocol++;
378                 }
379         }
380 #ifdef LWS_USE_LIBEV
381         ev_io_stop(context->io_loop, &context->w_accept.watcher);
382         if(context->use_ev_sigint)
383                 ev_signal_stop(context->io_loop, &context->w_sigint.watcher);
384 #endif /* LWS_USE_LIBEV */
385
386         for (n = 0; n < context->count_threads; n++)
387                 lws_free_set_NULL(context->pt[n].serv_buf);
388
389         lws_plat_context_early_destroy(context);
390         lws_ssl_context_destroy(context);
391         if (context->pt[0].fds)
392                 lws_free(context->pt[0].fds);
393         if (context->ah_pool)
394                 lws_free(context->ah_pool);
395         if (context->http_header_data)
396                 lws_free(context->http_header_data);
397
398         lws_plat_context_late_destroy(context);
399
400         lws_free(context);
401 }