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[] = {
54 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
59 /* allocate the vh priv array only on demand */
60 if (!vhost->protocol_vh_privs) {
61 vhost->protocol_vh_privs = (void **)lws_zalloc(
62 vhost->count_protocols * sizeof(void *));
63 if (!vhost->protocol_vh_privs)
67 while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
70 if (n == vhost->count_protocols)
73 vhost->protocol_vh_privs[n] = lws_zalloc(size);
74 return vhost->protocol_vh_privs[n];
78 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot)
82 if (!vhost->protocol_vh_privs)
85 while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
88 if (n == vhost->count_protocols) {
89 lwsl_err("%s: unknown protocol %p\n", __func__, prot);
93 return vhost->protocol_vh_privs[n];
96 static const struct lws_protocol_vhost_options *
97 lws_vhost_protocol_options(struct lws_vhost *vh, const char *name)
99 const struct lws_protocol_vhost_options *pvo = vh->pvo;
102 // lwsl_notice("%s: '%s' '%s'\n", __func__, pvo->name, name);
103 if (!strcmp(pvo->name, name))
112 lws_protocol_init(struct lws_context *context)
114 struct lws_vhost *vh = context->vhost_list;
115 const struct lws_protocol_vhost_options *pvo, *pvo1;
119 memset(&wsi, 0, sizeof(wsi));
120 wsi.context = context;
122 lwsl_notice("%s\n", __func__);
127 /* initialize supported protocols on this vhost */
129 for (n = 0; n < vh->count_protocols; n++) {
130 wsi.protocol = &vh->protocols[n];
132 pvo = lws_vhost_protocol_options(vh,
133 vh->protocols[n].name);
136 * linked list of options specific to
143 lwsl_notice(" vh %s prot %s opt %s\n",
145 vh->protocols[n].name,
148 if (!strcmp(pvo->name, "default")) {
149 lwsl_notice("Setting default "
150 "protocol for vh %s to %s\n",
152 vh->protocols[n].name);
153 vh->default_protocol_index = n;
162 * inform all the protocols that they are doing their one-time
163 * initialization if they want to.
165 * NOTE the wsi is all zeros except for the context, vh and
166 * protocol ptrs so lws_get_context(wsi) etc can work
168 vh->protocols[n].callback(&wsi,
169 LWS_CALLBACK_PROTOCOL_INIT, NULL,
176 context->protocol_init_done = 1;
181 static int callback_http_dummy(
182 struct lws *wsi, enum lws_callback_reasons reason, void *user,
183 void *in, size_t len)
188 /* list of supported protocols and callbacks */
190 static const struct lws_protocols protocols_dummy[] = {
191 /* first protocol must always be HTTP handler */
194 "http-only", /* name */
195 callback_http_dummy, /* callback */
196 0, /* per_session_data_size */
197 0, /* max frame size / rx buffer */
200 * the other protocols are provided by lws plugins
202 { NULL, NULL, 0, 0 } /* terminator */
205 LWS_VISIBLE struct lws_vhost *
206 lws_create_vhost(struct lws_context *context,
207 struct lws_context_creation_info *info)
209 struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
210 **vh1 = &context->vhost_list;
211 const struct lws_http_mount *mounts;
212 #ifdef LWS_WITH_PLUGINS
213 struct lws_plugin *plugin = context->plugin_list;
214 struct lws_protocols *lwsp;
215 int m, n, f = !info->pvo;
222 if (!info->protocols)
223 info->protocols = &protocols_dummy[0];
225 vh->context = context;
226 if (!info->vhost_name)
227 vh->name = "default";
229 vh->name = info->vhost_name;
231 vh->iface = info->iface;
232 for (vh->count_protocols = 0;
233 info->protocols[vh->count_protocols].callback;
234 vh->count_protocols++)
237 vh->options = info->options;
239 vh->keepalive_timeout = info->keepalive_timeout;
241 #ifdef LWS_WITH_PLUGINS
244 * give the vhost a unified list of protocols including the
245 * ones that came from plugins
247 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
248 (vh->count_protocols +
249 context->plugin_protocol_count + 1));
253 m = vh->count_protocols;
254 memcpy(lwsp, info->protocols,
255 sizeof(struct lws_protocols) * m);
257 /* for compatibility, all protocols enabled on vhost if only
258 * the default vhost exists. Otherwise only vhosts who ask
259 * for a protocol get it enabled.
262 if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
266 for (n = 0; n < plugin->caps.count_protocols; n++) {
268 * for compatibility's sake, no pvo implies
269 * allow all protocols
271 if (f || lws_vhost_protocol_options(vh,
272 plugin->caps.protocols[n].name)) {
274 &plugin->caps.protocols[n],
275 sizeof(struct lws_protocols));
277 vh->count_protocols++;
280 plugin = plugin->list;
282 vh->protocols = lwsp;
285 vh->protocols = info->protocols;
287 vh->same_vh_protocol_list = (struct lws **)
288 lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
290 vh->mount_list = info->mounts;
292 #ifdef LWS_USE_UNIX_SOCK
293 if (LWS_UNIX_SOCK_ENABLED(context)) {
294 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
295 vh->name, info->iface, vh->count_protocols);
298 lwsl_notice("Creating Vhost '%s' port %d, %d protocols\n",
299 vh->name, info->port, vh->count_protocols);
301 mounts = info->mounts;
303 lwsl_notice(" mounting %s%s to %s\n",
304 mount_protocols[mounts->origin_protocol],
305 mounts->origin, mounts->mountpoint);
306 mounts = mounts->mount_next;
309 #ifndef LWS_NO_EXTENSIONS
310 #ifdef LWS_WITH_PLUGINS
311 if (context->plugin_extension_count) {
314 while (info->extensions && info->extensions[m].callback)
318 * give the vhost a unified list of extensions including the
319 * ones that came from plugins
321 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
323 context->plugin_extension_count + 1));
327 memcpy((struct lws_extension *)vh->extensions, info->extensions,
328 sizeof(struct lws_extension) * m);
329 plugin = context->plugin_list;
331 memcpy((struct lws_extension *)&vh->extensions[m],
332 plugin->caps.extensions,
333 sizeof(struct lws_extension) *
334 plugin->caps.count_extensions);
335 m += plugin->caps.count_extensions;
336 plugin = plugin->list;
340 vh->extensions = info->extensions;
343 vh->listen_port = info->port;
344 vh->http_proxy_port = 0;
345 vh->http_proxy_address[0] = '\0';
347 /* either use proxy from info, or try get it from env var */
349 if (info->http_proxy_address) {
350 /* override for backwards compatibility */
351 if (info->http_proxy_port)
352 vh->http_proxy_port = info->http_proxy_port;
353 lws_set_proxy(vh, info->http_proxy_address);
355 #ifdef LWS_HAVE_GETENV
356 p = getenv("http_proxy");
358 lws_set_proxy(vh, p);
362 vh->ka_time = info->ka_time;
363 vh->ka_interval = info->ka_interval;
364 vh->ka_probes = info->ka_probes;
366 if (vh->options & LWS_SERVER_OPTION_STS)
367 lwsl_notice(" STS enabled\n");
369 #ifdef LWS_WITH_ACCESS_LOG
370 if (info->log_filepath) {
371 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
372 if (vh->log_fd == LWS_INVALID_FILE) {
373 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",
383 vh->log_fd = LWS_INVALID_FILE;
386 if (lws_context_init_server_ssl(info, vh))
389 if (lws_context_init_client_ssl(info, vh))
392 if (lws_context_init_server(info, vh))
400 vh1 = &(*vh1)->vhost_next;
412 * lws_create_context() - Create the websocket handler
413 * @info: pointer to struct with parameters
415 * This function creates the listening socket (if serving) and takes care
416 * of all initialization in one step.
418 * After initialization, it returns a struct lws_context * that
419 * represents this server. After calling, user code needs to take care
420 * of calling lws_service() with the context pointer to get the
421 * server's sockets serviced. This must be done in the same process
422 * context as the initialization call.
424 * The protocol callback functions are called for a handful of events
425 * including http requests coming in, websocket connections becoming
426 * established, and data arriving; it's also called periodically to allow
427 * async transmission.
429 * HTTP requests are sent always to the FIRST protocol in @protocol, since
430 * at that time websocket protocol has not been negotiated. Other
431 * protocols after the first one never see any HTTP callack activity.
433 * The server created is a simple http server by default; part of the
434 * websocket standard is upgrading this http connection to a websocket one.
436 * This allows the same server to provide files like scripts and favicon /
437 * images or whatever over http and dynamic data over websockets all in
438 * one place; they're all handled in the user callback.
440 LWS_VISIBLE struct lws_context *
441 lws_create_context(struct lws_context_creation_info *info)
443 struct lws_context *context = NULL;
445 #ifndef LWS_NO_DAEMONIZE
446 int pid_daemon = get_daemonize_pid();
449 #if defined(__ANDROID__)
453 lwsl_notice("Initial logging level %d\n", log_level);
454 lwsl_notice("Libwebsockets version: %s\n", library_version);
457 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
458 lwsl_notice("IPV6 compiled in and enabled\n");
460 lwsl_notice("IPV6 compiled in but disabled\n");
462 lwsl_notice("IPV6 not compiled in\n");
464 lws_feature_status_libev(info);
465 lws_feature_status_libuv(info);
467 lwsl_info(" LWS_DEF_HEADER_LEN : %u\n", LWS_DEF_HEADER_LEN);
468 lwsl_info(" LWS_MAX_PROTOCOLS : %u\n", LWS_MAX_PROTOCOLS);
469 lwsl_info(" LWS_MAX_SMP : %u\n", LWS_MAX_SMP);
470 lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
471 lwsl_info(" sizeof (*info) : %u\n", sizeof(*info));
473 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
475 if (lws_plat_context_early_init())
478 context = lws_zalloc(sizeof(struct lws_context));
480 lwsl_err("No memory for websocket context\n");
484 context->time_up = time(NULL);
485 #ifndef LWS_NO_DAEMONIZE
487 context->started_with_parent = pid_daemon;
488 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
491 #if defined(__ANDROID__)
492 n = getrlimit ( RLIMIT_NOFILE,&rt);
494 lwsl_err("Get RLIMIT_NOFILE failed!\n");
497 context->max_fds = rt.rlim_cur;
499 context->max_fds = getdtablesize();
502 if (info->count_threads)
503 context->count_threads = info->count_threads;
505 context->count_threads = 1;
507 if (context->count_threads > LWS_MAX_SMP)
508 context->count_threads = LWS_MAX_SMP;
510 context->token_limits = info->token_limits;
512 context->options = info->options;
514 if (info->timeout_secs)
515 context->timeout_secs = info->timeout_secs;
517 context->timeout_secs = AWAITING_TIMEOUT;
519 lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
521 if (info->max_http_header_data)
522 context->max_http_header_data = info->max_http_header_data;
524 context->max_http_header_data = LWS_DEF_HEADER_LEN;
525 if (info->max_http_header_pool)
526 context->max_http_header_pool = info->max_http_header_pool;
528 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
531 * Allocate the per-thread storage for scratchpad buffers,
532 * and header data pool
534 for (n = 0; n < context->count_threads; n++) {
535 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
536 if (!context->pt[n].serv_buf) {
541 context->pt[n].context = context;
542 context->pt[n].tid = n;
543 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
544 context->max_http_header_pool);
545 if (!context->pt[n].http_header_data)
548 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
549 context->max_http_header_pool);
550 for (m = 0; m < context->max_http_header_pool; m++)
551 context->pt[n].ah_pool[m].data =
552 (char *)context->pt[n].http_header_data +
553 (m * context->max_http_header_data);
554 if (!context->pt[n].ah_pool)
557 lws_pt_mutex_init(&context->pt[n]);
560 if (info->fd_limit_per_thread)
561 context->fd_limit_per_thread = info->fd_limit_per_thread;
563 context->fd_limit_per_thread = context->max_fds /
564 context->count_threads;
566 lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
567 context->fd_limit_per_thread);
569 memset(&wsi, 0, sizeof(wsi));
570 wsi.context = context;
572 if (!info->ka_interval && info->ka_time > 0) {
573 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
578 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
579 * enable libev mediated SIGINT handling with a default handler of
580 * lws_sigint_cb. The handler can be overridden or disabled
581 * by invoking lws_sigint_cfg after creating the context, but
582 * before invoking lws_initloop:
584 context->use_ev_sigint = 1;
585 context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
586 #endif /* LWS_USE_LIBEV */
588 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
589 * enable libev mediated SIGINT handling with a default handler of
590 * lws_sigint_cb. The handler can be overridden or disabled
591 * by invoking lws_sigint_cfg after creating the context, but
592 * before invoking lws_initloop:
594 context->use_ev_sigint = 1;
595 context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
598 lwsl_info(" mem: context: %5u bytes (%d ctx + (%d thr x %d))\n",
599 sizeof(struct lws_context) +
600 (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
601 sizeof(struct lws_context),
602 context->count_threads,
603 LWS_MAX_SOCKET_IO_BUF);
605 lwsl_info(" mem: http hdr rsvd: %5u bytes (%u thr x (%u + %u) x %u))\n",
606 (context->max_http_header_data +
607 sizeof(struct allocated_headers)) *
608 context->max_http_header_pool * context->count_threads,
609 context->count_threads,
610 context->max_http_header_data,
611 sizeof(struct allocated_headers),
612 context->max_http_header_pool);
613 n = sizeof(struct lws_pollfd) * context->count_threads *
614 context->fd_limit_per_thread;
615 context->pt[0].fds = lws_zalloc(n);
616 if (context->pt[0].fds == NULL) {
617 lwsl_err("OOM allocating %d fds\n", context->max_fds);
620 lwsl_info(" mem: pollfd map: %5u\n", n);
622 if (info->server_string) {
623 context->server_string = info->server_string;
624 context->server_string_len = (short)
625 strlen(context->server_string);
627 context->server_string = "libwebsockets";
628 context->server_string_len = 13;
632 /* each thread serves his own chunk of fds */
633 for (n = 1; n < (int)info->count_threads; n++)
634 context->pt[n].fds = context->pt[n - 1].fds +
635 context->fd_limit_per_thread;
638 if (lws_plat_init(context, info))
641 lws_context_init_ssl_library(info);
643 context->user_space = info->user;
646 * if he's not saying he'll make his own vhosts later then act
647 * compatibly and make a default vhost using the data in the info
649 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
650 if (!lws_create_vhost(context, info)) {
651 lwsl_err("Failed to create default vhost\n");
655 lws_context_init_extensions(info, context);
657 lwsl_notice(" mem: per-conn: %5u bytes + protocol rx buf\n",
660 strcpy(context->canonical_hostname, "unknown");
661 lws_server_get_canonical_hostname(context, info);
663 context->uid = info->uid;
664 context->gid = info->gid;
667 * drop any root privs for this process
668 * to listen on port < 1023 we would have needed root, but now we are
669 * listening, we don't want the power for anything else
671 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
672 lws_plat_drop_app_privileges(info);
675 * give all extensions a chance to create any per-context
676 * allocations they need
678 if (info->port != CONTEXT_PORT_NO_LISTEN) {
679 if (lws_ext_cb_all_exts(context, NULL,
680 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
683 if (lws_ext_cb_all_exts(context, NULL,
684 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
690 lws_context_destroy(context);
695 * lws_context_destroy() - Destroy the websocket context
696 * @context: Websocket context
698 * This function closes any active connections and then frees the
699 * context. After calling this, any further use of the context is
703 lws_context_destroy(struct lws_context *context)
705 const struct lws_protocols *protocol = NULL;
706 struct lws_context_per_thread *pt;
707 struct lws_vhost *vh = NULL, *vh1;
711 lwsl_notice("%s\n", __func__);
716 m = context->count_threads;
717 context->being_destroyed = 1;
719 memset(&wsi, 0, sizeof(wsi));
720 wsi.context = context;
723 if (context->worst_latency_info[0])
724 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
728 pt = &context->pt[m];
730 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
731 struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
735 lws_close_free_wsi(wsi,
736 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
737 /* no protocol close */);
742 * give all extensions a chance to clean up any per-context
743 * allocations they might have made
746 n = lws_ext_cb_all_exts(context, NULL,
747 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
749 n = lws_ext_cb_all_exts(context, NULL,
750 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
753 * inform all the protocols that they are done and will have no more
756 * We can't free things until after the event loop shuts down.
758 if (context->protocol_init_done)
759 vh = context->vhost_list;
762 protocol = vh->protocols;
765 while (n < vh->count_protocols) {
766 wsi.protocol = protocol;
767 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
777 for (n = 0; n < context->count_threads; n++) {
778 pt = &context->pt[n];
780 lws_libev_destroyloop(context, n);
781 lws_libuv_destroyloop(context, n);
783 lws_free_set_NULL(context->pt[n].serv_buf);
785 lws_free(pt->ah_pool);
786 if (pt->http_header_data)
787 lws_free(pt->http_header_data);
789 lws_plat_context_early_destroy(context);
790 lws_ssl_context_destroy(context);
792 if (context->pt[0].fds)
793 lws_free_set_NULL(context->pt[0].fds);
795 /* free all the vhost allocations */
797 vh = context->vhost_list;
799 protocol = vh->protocols;
802 while (n < vh->count_protocols) {
803 if (vh->protocol_vh_privs &&
804 vh->protocol_vh_privs[n]) {
805 lws_free(vh->protocol_vh_privs[n]);
806 vh->protocol_vh_privs[n] = NULL;
812 if (vh->protocol_vh_privs)
813 lws_free(vh->protocol_vh_privs);
814 lws_ssl_SSL_CTX_destroy(vh);
815 lws_free(vh->same_vh_protocol_list);
816 #ifdef LWS_WITH_PLUGINS
817 if (context->plugin_list)
818 lws_free((void *)vh->protocols);
819 #ifndef LWS_NO_EXTENSIONS
820 if (context->plugin_extension_count)
821 lws_free((void *)vh->extensions);
824 #ifdef LWS_WITH_ACCESS_LOG
825 if (vh->log_fd != LWS_INVALID_FILE)
829 vh1 = vh->vhost_next;
834 lws_plat_context_late_destroy(context);