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[] = {
53 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
58 /* allocate the vh priv array only on demand */
59 if (!vhost->protocol_vh_privs) {
60 vhost->protocol_vh_privs = (void **)lws_zalloc(
61 vhost->count_protocols * sizeof(void *));
62 if (!vhost->protocol_vh_privs)
66 while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
69 if (n == vhost->count_protocols)
72 vhost->protocol_vh_privs[n] = lws_zalloc(size);
73 return vhost->protocol_vh_privs[n];
77 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot)
81 if (!vhost->protocol_vh_privs)
84 while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
87 if (n == vhost->count_protocols) {
88 lwsl_err("%s: unknown protocol %p\n", __func__, prot);
92 return vhost->protocol_vh_privs[n];
95 static const struct lws_protocol_vhost_options *
96 lws_vhost_protocol_options(struct lws_vhost *vh, const char *name)
98 const struct lws_protocol_vhost_options *pvo = vh->pvo;
101 // lwsl_notice("%s: '%s' '%s'\n", __func__, pvo->name, name);
102 if (!strcmp(pvo->name, name))
111 lws_protocol_init(struct lws_context *context)
113 struct lws_vhost *vh = context->vhost_list;
114 const struct lws_protocol_vhost_options *pvo, *pvo1;
118 memset(&wsi, 0, sizeof(wsi));
119 wsi.context = context;
121 lwsl_notice("%s\n", __func__);
126 /* initialize supported protocols on this vhost */
128 for (n = 0; n < vh->count_protocols; n++) {
129 wsi.protocol = &vh->protocols[n];
131 pvo = lws_vhost_protocol_options(vh,
132 vh->protocols[n].name);
135 * linked list of options specific to
142 lwsl_notice(" vh %s prot %s opt %s\n",
144 vh->protocols[n].name,
147 if (!strcmp(pvo->name, "default")) {
148 lwsl_notice("Setting default "
149 "protocol for vh %s to %s\n",
151 vh->protocols[n].name);
152 vh->default_protocol_index = n;
161 * inform all the protocols that they are doing their one-time
162 * initialization if they want to.
164 * NOTE the wsi is all zeros except for the context, vh and
165 * protocol ptrs so lws_get_context(wsi) etc can work
167 vh->protocols[n].callback(&wsi,
168 LWS_CALLBACK_PROTOCOL_INIT, NULL,
175 context->protocol_init_done = 1;
180 static int callback_http_dummy(
181 struct lws *wsi, enum lws_callback_reasons reason, void *user,
182 void *in, size_t len)
187 /* list of supported protocols and callbacks */
189 static const struct lws_protocols protocols_dummy[] = {
190 /* first protocol must always be HTTP handler */
193 "http-only", /* name */
194 callback_http_dummy, /* callback */
195 0, /* per_session_data_size */
196 0, /* max frame size / rx buffer */
199 * the other protocols are provided by lws plugins
201 { NULL, NULL, 0, 0 } /* terminator */
204 LWS_VISIBLE struct lws_vhost *
205 lws_create_vhost(struct lws_context *context,
206 struct lws_context_creation_info *info)
208 struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
209 **vh1 = &context->vhost_list;
210 const struct lws_http_mount *mounts;
211 #ifdef LWS_WITH_PLUGINS
212 struct lws_plugin *plugin = context->plugin_list;
213 struct lws_protocols *lwsp;
214 int m, n, f = !info->pvo;
221 if (!info->protocols)
222 info->protocols = &protocols_dummy[0];
224 vh->context = context;
225 if (!info->vhost_name)
226 vh->name = "default";
228 vh->name = info->vhost_name;
230 vh->iface = info->iface;
231 for (vh->count_protocols = 0;
232 info->protocols[vh->count_protocols].callback;
233 vh->count_protocols++)
236 vh->options = info->options;
238 vh->keepalive_timeout = info->keepalive_timeout;
240 #ifdef LWS_WITH_PLUGINS
243 * give the vhost a unified list of protocols including the
244 * ones that came from plugins
246 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
247 (vh->count_protocols +
248 context->plugin_protocol_count + 1));
252 m = vh->count_protocols;
253 memcpy(lwsp, info->protocols,
254 sizeof(struct lws_protocols) * m);
256 /* for compatibility, all protocols enabled on vhost if only
257 * the default vhost exists. Otherwise only vhosts who ask
258 * for a protocol get it enabled.
261 if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
265 for (n = 0; n < plugin->caps.count_protocols; n++) {
267 * for compatibility's sake, no pvo implies
268 * allow all protocols
270 if (f || lws_vhost_protocol_options(vh,
271 plugin->caps.protocols[n].name)) {
273 &plugin->caps.protocols[n],
274 sizeof(struct lws_protocols));
276 vh->count_protocols++;
279 plugin = plugin->list;
281 vh->protocols = lwsp;
284 vh->protocols = info->protocols;
286 vh->same_vh_protocol_list = (struct lws **)
287 lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
289 vh->mount_list = info->mounts;
291 #ifdef LWS_USE_UNIX_SOCK
292 if (LWS_UNIX_SOCK_ENABLED(context)) {
293 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
294 vh->name, info->iface, vh->count_protocols);
297 lwsl_notice("Creating Vhost '%s' port %d, %d protocols\n",
298 vh->name, info->port, vh->count_protocols);
300 mounts = info->mounts;
302 lwsl_notice(" mounting %s%s to %s\n",
303 mount_protocols[mounts->origin_protocol],
304 mounts->origin, mounts->mountpoint);
305 mounts = mounts->mount_next;
308 #ifndef LWS_NO_EXTENSIONS
309 #ifdef LWS_WITH_PLUGINS
310 if (context->plugin_extension_count) {
313 while (info->extensions && info->extensions[m].callback)
317 * give the vhost a unified list of extensions including the
318 * ones that came from plugins
320 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
322 context->plugin_extension_count + 1));
326 memcpy((struct lws_extension *)vh->extensions, info->extensions,
327 sizeof(struct lws_extension) * m);
328 plugin = context->plugin_list;
330 memcpy((struct lws_extension *)&vh->extensions[m],
331 plugin->caps.extensions,
332 sizeof(struct lws_extension) *
333 plugin->caps.count_extensions);
334 m += plugin->caps.count_extensions;
335 plugin = plugin->list;
339 vh->extensions = info->extensions;
342 vh->listen_port = info->port;
343 vh->http_proxy_port = 0;
344 vh->http_proxy_address[0] = '\0';
346 /* either use proxy from info, or try get it from env var */
348 if (info->http_proxy_address) {
349 /* override for backwards compatibility */
350 if (info->http_proxy_port)
351 vh->http_proxy_port = info->http_proxy_port;
352 lws_set_proxy(vh, info->http_proxy_address);
354 #ifdef LWS_HAVE_GETENV
355 p = getenv("http_proxy");
357 lws_set_proxy(vh, p);
361 vh->ka_time = info->ka_time;
362 vh->ka_interval = info->ka_interval;
363 vh->ka_probes = info->ka_probes;
365 if (vh->options & LWS_SERVER_OPTION_STS)
366 lwsl_notice(" STS enabled\n");
368 #ifdef LWS_WITH_ACCESS_LOG
369 if (info->log_filepath) {
370 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
371 if (vh->log_fd == LWS_INVALID_FILE) {
372 lwsl_err("unable to open log filepath %s\n",
377 if (context->uid != -1)
378 if (chown(info->log_filepath, context->uid,
380 lwsl_err("unable to chown log file %s\n",
384 vh->log_fd = LWS_INVALID_FILE;
387 if (lws_context_init_server_ssl(info, vh))
390 if (lws_context_init_client_ssl(info, vh))
393 if (lws_context_init_server(info, vh))
401 vh1 = &(*vh1)->vhost_next;
413 * lws_create_context() - Create the websocket handler
414 * @info: pointer to struct with parameters
416 * This function creates the listening socket (if serving) and takes care
417 * of all initialization in one step.
419 * After initialization, it returns a struct lws_context * that
420 * represents this server. After calling, user code needs to take care
421 * of calling lws_service() with the context pointer to get the
422 * server's sockets serviced. This must be done in the same process
423 * context as the initialization call.
425 * The protocol callback functions are called for a handful of events
426 * including http requests coming in, websocket connections becoming
427 * established, and data arriving; it's also called periodically to allow
428 * async transmission.
430 * HTTP requests are sent always to the FIRST protocol in @protocol, since
431 * at that time websocket protocol has not been negotiated. Other
432 * protocols after the first one never see any HTTP callack activity.
434 * The server created is a simple http server by default; part of the
435 * websocket standard is upgrading this http connection to a websocket one.
437 * This allows the same server to provide files like scripts and favicon /
438 * images or whatever over http and dynamic data over websockets all in
439 * one place; they're all handled in the user callback.
441 LWS_VISIBLE struct lws_context *
442 lws_create_context(struct lws_context_creation_info *info)
444 struct lws_context *context = NULL;
446 #ifndef LWS_NO_DAEMONIZE
447 int pid_daemon = get_daemonize_pid();
450 #if defined(__ANDROID__)
454 lwsl_notice("Initial logging level %d\n", log_level);
455 lwsl_notice("Libwebsockets version: %s\n", library_version);
458 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
459 lwsl_notice("IPV6 compiled in and enabled\n");
461 lwsl_notice("IPV6 compiled in but disabled\n");
463 lwsl_notice("IPV6 not compiled in\n");
465 lws_feature_status_libev(info);
466 lws_feature_status_libuv(info);
468 lwsl_info(" LWS_DEF_HEADER_LEN : %u\n", LWS_DEF_HEADER_LEN);
469 lwsl_info(" LWS_MAX_PROTOCOLS : %u\n", LWS_MAX_PROTOCOLS);
470 lwsl_info(" LWS_MAX_SMP : %u\n", LWS_MAX_SMP);
471 lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
472 lwsl_info(" sizeof (*info) : %u\n", sizeof(*info));
474 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
476 if (lws_plat_context_early_init())
479 context = lws_zalloc(sizeof(struct lws_context));
481 lwsl_err("No memory for websocket context\n");
485 context->time_up = time(NULL);
486 #ifndef LWS_NO_DAEMONIZE
488 context->started_with_parent = pid_daemon;
489 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
492 #if defined(__ANDROID__)
493 n = getrlimit ( RLIMIT_NOFILE,&rt);
495 lwsl_err("Get RLIMIT_NOFILE failed!\n");
498 context->max_fds = rt.rlim_cur;
500 context->max_fds = getdtablesize();
503 if (info->count_threads)
504 context->count_threads = info->count_threads;
506 context->count_threads = 1;
508 if (context->count_threads > LWS_MAX_SMP)
509 context->count_threads = LWS_MAX_SMP;
511 context->token_limits = info->token_limits;
513 context->options = info->options;
515 if (info->timeout_secs)
516 context->timeout_secs = info->timeout_secs;
518 context->timeout_secs = AWAITING_TIMEOUT;
520 lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
522 if (info->max_http_header_data)
523 context->max_http_header_data = info->max_http_header_data;
525 context->max_http_header_data = LWS_DEF_HEADER_LEN;
526 if (info->max_http_header_pool)
527 context->max_http_header_pool = info->max_http_header_pool;
529 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
532 * Allocate the per-thread storage for scratchpad buffers,
533 * and header data pool
535 for (n = 0; n < context->count_threads; n++) {
536 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
537 if (!context->pt[n].serv_buf) {
542 context->pt[n].context = context;
543 context->pt[n].tid = n;
544 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
545 context->max_http_header_pool);
546 if (!context->pt[n].http_header_data)
549 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
550 context->max_http_header_pool);
551 for (m = 0; m < context->max_http_header_pool; m++)
552 context->pt[n].ah_pool[m].data =
553 (char *)context->pt[n].http_header_data +
554 (m * context->max_http_header_data);
555 if (!context->pt[n].ah_pool)
558 lws_pt_mutex_init(&context->pt[n]);
561 if (info->fd_limit_per_thread)
562 context->fd_limit_per_thread = info->fd_limit_per_thread;
564 context->fd_limit_per_thread = context->max_fds /
565 context->count_threads;
567 lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
568 context->fd_limit_per_thread);
570 memset(&wsi, 0, sizeof(wsi));
571 wsi.context = context;
573 if (!info->ka_interval && info->ka_time > 0) {
574 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
579 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
580 * enable libev mediated SIGINT handling with a default handler of
581 * lws_sigint_cb. The handler can be overridden or disabled
582 * by invoking lws_sigint_cfg after creating the context, but
583 * before invoking lws_initloop:
585 context->use_ev_sigint = 1;
586 context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
587 #endif /* LWS_USE_LIBEV */
589 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
590 * enable libev mediated SIGINT handling with a default handler of
591 * lws_sigint_cb. The handler can be overridden or disabled
592 * by invoking lws_sigint_cfg after creating the context, but
593 * before invoking lws_initloop:
595 context->use_ev_sigint = 1;
596 context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
599 lwsl_info(" mem: context: %5u bytes (%d ctx + (%d thr x %d))\n",
600 sizeof(struct lws_context) +
601 (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
602 sizeof(struct lws_context),
603 context->count_threads,
604 LWS_MAX_SOCKET_IO_BUF);
606 lwsl_info(" mem: http hdr rsvd: %5u bytes (%u thr x (%u + %u) x %u))\n",
607 (context->max_http_header_data +
608 sizeof(struct allocated_headers)) *
609 context->max_http_header_pool * context->count_threads,
610 context->count_threads,
611 context->max_http_header_data,
612 sizeof(struct allocated_headers),
613 context->max_http_header_pool);
614 n = sizeof(struct lws_pollfd) * context->count_threads *
615 context->fd_limit_per_thread;
616 context->pt[0].fds = lws_zalloc(n);
617 if (context->pt[0].fds == NULL) {
618 lwsl_err("OOM allocating %d fds\n", context->max_fds);
621 lwsl_info(" mem: pollfd map: %5u\n", n);
623 if (info->server_string) {
624 context->server_string = info->server_string;
625 context->server_string_len = (short)
626 strlen(context->server_string);
628 context->server_string = "libwebsockets";
629 context->server_string_len = 13;
633 /* each thread serves his own chunk of fds */
634 for (n = 1; n < (int)info->count_threads; n++)
635 context->pt[n].fds = context->pt[n - 1].fds +
636 context->fd_limit_per_thread;
639 if (lws_plat_init(context, info))
642 lws_context_init_ssl_library(info);
644 context->user_space = info->user;
647 * if he's not saying he'll make his own vhosts later then act
648 * compatibly and make a default vhost using the data in the info
650 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
651 if (!lws_create_vhost(context, info)) {
652 lwsl_err("Failed to create default vhost\n");
656 lws_context_init_extensions(info, context);
658 lwsl_notice(" mem: per-conn: %5u bytes + protocol rx buf\n",
661 strcpy(context->canonical_hostname, "unknown");
662 lws_server_get_canonical_hostname(context, info);
664 context->uid = info->uid;
665 context->gid = info->gid;
668 * drop any root privs for this process
669 * to listen on port < 1023 we would have needed root, but now we are
670 * listening, we don't want the power for anything else
672 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
673 lws_plat_drop_app_privileges(info);
676 * give all extensions a chance to create any per-context
677 * allocations they need
679 if (info->port != CONTEXT_PORT_NO_LISTEN) {
680 if (lws_ext_cb_all_exts(context, NULL,
681 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
684 if (lws_ext_cb_all_exts(context, NULL,
685 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
691 lws_context_destroy(context);
696 * lws_context_destroy() - Destroy the websocket context
697 * @context: Websocket context
699 * This function closes any active connections and then frees the
700 * context. After calling this, any further use of the context is
704 lws_context_destroy(struct lws_context *context)
706 const struct lws_protocols *protocol = NULL;
707 struct lws_context_per_thread *pt;
708 struct lws_vhost *vh = NULL, *vh1;
712 lwsl_notice("%s\n", __func__);
717 m = context->count_threads;
718 context->being_destroyed = 1;
720 memset(&wsi, 0, sizeof(wsi));
721 wsi.context = context;
724 if (context->worst_latency_info[0])
725 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
729 pt = &context->pt[m];
731 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
732 struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
736 lws_close_free_wsi(wsi,
737 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
738 /* no protocol close */);
743 * give all extensions a chance to clean up any per-context
744 * allocations they might have made
747 n = lws_ext_cb_all_exts(context, NULL,
748 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
750 n = lws_ext_cb_all_exts(context, NULL,
751 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
754 * inform all the protocols that they are done and will have no more
757 * We can't free things until after the event loop shuts down.
759 if (context->protocol_init_done)
760 vh = context->vhost_list;
763 protocol = vh->protocols;
766 while (n < vh->count_protocols) {
767 wsi.protocol = protocol;
768 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
778 for (n = 0; n < context->count_threads; n++) {
779 pt = &context->pt[n];
781 lws_libev_destroyloop(context, n);
782 lws_libuv_destroyloop(context, n);
784 lws_free_set_NULL(context->pt[n].serv_buf);
786 lws_free(pt->ah_pool);
787 if (pt->http_header_data)
788 lws_free(pt->http_header_data);
790 lws_plat_context_early_destroy(context);
791 lws_ssl_context_destroy(context);
793 if (context->pt[0].fds)
794 lws_free_set_NULL(context->pt[0].fds);
796 /* free all the vhost allocations */
798 vh = context->vhost_list;
800 protocol = vh->protocols;
803 while (n < vh->count_protocols) {
804 if (vh->protocol_vh_privs &&
805 vh->protocol_vh_privs[n]) {
806 lws_free(vh->protocol_vh_privs[n]);
807 vh->protocol_vh_privs[n] = NULL;
813 if (vh->protocol_vh_privs)
814 lws_free(vh->protocol_vh_privs);
815 lws_ssl_SSL_CTX_destroy(vh);
816 lws_free(vh->same_vh_protocol_list);
817 #ifdef LWS_WITH_PLUGINS
818 if (context->plugin_list)
819 lws_free((void *)vh->protocols);
820 #ifndef LWS_NO_EXTENSIONS
821 if (context->plugin_extension_count)
822 lws_free((void *)vh->extensions);
825 #ifdef LWS_WITH_ACCESS_LOG
826 if (vh->log_fd != LWS_INVALID_FILE)
830 vh1 = vh->vhost_next;
835 lws_plat_context_late_destroy(context);