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;
118 memset(&wsi, 0, sizeof(wsi));
119 wsi.context = context;
124 /* initialize supported protocols on this vhost */
126 for (n = 0; n < vh->count_protocols; n++) {
127 wsi.protocol = &vh->protocols[n];
129 pvo = lws_vhost_protocol_options(vh,
130 vh->protocols[n].name);
133 * linked list of options specific to
139 * inform all the protocols that they are doing their one-time
140 * initialization if they want to.
142 * NOTE the wsi is all zeros except for the context, vh and
143 * protocol ptrs so lws_get_context(wsi) etc can work
145 vh->protocols[n].callback(&wsi,
146 LWS_CALLBACK_PROTOCOL_INIT, NULL,
153 context->protocol_init_done = 1;
158 static int callback_http_dummy(
159 struct lws *wsi, enum lws_callback_reasons reason, void *user,
160 void *in, size_t len)
165 /* list of supported protocols and callbacks */
167 static const struct lws_protocols protocols_dummy[] = {
168 /* first protocol must always be HTTP handler */
171 "http-only", /* name */
172 callback_http_dummy, /* callback */
173 0, /* per_session_data_size */
174 0, /* max frame size / rx buffer */
177 * the other protocols are provided by lws plugins
179 { NULL, NULL, 0, 0 } /* terminator */
182 LWS_VISIBLE struct lws_vhost *
183 lws_create_vhost(struct lws_context *context,
184 struct lws_context_creation_info *info)
186 struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
187 **vh1 = &context->vhost_list;
188 const struct lws_http_mount *mounts;
189 #ifdef LWS_WITH_PLUGINS
190 struct lws_plugin *plugin = context->plugin_list;
191 struct lws_protocols *lwsp;
192 int m, n, f = !info->pvo;
199 if (!info->protocols)
200 info->protocols = &protocols_dummy[0];
202 vh->context = context;
203 if (!info->vhost_name)
204 vh->name = "default";
206 vh->name = info->vhost_name;
208 vh->iface = info->iface;
209 for (vh->count_protocols = 0;
210 info->protocols[vh->count_protocols].callback;
211 vh->count_protocols++)
214 vh->options = info->options;
216 vh->keepalive_timeout = info->keepalive_timeout;
218 #ifdef LWS_WITH_PLUGINS
221 * give the vhost a unified list of protocols including the
222 * ones that came from plugins
224 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
225 (vh->count_protocols +
226 context->plugin_protocol_count + 1));
230 m = vh->count_protocols;
231 memcpy(lwsp, info->protocols,
232 sizeof(struct lws_protocols) * m);
234 /* for compatibility, all protocols enabled on vhost if only
235 * the default vhost exists. Otherwise only vhosts who ask
236 * for a protocol get it enabled.
239 if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
243 for (n = 0; n < plugin->caps.count_protocols; n++) {
245 * for compatibility's sake, no pvo implies
246 * allow all protocols
248 if (f || lws_vhost_protocol_options(vh,
249 plugin->caps.protocols[n].name)) {
251 &plugin->caps.protocols[n],
252 sizeof(struct lws_protocols));
254 vh->count_protocols++;
257 plugin = plugin->list;
259 vh->protocols = lwsp;
262 vh->protocols = info->protocols;
264 vh->same_vh_protocol_list = (struct lws **)
265 lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
267 vh->mount_list = info->mounts;
269 #ifdef LWS_USE_UNIX_SOCK
270 if (LWS_UNIX_SOCK_ENABLED(context)) {
271 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
272 vh->name, info->iface, vh->count_protocols);
275 lwsl_notice("Creating Vhost '%s' port %d, %d protocols\n",
276 vh->name, info->port, vh->count_protocols);
278 mounts = info->mounts;
280 lwsl_notice(" mounting %s%s to %s\n",
281 mount_protocols[mounts->origin_protocol],
282 mounts->origin, mounts->mountpoint);
283 mounts = mounts->mount_next;
286 #ifndef LWS_NO_EXTENSIONS
287 #ifdef LWS_WITH_PLUGINS
288 if (context->plugin_extension_count) {
291 while (info->extensions && info->extensions[m].callback)
295 * give the vhost a unified list of extensions including the
296 * ones that came from plugins
298 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
300 context->plugin_extension_count + 1));
304 memcpy((struct lws_extension *)vh->extensions, info->extensions,
305 sizeof(struct lws_extension) * m);
306 plugin = context->plugin_list;
308 memcpy((struct lws_extension *)&vh->extensions[m],
309 plugin->caps.extensions,
310 sizeof(struct lws_extension) *
311 plugin->caps.count_extensions);
312 m += plugin->caps.count_extensions;
313 plugin = plugin->list;
317 vh->extensions = info->extensions;
320 vh->listen_port = info->port;
321 vh->http_proxy_port = 0;
322 vh->http_proxy_address[0] = '\0';
324 /* either use proxy from info, or try get it from env var */
326 if (info->http_proxy_address) {
327 /* override for backwards compatibility */
328 if (info->http_proxy_port)
329 vh->http_proxy_port = info->http_proxy_port;
330 lws_set_proxy(vh, info->http_proxy_address);
332 #ifdef LWS_HAVE_GETENV
333 p = getenv("http_proxy");
335 lws_set_proxy(vh, p);
339 vh->ka_time = info->ka_time;
340 vh->ka_interval = info->ka_interval;
341 vh->ka_probes = info->ka_probes;
343 if (vh->options & LWS_SERVER_OPTION_STS)
344 lwsl_notice(" STS enabled\n");
346 #ifdef LWS_WITH_ACCESS_LOG
347 if (info->log_filepath) {
348 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
349 if (vh->log_fd == LWS_INVALID_FILE) {
350 lwsl_err("unable to open log filepath %s\n",
354 if (context->uid != -1)
355 if (chown(info->log_filepath, context->uid,
357 lwsl_err("unable to chown log file %s\n",
360 vh->log_fd = LWS_INVALID_FILE;
363 if (lws_context_init_server_ssl(info, vh))
366 if (lws_context_init_client_ssl(info, vh))
369 if (lws_context_init_server(info, vh))
377 vh1 = &(*vh1)->vhost_next;
389 * lws_create_context() - Create the websocket handler
390 * @info: pointer to struct with parameters
392 * This function creates the listening socket (if serving) and takes care
393 * of all initialization in one step.
395 * After initialization, it returns a struct lws_context * that
396 * represents this server. After calling, user code needs to take care
397 * of calling lws_service() with the context pointer to get the
398 * server's sockets serviced. This must be done in the same process
399 * context as the initialization call.
401 * The protocol callback functions are called for a handful of events
402 * including http requests coming in, websocket connections becoming
403 * established, and data arriving; it's also called periodically to allow
404 * async transmission.
406 * HTTP requests are sent always to the FIRST protocol in @protocol, since
407 * at that time websocket protocol has not been negotiated. Other
408 * protocols after the first one never see any HTTP callack activity.
410 * The server created is a simple http server by default; part of the
411 * websocket standard is upgrading this http connection to a websocket one.
413 * This allows the same server to provide files like scripts and favicon /
414 * images or whatever over http and dynamic data over websockets all in
415 * one place; they're all handled in the user callback.
417 LWS_VISIBLE struct lws_context *
418 lws_create_context(struct lws_context_creation_info *info)
420 struct lws_context *context = NULL;
422 #ifndef LWS_NO_DAEMONIZE
423 int pid_daemon = get_daemonize_pid();
426 #if defined(__ANDROID__)
430 lwsl_notice("Initial logging level %d\n", log_level);
431 lwsl_notice("Libwebsockets version: %s\n", library_version);
434 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
435 lwsl_notice("IPV6 compiled in and enabled\n");
437 lwsl_notice("IPV6 compiled in but disabled\n");
439 lwsl_notice("IPV6 not compiled in\n");
441 lws_feature_status_libev(info);
442 lws_feature_status_libuv(info);
444 lwsl_info(" LWS_DEF_HEADER_LEN : %u\n", LWS_DEF_HEADER_LEN);
445 lwsl_info(" LWS_MAX_PROTOCOLS : %u\n", LWS_MAX_PROTOCOLS);
446 lwsl_info(" LWS_MAX_SMP : %u\n", LWS_MAX_SMP);
447 lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
448 lwsl_info(" sizeof (*info) : %u\n", sizeof(*info));
450 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
452 if (lws_plat_context_early_init())
455 context = lws_zalloc(sizeof(struct lws_context));
457 lwsl_err("No memory for websocket context\n");
461 context->time_up = time(NULL);
462 #ifndef LWS_NO_DAEMONIZE
464 context->started_with_parent = pid_daemon;
465 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
468 #if defined(__ANDROID__)
469 n = getrlimit ( RLIMIT_NOFILE,&rt);
471 lwsl_err("Get RLIMIT_NOFILE failed!\n");
474 context->max_fds = rt.rlim_cur;
476 context->max_fds = getdtablesize();
479 if (info->count_threads)
480 context->count_threads = info->count_threads;
482 context->count_threads = 1;
484 if (context->count_threads > LWS_MAX_SMP)
485 context->count_threads = LWS_MAX_SMP;
487 context->token_limits = info->token_limits;
489 context->options = info->options;
491 if (info->timeout_secs)
492 context->timeout_secs = info->timeout_secs;
494 context->timeout_secs = AWAITING_TIMEOUT;
496 lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
498 if (info->max_http_header_data)
499 context->max_http_header_data = info->max_http_header_data;
501 context->max_http_header_data = LWS_DEF_HEADER_LEN;
502 if (info->max_http_header_pool)
503 context->max_http_header_pool = info->max_http_header_pool;
505 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
508 * Allocate the per-thread storage for scratchpad buffers,
509 * and header data pool
511 for (n = 0; n < context->count_threads; n++) {
512 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
513 if (!context->pt[n].serv_buf) {
518 context->pt[n].context = context;
519 context->pt[n].tid = n;
520 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
521 context->max_http_header_pool);
522 if (!context->pt[n].http_header_data)
525 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
526 context->max_http_header_pool);
527 for (m = 0; m < context->max_http_header_pool; m++)
528 context->pt[n].ah_pool[m].data =
529 (char *)context->pt[n].http_header_data +
530 (m * context->max_http_header_data);
531 if (!context->pt[n].ah_pool)
534 lws_pt_mutex_init(&context->pt[n]);
537 if (info->fd_limit_per_thread)
538 context->fd_limit_per_thread = info->fd_limit_per_thread;
540 context->fd_limit_per_thread = context->max_fds /
541 context->count_threads;
543 lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
544 context->fd_limit_per_thread);
546 memset(&wsi, 0, sizeof(wsi));
547 wsi.context = context;
549 if (!info->ka_interval && info->ka_time > 0) {
550 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
555 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
556 * enable libev mediated SIGINT handling with a default handler of
557 * lws_sigint_cb. The handler can be overridden or disabled
558 * by invoking lws_sigint_cfg after creating the context, but
559 * before invoking lws_initloop:
561 context->use_ev_sigint = 1;
562 context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
563 #endif /* LWS_USE_LIBEV */
565 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
566 * enable libev mediated SIGINT handling with a default handler of
567 * lws_sigint_cb. The handler can be overridden or disabled
568 * by invoking lws_sigint_cfg after creating the context, but
569 * before invoking lws_initloop:
571 context->use_ev_sigint = 1;
572 context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
575 lwsl_info(" mem: context: %5u bytes (%d ctx + (%d thr x %d))\n",
576 sizeof(struct lws_context) +
577 (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
578 sizeof(struct lws_context),
579 context->count_threads,
580 LWS_MAX_SOCKET_IO_BUF);
582 lwsl_info(" mem: http hdr rsvd: %5u bytes (%u thr x (%u + %u) x %u))\n",
583 (context->max_http_header_data +
584 sizeof(struct allocated_headers)) *
585 context->max_http_header_pool * context->count_threads,
586 context->count_threads,
587 context->max_http_header_data,
588 sizeof(struct allocated_headers),
589 context->max_http_header_pool);
590 n = sizeof(struct lws_pollfd) * context->count_threads *
591 context->fd_limit_per_thread;
592 context->pt[0].fds = lws_zalloc(n);
593 if (context->pt[0].fds == NULL) {
594 lwsl_err("OOM allocating %d fds\n", context->max_fds);
597 lwsl_info(" mem: pollfd map: %5u\n", n);
599 if (info->server_string) {
600 context->server_string = info->server_string;
601 context->server_string_len = strlen(context->server_string);
603 context->server_string = "libwebsockets";
604 context->server_string_len = 13;
608 /* each thread serves his own chunk of fds */
609 for (n = 1; n < (int)info->count_threads; n++)
610 context->pt[n].fds = context->pt[n - 1].fds +
611 context->fd_limit_per_thread;
614 if (lws_plat_init(context, info))
617 lws_context_init_ssl_library(info);
619 context->user_space = info->user;
622 * if he's not saying he'll make his own vhosts later then act
623 * compatibly and make a default vhost using the data in the info
625 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
626 if (!lws_create_vhost(context, info)) {
627 lwsl_err("Failed to create default vhost\n");
631 lws_context_init_extensions(info, context);
633 lwsl_notice(" mem: per-conn: %5u bytes + protocol rx buf\n",
636 strcpy(context->canonical_hostname, "unknown");
637 lws_server_get_canonical_hostname(context, info);
639 context->uid = info->uid;
640 context->gid = info->gid;
643 * drop any root privs for this process
644 * to listen on port < 1023 we would have needed root, but now we are
645 * listening, we don't want the power for anything else
647 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
648 lws_plat_drop_app_privileges(info);
651 * give all extensions a chance to create any per-context
652 * allocations they need
654 if (info->port != CONTEXT_PORT_NO_LISTEN) {
655 if (lws_ext_cb_all_exts(context, NULL,
656 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
659 if (lws_ext_cb_all_exts(context, NULL,
660 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
666 lws_context_destroy(context);
671 * lws_context_destroy() - Destroy the websocket context
672 * @context: Websocket context
674 * This function closes any active connections and then frees the
675 * context. After calling this, any further use of the context is
679 lws_context_destroy(struct lws_context *context)
681 const struct lws_protocols *protocol = NULL;
682 struct lws_context_per_thread *pt;
683 struct lws_vhost *vh, *vh1;
687 lwsl_notice("%s\n", __func__);
692 m = context->count_threads;
693 context->being_destroyed = 1;
695 memset(&wsi, 0, sizeof(wsi));
696 wsi.context = context;
699 if (context->worst_latency_info[0])
700 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
704 pt = &context->pt[m];
706 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
707 struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
711 lws_close_free_wsi(wsi,
712 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
713 /* no protocol close */);
718 * give all extensions a chance to clean up any per-context
719 * allocations they might have made
722 n = lws_ext_cb_all_exts(context, NULL,
723 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
725 n = lws_ext_cb_all_exts(context, NULL,
726 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
729 * inform all the protocols that they are done and will have no more
732 * We can't free things until after the event loop shuts down.
734 vh = context->vhost_list;
737 protocol = vh->protocols;
740 while (n < vh->count_protocols) {
741 wsi.protocol = protocol;
742 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
752 for (n = 0; n < context->count_threads; n++) {
753 pt = &context->pt[n];
755 lws_libev_destroyloop(context, n);
756 lws_libuv_destroyloop(context, n);
758 lws_free_set_NULL(context->pt[n].serv_buf);
760 lws_free(pt->ah_pool);
761 if (pt->http_header_data)
762 lws_free(pt->http_header_data);
764 lws_plat_context_early_destroy(context);
765 lws_ssl_context_destroy(context);
767 if (context->pt[0].fds)
768 lws_free_set_NULL(context->pt[0].fds);
770 /* free all the vhost allocations */
772 vh = context->vhost_list;
774 protocol = vh->protocols;
777 while (n < vh->count_protocols) {
778 if (vh->protocol_vh_privs &&
779 vh->protocol_vh_privs[n]) {
780 lws_free(vh->protocol_vh_privs[n]);
781 vh->protocol_vh_privs[n] = NULL;
787 if (vh->protocol_vh_privs)
788 lws_free(vh->protocol_vh_privs);
789 lws_ssl_SSL_CTX_destroy(vh);
790 lws_free(vh->same_vh_protocol_list);
791 #ifdef LWS_WITH_PLUGINS
792 if (context->plugin_list)
793 lws_free((void *)vh->protocols);
794 #ifndef LWS_NO_EXTENSIONS
795 if (context->plugin_extension_count)
796 lws_free((void *)vh->extensions);
799 #ifdef LWS_WITH_ACCESS_LOG
800 if (vh->log_fd != LWS_INVALID_FILE)
804 vh1 = vh->vhost_next;
809 lws_plat_context_late_destroy(context);