2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2015 Andy Green <andy@warmcat.com>
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.
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.
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,
22 #include "private-libwebsockets.h"
24 #ifndef LWS_BUILD_HASH
25 #define LWS_BUILD_HASH "unknown-build-hash"
28 static const char *library_version = LWS_LIBRARY_VERSION " " LWS_BUILD_HASH;
31 * lws_get_library_version: get version and git hash library built from
33 * returns a const char * to a string like "1.1 178d78c"
34 * representing the library version followed by the git head hash it
37 LWS_VISIBLE const char *
38 lws_get_library_version(void)
40 return library_version;
43 static const char * const mount_protocols[] = {
52 LWS_VISIBLE LWS_EXTERN int
53 lws_write_http_mount(struct lws_http_mount *next, struct lws_http_mount **res,
54 void *store, const char *mountpoint, const char *origin,
57 struct lws_http_mount *m;
59 unsigned long l = (unsigned long)store;
66 m = (struct lws_http_mount *)store;
70 m->mountpoint = mountpoint;
71 m->mountpoint_len = (unsigned char)strlen(mountpoint);
76 for (n = 0; n < ARRAY_SIZE(mount_protocols); n++)
77 if (!strncmp(origin, mount_protocols[n],
78 strlen(mount_protocols[n]))) {
79 m->origin_protocol = n;
80 m->origin = origin + strlen(mount_protocols[n]);
84 if (n == ARRAY_SIZE(mount_protocols)) {
85 lwsl_err("unsupported protocol://\n");
86 return 0; /* ie, fail */
89 return ((char *)store + sizeof(*m)) - (char *)orig;
93 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
98 /* allocate the vh priv array only on demand */
99 if (!vhost->protocol_vh_privs) {
100 vhost->protocol_vh_privs = (void **)lws_zalloc(
101 vhost->count_protocols * sizeof(void *));
102 if (!vhost->protocol_vh_privs)
106 while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
109 if (n == vhost->count_protocols)
112 vhost->protocol_vh_privs[n] = lws_zalloc(size);
113 return vhost->protocol_vh_privs[n];
117 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot)
121 if (!vhost->protocol_vh_privs)
124 while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
127 if (n == vhost->count_protocols) {
128 lwsl_err("%s: unknown protocol %p\n", __func__, prot);
132 return vhost->protocol_vh_privs[n];
135 static struct lws_protocol_vhost_options *
136 lws_vhost_protocol_options(struct lws_vhost *vh, const char *name)
138 struct lws_protocol_vhost_options *pvo = vh->pvo;
141 // lwsl_notice("%s: '%s' '%s'\n", __func__, pvo->name, name);
142 if (!strcmp(pvo->name, name))
151 lws_protocol_init(struct lws_context *context)
153 struct lws_vhost *vh = context->vhost_list;
154 struct lws_protocol_vhost_options *pvo;
158 memset(&wsi, 0, sizeof(wsi));
159 wsi.context = context;
164 /* initialize supported protocols on this vhost */
166 for (n = 0; n < vh->count_protocols; n++) {
167 wsi.protocol = &vh->protocols[n];
169 pvo = lws_vhost_protocol_options(vh,
170 vh->protocols[n].name);
173 * linked list of options specific to
179 * inform all the protocols that they are doing their one-time
180 * initialization if they want to.
182 * NOTE the wsi is all zeros except for the context, vh and
183 * protocol ptrs so lws_get_context(wsi) etc can work
185 vh->protocols[n].callback(&wsi,
186 LWS_CALLBACK_PROTOCOL_INIT, NULL, pvo, 0);
192 context->protocol_init_done = 1;
197 LWS_VISIBLE struct lws_vhost *
198 lws_create_vhost(struct lws_context *context,
199 struct lws_context_creation_info *info,
200 struct lws_http_mount *mounts)
202 struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
203 **vh1 = &context->vhost_list;
204 #ifdef LWS_WITH_PLUGINS
205 struct lws_plugin *plugin = context->plugin_list;
206 struct lws_protocols *lwsp;
214 vh->context = context;
215 if (!info->vhost_name)
216 vh->name = "default";
218 vh->name = info->vhost_name;
220 vh->iface = info->iface;
221 for (vh->count_protocols = 0;
222 info->protocols[vh->count_protocols].callback;
223 vh->count_protocols++)
228 #ifdef LWS_WITH_PLUGINS
231 * give the vhost a unified list of protocols including the
232 * ones that came from plugins
234 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
235 (vh->count_protocols +
236 context->plugin_protocol_count + 1));
240 m = vh->count_protocols;
241 memcpy(lwsp, info->protocols,
242 sizeof(struct lws_protocols) * m);
245 for (n = 0; n < plugin->caps.count_protocols; n++) {
247 * for compatibility's sake, no pvo implies
248 * allow all protocols
250 if (!info->pvo || lws_vhost_protocol_options(vh,
251 plugin->caps.protocols[n].name)) {
253 &plugin->caps.protocols[n],
254 sizeof(struct lws_protocols));
256 vh->count_protocols++;
259 plugin = plugin->list;
261 vh->protocols = lwsp;
264 vh->protocols = info->protocols;
266 vh->mount_list = mounts;
268 lwsl_notice("Creating Vhost '%s' port %d, %d protocols\n",
269 vh->name, info->port, vh->count_protocols);
272 lwsl_notice(" mounting %s%s to %s\n",
273 mount_protocols[mounts->origin_protocol],
274 mounts->origin, mounts->mountpoint);
275 mounts = mounts->mount_next;
278 #ifndef LWS_NO_EXTENSIONS
279 #ifdef LWS_WITH_PLUGINS
280 if (context->plugin_extension_count) {
283 while (info->extensions && info->extensions[m].callback)
287 * give the vhost a unified list of extensions including the
288 * ones that came from plugins
290 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
292 context->plugin_extension_count + 1));
296 memcpy((struct lws_extension *)vh->extensions, info->extensions,
297 sizeof(struct lws_extension) * m);
299 memcpy((struct lws_extension *)&vh->extensions[m], plugin->caps.extensions,
300 sizeof(struct lws_extension) *
301 plugin->caps.count_extensions);
302 m += plugin->caps.count_extensions;
303 plugin = plugin->list;
307 vh->extensions = info->extensions;
310 vh->listen_port = info->port;
311 vh->http_proxy_port = 0;
312 vh->http_proxy_address[0] = '\0';
314 /* either use proxy from info, or try get it from env var */
316 if (info->http_proxy_address) {
317 /* override for backwards compatibility */
318 if (info->http_proxy_port)
319 vh->http_proxy_port = info->http_proxy_port;
320 lws_set_proxy(vh, info->http_proxy_address);
322 #ifdef LWS_HAVE_GETENV
323 p = getenv("http_proxy");
325 lws_set_proxy(vh, p);
329 vh->ka_time = info->ka_time;
330 vh->ka_interval = info->ka_interval;
331 vh->ka_probes = info->ka_probes;
333 if (lws_context_init_server_ssl(info, vh))
336 if (lws_context_init_client_ssl(info, vh))
339 if (lws_context_init_server(info, vh))
347 vh1 = &(*vh1)->vhost_next;
359 * lws_create_context() - Create the websocket handler
360 * @info: pointer to struct with parameters
362 * This function creates the listening socket (if serving) and takes care
363 * of all initialization in one step.
365 * After initialization, it returns a struct lws_context * that
366 * represents this server. After calling, user code needs to take care
367 * of calling lws_service() with the context pointer to get the
368 * server's sockets serviced. This must be done in the same process
369 * context as the initialization call.
371 * The protocol callback functions are called for a handful of events
372 * including http requests coming in, websocket connections becoming
373 * established, and data arriving; it's also called periodically to allow
374 * async transmission.
376 * HTTP requests are sent always to the FIRST protocol in @protocol, since
377 * at that time websocket protocol has not been negotiated. Other
378 * protocols after the first one never see any HTTP callack activity.
380 * The server created is a simple http server by default; part of the
381 * websocket standard is upgrading this http connection to a websocket one.
383 * This allows the same server to provide files like scripts and favicon /
384 * images or whatever over http and dynamic data over websockets all in
385 * one place; they're all handled in the user callback.
387 LWS_VISIBLE struct lws_context *
388 lws_create_context(struct lws_context_creation_info *info)
390 struct lws_context *context = NULL;
392 #ifndef LWS_NO_DAEMONIZE
393 int pid_daemon = get_daemonize_pid();
396 #if defined(__ANDROID__)
401 lwsl_notice("Initial logging level %d\n", log_level);
402 lwsl_notice("Libwebsockets version: %s\n", library_version);
405 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
406 lwsl_notice("IPV6 compiled in and enabled\n");
408 lwsl_notice("IPV6 compiled in but disabled\n");
410 lwsl_notice("IPV6 not compiled in\n");
412 lws_feature_status_libev(info);
413 lws_feature_status_libuv(info);
415 lwsl_info(" LWS_DEF_HEADER_LEN : %u\n", LWS_DEF_HEADER_LEN);
416 lwsl_info(" LWS_MAX_PROTOCOLS : %u\n", LWS_MAX_PROTOCOLS);
417 lwsl_info(" LWS_MAX_SMP : %u\n", LWS_MAX_SMP);
418 lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
419 lwsl_info(" sizeof (*info) : %u\n", sizeof(*info));
421 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
423 if (lws_plat_context_early_init())
426 context = lws_zalloc(sizeof(struct lws_context));
428 lwsl_err("No memory for websocket context\n");
431 #ifndef LWS_NO_DAEMONIZE
433 context->started_with_parent = pid_daemon;
434 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
437 #if defined(__ANDROID__)
438 n = getrlimit ( RLIMIT_NOFILE,&rt);
440 lwsl_err("Get RLIMIT_NOFILE failed!\n");
443 context->max_fds = rt.rlim_cur;
445 context->max_fds = getdtablesize();
448 if (info->count_threads)
449 context->count_threads = info->count_threads;
451 context->count_threads = 1;
453 if (context->count_threads > LWS_MAX_SMP)
454 context->count_threads = LWS_MAX_SMP;
456 context->token_limits = info->token_limits;
458 context->options = info->options;
460 if (info->timeout_secs)
461 context->timeout_secs = info->timeout_secs;
463 context->timeout_secs = AWAITING_TIMEOUT;
465 lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
467 if (info->max_http_header_data)
468 context->max_http_header_data = info->max_http_header_data;
470 context->max_http_header_data = LWS_DEF_HEADER_LEN;
471 if (info->max_http_header_pool)
472 context->max_http_header_pool = info->max_http_header_pool;
474 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
477 * Allocate the per-thread storage for scratchpad buffers,
478 * and header data pool
480 for (n = 0; n < context->count_threads; n++) {
481 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
482 if (!context->pt[n].serv_buf) {
487 context->pt[n].context = context;
488 context->pt[n].tid = n;
489 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
490 context->max_http_header_pool);
491 if (!context->pt[n].http_header_data)
494 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
495 context->max_http_header_pool);
496 for (m = 0; m < context->max_http_header_pool; m++)
497 context->pt[n].ah_pool[m].data =
498 (char *)context->pt[n].http_header_data +
499 (m * context->max_http_header_data);
500 if (!context->pt[n].ah_pool)
503 lws_pt_mutex_init(&context->pt[n]);
506 if (info->fd_limit_per_thread)
507 context->fd_limit_per_thread = info->fd_limit_per_thread;
509 context->fd_limit_per_thread = context->max_fds /
510 context->count_threads;
512 lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
513 context->fd_limit_per_thread);
515 memset(&wsi, 0, sizeof(wsi));
516 wsi.context = context;
518 if (!info->ka_interval && info->ka_time > 0) {
519 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
524 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
525 * enable libev mediated SIGINT handling with a default handler of
526 * lws_sigint_cb. The handler can be overridden or disabled
527 * by invoking lws_sigint_cfg after creating the context, but
528 * before invoking lws_initloop:
530 context->use_ev_sigint = 1;
531 context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
532 #endif /* LWS_USE_LIBEV */
534 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
535 * enable libev mediated SIGINT handling with a default handler of
536 * lws_sigint_cb. The handler can be overridden or disabled
537 * by invoking lws_sigint_cfg after creating the context, but
538 * before invoking lws_initloop:
540 context->use_ev_sigint = 1;
541 context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
544 lwsl_info(" mem: context: %5u bytes (%d ctx + (%d thr x %d))\n",
545 sizeof(struct lws_context) +
546 (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
547 sizeof(struct lws_context),
548 context->count_threads,
549 LWS_MAX_SOCKET_IO_BUF);
551 lwsl_info(" mem: http hdr rsvd: %5u bytes (%u thr x (%u + %u) x %u))\n",
552 (context->max_http_header_data +
553 sizeof(struct allocated_headers)) *
554 context->max_http_header_pool * context->count_threads,
555 context->count_threads,
556 context->max_http_header_data,
557 sizeof(struct allocated_headers),
558 context->max_http_header_pool);
559 n = sizeof(struct lws_pollfd) * context->count_threads *
560 context->fd_limit_per_thread;
561 context->pt[0].fds = lws_zalloc(n);
562 if (context->pt[0].fds == NULL) {
563 lwsl_err("OOM allocating %d fds\n", context->max_fds);
566 lwsl_info(" mem: pollfd map: %5u\n", n);
569 /* each thread serves his own chunk of fds */
570 for (n = 1; n < (int)info->count_threads; n++)
571 context->pt[n].fds = context->pt[n - 1].fds +
572 context->fd_limit_per_thread;
575 if (lws_plat_init(context, info))
578 lws_context_init_ssl_library(info);
581 * if he's not saying he'll make his own vhosts later then act
582 * compatibly and make a default vhost using the data in the info
584 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
585 if (!lws_create_vhost(context, info, NULL)) {
586 lwsl_err("Failed to create default vhost\n");
590 lws_context_init_extensions(info, context);
592 context->user_space = info->user;
594 lwsl_notice(" mem: per-conn: %5u bytes + protocol rx buf\n",
597 strcpy(context->canonical_hostname, "unknown");
598 lws_server_get_canonical_hostname(context, info);
600 context->uid = info->uid;
601 context->gid = info->gid;
604 * drop any root privs for this process
605 * to listen on port < 1023 we would have needed root, but now we are
606 * listening, we don't want the power for anything else
608 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
609 lws_plat_drop_app_privileges(info);
612 * give all extensions a chance to create any per-context
613 * allocations they need
615 if (info->port != CONTEXT_PORT_NO_LISTEN) {
616 if (lws_ext_cb_all_exts(context, NULL,
617 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
620 if (lws_ext_cb_all_exts(context, NULL,
621 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
627 lws_context_destroy(context);
632 * lws_context_destroy() - Destroy the websocket context
633 * @context: Websocket context
635 * This function closes any active connections and then frees the
636 * context. After calling this, any further use of the context is
640 lws_context_destroy(struct lws_context *context)
642 const struct lws_protocols *protocol = NULL;
643 struct lws_context_per_thread *pt;
644 struct lws_vhost *vh, *vh1;
648 lwsl_notice("%s\n", __func__);
653 m = context->count_threads;
654 context->being_destroyed = 1;
656 memset(&wsi, 0, sizeof(wsi));
657 wsi.context = context;
660 if (context->worst_latency_info[0])
661 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
665 pt = &context->pt[m];
667 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
668 struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
672 lws_close_free_wsi(wsi,
673 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
674 /* no protocol close */);
679 * give all extensions a chance to clean up any per-context
680 * allocations they might have made
683 n = lws_ext_cb_all_exts(context, NULL,
684 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
686 n = lws_ext_cb_all_exts(context, NULL,
687 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
690 * inform all the protocols that they are done and will have no more
693 * We can't free things until after the event loop shuts down.
695 vh = context->vhost_list;
698 protocol = vh->protocols;
701 while (n < vh->count_protocols) {
702 wsi.protocol = protocol;
703 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
713 for (n = 0; n < context->count_threads; n++) {
714 pt = &context->pt[n];
716 lws_libev_destroyloop(context, n);
717 lws_libuv_destroyloop(context, n);
719 lws_free_set_NULL(context->pt[n].serv_buf);
721 lws_free(pt->ah_pool);
722 if (pt->http_header_data)
723 lws_free(pt->http_header_data);
725 lws_plat_context_early_destroy(context);
726 lws_ssl_context_destroy(context);
728 if (context->pt[0].fds)
729 lws_free_set_NULL(context->pt[0].fds);
731 /* free all the vhost allocations */
733 vh = context->vhost_list;
735 protocol = vh->protocols;
738 while (n < vh->count_protocols) {
739 if (vh->protocol_vh_privs &&
740 vh->protocol_vh_privs[n]) {
741 lws_free(vh->protocol_vh_privs[n]);
742 vh->protocol_vh_privs[n] = NULL;
748 if (vh->protocol_vh_privs)
749 lws_free(vh->protocol_vh_privs);
750 lws_ssl_SSL_CTX_destroy(vh);
751 #ifdef LWS_WITH_PLUGINS
752 if (context->plugin_list)
753 lws_free((void *)vh->protocols);
754 #ifndef LWS_NO_EXTENSIONS
755 if (context->plugin_extension_count)
756 lws_free((void *)vh->extensions);
759 vh1 = vh->vhost_next;
764 lws_plat_context_late_destroy(context);