client: protect against possible NULL deref path
[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 LWS_VISIBLE const char *
38 lws_get_library_version(void)
39 {
40         return library_version;
41 }
42
43 /**
44  * lws_create_context() - Create the websocket handler
45  * @info:       pointer to struct with parameters
46  *
47  *      This function creates the listening socket (if serving) and takes care
48  *      of all initialization in one step.
49  *
50  *      After initialization, it returns a struct lws_context * that
51  *      represents this server.  After calling, user code needs to take care
52  *      of calling lws_service() with the context pointer to get the
53  *      server's sockets serviced.  This must be done in the same process
54  *      context as the initialization call.
55  *
56  *      The protocol callback functions are called for a handful of events
57  *      including http requests coming in, websocket connections becoming
58  *      established, and data arriving; it's also called periodically to allow
59  *      async transmission.
60  *
61  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
62  *      at that time websocket protocol has not been negotiated.  Other
63  *      protocols after the first one never see any HTTP callack activity.
64  *
65  *      The server created is a simple http server by default; part of the
66  *      websocket standard is upgrading this http connection to a websocket one.
67  *
68  *      This allows the same server to provide files like scripts and favicon /
69  *      images or whatever over http and dynamic data over websockets all in
70  *      one place; they're all handled in the user callback.
71  */
72 LWS_VISIBLE struct lws_context *
73 lws_create_context(struct lws_context_creation_info *info)
74 {
75         struct lws_context *context = NULL;
76         struct lws wsi;
77 #ifndef LWS_NO_DAEMONIZE
78         int pid_daemon = get_daemonize_pid();
79 #endif
80         char *p;
81         int n, m;
82 #if defined(__ANDROID__)
83         struct rlimit rt;
84 #endif
85
86
87         lwsl_notice("Initial logging level %d\n", log_level);
88         lwsl_notice("Libwebsockets version: %s\n", library_version);
89 #if LWS_POSIX
90 #ifdef LWS_USE_IPV6
91         if (!(info->options & LWS_SERVER_OPTION_DISABLE_IPV6))
92                 lwsl_notice("IPV6 compiled in and enabled\n");
93         else
94                 lwsl_notice("IPV6 compiled in but disabled\n");
95 #else
96         lwsl_notice("IPV6 not compiled in\n");
97 #endif
98         lws_feature_status_libev(info);
99 #endif
100         lwsl_info(" LWS_DEF_HEADER_LEN    : %u\n", LWS_DEF_HEADER_LEN);
101         lwsl_info(" LWS_MAX_PROTOCOLS     : %u\n", LWS_MAX_PROTOCOLS);
102         lwsl_info(" LWS_MAX_SMP           : %u\n", LWS_MAX_SMP);
103         lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
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 #if defined(__ANDROID__)
123                 n = getrlimit ( RLIMIT_NOFILE,&rt);
124                 if (-1 == n) {
125                         lwsl_err("Get RLIMIT_NOFILE failed!\n");
126                         return NULL;
127                 }
128                 context->max_fds = rt.rlim_cur;
129 #else
130                 context->max_fds = getdtablesize();
131 #endif
132
133         if (info->count_threads)
134                 context->count_threads = info->count_threads;
135         else
136                 context->count_threads = 1;
137
138         if (context->count_threads > LWS_MAX_SMP)
139                 context->count_threads = LWS_MAX_SMP;
140
141         context->protocols = info->protocols;
142         context->token_limits = info->token_limits;
143         context->listen_port = info->port;
144         context->http_proxy_port = 0;
145         context->http_proxy_address[0] = '\0';
146         context->options = info->options;
147         context->iface = info->iface;
148         context->ka_time = info->ka_time;
149         context->ka_interval = info->ka_interval;
150         context->ka_probes = info->ka_probes;
151         if (info->timeout_secs)
152                 context->timeout_secs = info->timeout_secs;
153         else
154                 context->timeout_secs = AWAITING_TIMEOUT;
155
156         lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
157
158         if (info->max_http_header_data)
159                 context->max_http_header_data = info->max_http_header_data;
160         else
161                 context->max_http_header_data = LWS_DEF_HEADER_LEN;
162         if (info->max_http_header_pool)
163                 context->max_http_header_pool = info->max_http_header_pool;
164         else
165                 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
166
167         /*
168          * Allocate the per-thread storage for scratchpad buffers,
169          * and header data pool
170          */
171         for (n = 0; n < context->count_threads; n++) {
172                 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
173                 if (!context->pt[n].serv_buf) {
174                         lwsl_err("OOM\n");
175                         return NULL;
176                 }
177
178                 context->pt[n].context = context;
179                 context->pt[n].tid = n;
180                 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
181                                                        context->max_http_header_pool);
182                 if (!context->pt[n].http_header_data)
183                         goto bail;
184
185                 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
186                                               context->max_http_header_pool);
187                 for (m = 0; m < context->max_http_header_pool; m++)
188                         context->pt[n].ah_pool[m].data =
189                                 (char *)context->pt[n].http_header_data +
190                                 (m * context->max_http_header_data);
191                 if (!context->pt[n].ah_pool)
192                         goto bail;
193
194                 lws_pt_mutex_init(&context->pt[n]);
195         }
196
197         if (info->fd_limit_per_thread)
198                 context->fd_limit_per_thread = info->fd_limit_per_thread;
199         else
200                 context->fd_limit_per_thread = context->max_fds /
201                                                context->count_threads;
202
203         lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
204                     context->fd_limit_per_thread);
205
206         memset(&wsi, 0, sizeof(wsi));
207         wsi.context = context;
208
209         if (!info->ka_interval && info->ka_time > 0) {
210                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
211                 return NULL;
212         }
213
214 #ifdef LWS_USE_LIBEV
215         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
216          * enable libev mediated SIGINT handling with a default handler of
217          * lws_sigint_cb. The handler can be overridden or disabled
218          * by invoking lws_sigint_cfg after creating the context, but
219          * before invoking lws_initloop:
220          */
221         context->use_ev_sigint = 1;
222         context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
223 #endif /* LWS_USE_LIBEV */
224 #ifdef LWS_USE_LIBUV
225         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
226          * enable libev mediated SIGINT handling with a default handler of
227          * lws_sigint_cb. The handler can be overridden or disabled
228          * by invoking lws_sigint_cfg after creating the context, but
229          * before invoking lws_initloop:
230          */
231         context->use_ev_sigint = 1;
232         context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
233 #endif
234
235         lwsl_info(" mem: context:         %5u bytes (%d ctx + (%d thr x %d))\n",
236                   sizeof(struct lws_context) +
237                   (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
238                   sizeof(struct lws_context),
239                   context->count_threads,
240                   LWS_MAX_SOCKET_IO_BUF);
241
242         lwsl_info(" mem: http hdr rsvd:   %5u bytes (%u thr x (%u + %u) x %u))\n",
243                     (context->max_http_header_data +
244                      sizeof(struct allocated_headers)) *
245                     context->max_http_header_pool * context->count_threads,
246                     context->count_threads,
247                     context->max_http_header_data,
248                     sizeof(struct allocated_headers),
249                     context->max_http_header_pool);
250         n = sizeof(struct lws_pollfd) * context->count_threads *
251             context->fd_limit_per_thread;
252         context->pt[0].fds = lws_zalloc(n);
253         if (context->pt[0].fds == NULL) {
254                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
255                 goto bail;
256         }
257         lwsl_info(" mem: pollfd map:      %5u\n", n);
258
259 #if LWS_MAX_SMP > 1
260         /* each thread serves his own chunk of fds */
261         for (n = 1; n < (int)info->count_threads; n++)
262                 context->pt[n].fds = context->pt[n - 1].fds +
263                                      context->fd_limit_per_thread;
264 #endif
265
266         if (lws_plat_init(context, info))
267                 goto bail;
268
269         lws_context_init_extensions(info, context);
270
271         context->user_space = info->user;
272
273         lwsl_notice(" mem: per-conn:        %5u bytes + protocol rx buf\n",
274                     sizeof(struct lws));
275
276         strcpy(context->canonical_hostname, "unknown");
277         lws_server_get_canonical_hostname(context, info);
278
279         /* either use proxy from info, or try get it from env var */
280
281         if (info->http_proxy_address) {
282                 /* override for backwards compatibility */
283                 if (info->http_proxy_port)
284                         context->http_proxy_port = info->http_proxy_port;
285                 lws_set_proxy(context, info->http_proxy_address);
286         } else {
287 #ifdef LWS_HAVE_GETENV
288                 p = getenv("http_proxy");
289                 if (p)
290                         lws_set_proxy(context, p);
291 #endif
292         }
293
294         if (lws_context_init_server_ssl(info, context))
295                 goto bail;
296
297         if (lws_context_init_client_ssl(info, context))
298                 goto bail;
299
300         if (lws_context_init_server(info, context))
301                 goto bail;
302
303         /*
304          * drop any root privs for this process
305          * to listen on port < 1023 we would have needed root, but now we are
306          * listening, we don't want the power for anything else
307          */
308         lws_plat_drop_app_privileges(info);
309
310         /* initialize supported protocols */
311
312         for (context->count_protocols = 0;
313              info->protocols[context->count_protocols].callback;
314              context->count_protocols++)
315                 /*
316                  * inform all the protocols that they are doing their one-time
317                  * initialization if they want to.
318                  *
319                  * NOTE the wsi is all zeros except for the context pointer
320                  * so lws_get_context(wsi) can work in the callback.
321                  */
322                 info->protocols[context->count_protocols].callback(&wsi,
323                                 LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
324
325         /*
326          * give all extensions a chance to create any per-context
327          * allocations they need
328          */
329         if (info->port != CONTEXT_PORT_NO_LISTEN) {
330                 if (lws_ext_cb_all_exts(context, NULL,
331                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
332                         goto bail;
333         } else
334                 if (lws_ext_cb_all_exts(context, NULL,
335                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
336                         goto bail;
337
338         return context;
339
340 bail:
341         lws_context_destroy(context);
342         return NULL;
343 }
344
345 /**
346  * lws_context_destroy() - Destroy the websocket context
347  * @context:    Websocket context
348  *
349  *      This function closes any active connections and then frees the
350  *      context.  After calling this, any further use of the context is
351  *      undefined.
352  */
353 LWS_VISIBLE void
354 lws_context_destroy(struct lws_context *context)
355 {
356         const struct lws_protocols *protocol = NULL;
357         struct lws_context_per_thread *pt;
358         struct lws wsi;
359         int n, m;
360
361         lwsl_notice("%s\n", __func__);
362
363         if (!context)
364                 return;
365
366         m = context->count_threads;
367         context->being_destroyed = 1;
368
369         memset(&wsi, 0, sizeof(wsi));
370         wsi.context = context;
371
372 #ifdef LWS_LATENCY
373         if (context->worst_latency_info[0])
374                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
375 #endif
376
377         while (m--) {
378                 pt = &context->pt[m];
379
380                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
381                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
382                         if (!wsi)
383                                 continue;
384
385                         lws_close_free_wsi(wsi,
386                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
387                                 /* no protocol close */);
388                         n--;
389                 }
390                 lws_pt_mutex_destroy(pt);
391         }
392         /*
393          * give all extensions a chance to clean up any per-context
394          * allocations they might have made
395          */
396
397         n = lws_ext_cb_all_exts(context, NULL,
398                                 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
399
400         n = lws_ext_cb_all_exts(context, NULL,
401                                 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
402
403         /*
404          * inform all the protocols that they are done and will have no more
405          * callbacks
406          */
407         protocol = context->protocols;
408         if (protocol)
409                 while (protocol->callback) {
410                         protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
411                                            NULL, NULL, 0);
412                         protocol++;
413                 }
414
415         for (n = 0; n < context->count_threads; n++) {
416                 pt = &context->pt[n];
417
418                 lws_libev_destroyloop(context, n);
419                 lws_libuv_destroyloop(context, n);
420
421                 lws_free_set_NULL(context->pt[n].serv_buf);
422                 if (pt->ah_pool)
423                         lws_free(pt->ah_pool);
424                 if (pt->http_header_data)
425                         lws_free(pt->http_header_data);
426         }
427         lws_plat_context_early_destroy(context);
428         lws_ssl_context_destroy(context);
429         if (context->pt[0].fds)
430                 lws_free_set_NULL(context->pt[0].fds);
431
432         lws_plat_context_late_destroy(context);
433
434         lws_free(context);
435 }