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) {
72 while (n < vhost->count_protocols &&
73 strcmp(vhost->protocols[n].name, prot->name))
76 if (n == vhost->count_protocols)
80 vhost->protocol_vh_privs[n] = lws_zalloc(size);
81 return vhost->protocol_vh_privs[n];
85 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot)
89 if (!vhost->protocol_vh_privs)
92 while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
95 if (n == vhost->count_protocols) {
97 while (n < vhost->count_protocols &&
98 strcmp(vhost->protocols[n].name, prot->name))
101 if (n == vhost->count_protocols) {
102 lwsl_err("%s: unknown protocol %p\n", __func__, prot);
107 return vhost->protocol_vh_privs[n];
110 static const struct lws_protocol_vhost_options *
111 lws_vhost_protocol_options(struct lws_vhost *vh, const char *name)
113 const struct lws_protocol_vhost_options *pvo = vh->pvo;
116 // lwsl_notice("%s: '%s' '%s'\n", __func__, pvo->name, name);
117 if (!strcmp(pvo->name, name))
126 lws_protocol_init(struct lws_context *context)
128 struct lws_vhost *vh = context->vhost_list;
129 const struct lws_protocol_vhost_options *pvo, *pvo1;
133 memset(&wsi, 0, sizeof(wsi));
134 wsi.context = context;
136 lwsl_notice("%s\n", __func__);
141 /* initialize supported protocols on this vhost */
143 for (n = 0; n < vh->count_protocols; n++) {
144 wsi.protocol = &vh->protocols[n];
146 pvo = lws_vhost_protocol_options(vh,
147 vh->protocols[n].name);
150 * linked list of options specific to
157 lwsl_notice(" vh %s prot %s opt %s\n",
159 vh->protocols[n].name,
162 if (!strcmp(pvo->name, "default")) {
163 lwsl_notice("Setting default "
164 "protocol for vh %s to %s\n",
166 vh->protocols[n].name);
167 vh->default_protocol_index = n;
176 * inform all the protocols that they are doing their one-time
177 * initialization if they want to.
179 * NOTE the wsi is all zeros except for the context, vh and
180 * protocol ptrs so lws_get_context(wsi) etc can work
182 if (vh->protocols[n].callback(&wsi,
183 LWS_CALLBACK_PROTOCOL_INIT, NULL,
191 context->protocol_init_done = 1;
192 lws_finalize_startup(context);
198 callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
199 void *user, void *in, size_t len)
202 struct lws_cgi_args *args;
208 case LWS_CALLBACK_HTTP:
209 #ifndef LWS_NO_SERVER
210 if (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL))
213 if (lws_http_transaction_completed(wsi))
218 case LWS_CALLBACK_HTTP_WRITEABLE:
220 if (wsi->reason_bf & 1) {
221 if (lws_cgi_write_split_stdout_headers(wsi) < 0)
224 wsi->reason_bf &= ~1;
232 /* CGI IO events (POLLIN/OUT) appear here, our default policy is:
234 * - POST data goes on subprocess stdin
235 * - subprocess stdout goes on http via writeable callback
236 * - subprocess stderr goes to the logs
238 case LWS_CALLBACK_CGI:
239 args = (struct lws_cgi_args *)in;
240 switch (args->ch) { /* which of stdin/out/err ? */
242 /* TBD stdin rx flow control */
246 /* when writing to MASTER would not block */
247 lws_callback_on_writable(wsi);
250 n = read(lws_get_socket_fd(args->stdwsi[LWS_STDERR]),
251 buf, sizeof(buf) - 1);
253 if (buf[n - 1] != '\n')
256 lwsl_notice("CGI-stderr: %s\n", buf);
262 case LWS_CALLBACK_CGI_TERMINATED:
265 case LWS_CALLBACK_CGI_STDIN_DATA: /* POST body for stdin */
266 args = (struct lws_cgi_args *)in;
267 args->data[args->len] = '\0';
268 n = write(lws_get_socket_fd(args->stdwsi[LWS_STDIN]),
269 args->data, args->len);
271 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: "
272 "sent %d only %d went", n, args->len);
282 /* list of supported protocols and callbacks */
284 static const struct lws_protocols protocols_dummy[] = {
285 /* first protocol must always be HTTP handler */
288 "http-only", /* name */
289 callback_http_dummy, /* callback */
290 0, /* per_session_data_size */
291 0, /* max frame size / rx buffer */
294 * the other protocols are provided by lws plugins
296 { NULL, NULL, 0, 0 } /* terminator */
299 LWS_VISIBLE struct lws_vhost *
300 lws_create_vhost(struct lws_context *context,
301 struct lws_context_creation_info *info)
303 struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
304 **vh1 = &context->vhost_list;
305 const struct lws_http_mount *mounts;
306 const struct lws_protocol_vhost_options *pvo;
307 #ifdef LWS_WITH_PLUGINS
308 struct lws_plugin *plugin = context->plugin_list;
309 struct lws_protocols *lwsp;
310 int m, f = !info->pvo;
318 if (!info->protocols)
319 info->protocols = &protocols_dummy[0];
321 vh->context = context;
322 if (!info->vhost_name)
323 vh->name = "default";
325 vh->name = info->vhost_name;
327 vh->iface = info->iface;
328 for (vh->count_protocols = 0;
329 info->protocols[vh->count_protocols].callback;
330 vh->count_protocols++)
333 vh->options = info->options;
335 vh->keepalive_timeout = info->keepalive_timeout;
337 #ifdef LWS_WITH_PLUGINS
340 * give the vhost a unified list of protocols including the
341 * ones that came from plugins
343 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
344 (vh->count_protocols +
345 context->plugin_protocol_count + 1));
349 m = vh->count_protocols;
350 memcpy(lwsp, info->protocols,
351 sizeof(struct lws_protocols) * m);
353 /* for compatibility, all protocols enabled on vhost if only
354 * the default vhost exists. Otherwise only vhosts who ask
355 * for a protocol get it enabled.
358 if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
362 for (n = 0; n < plugin->caps.count_protocols; n++) {
364 * for compatibility's sake, no pvo implies
365 * allow all protocols
367 if (f || lws_vhost_protocol_options(vh,
368 plugin->caps.protocols[n].name)) {
370 &plugin->caps.protocols[n],
371 sizeof(struct lws_protocols));
373 vh->count_protocols++;
376 plugin = plugin->list;
378 vh->protocols = lwsp;
381 vh->protocols = info->protocols;
383 vh->same_vh_protocol_list = (struct lws **)
384 lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
386 vh->mount_list = info->mounts;
388 #ifdef LWS_USE_UNIX_SOCK
389 if (LWS_UNIX_SOCK_ENABLED(context)) {
390 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
391 vh->name, info->iface, vh->count_protocols);
394 lwsl_notice("Creating Vhost '%s' port %d, %d protocols, IPv6 %s\n",
395 vh->name, info->port, vh->count_protocols, LWS_IPV6_ENABLED(vh) ? "on" : "off");
397 mounts = info->mounts;
399 lwsl_notice(" mounting %s%s to %s\n",
400 mount_protocols[mounts->origin_protocol],
401 mounts->origin, mounts->mountpoint);
403 /* convert interpreter protocol names to pointers */
404 pvo = mounts->interpret;
406 for (n = 0; n < vh->count_protocols; n++)
407 if (!strcmp(pvo->value, vh->protocols[n].name)) {
408 ((struct lws_protocol_vhost_options *)pvo)->value =
409 (const char *)(long)n;
412 if (n == vh->count_protocols)
413 lwsl_err("ignoring unknown interpret protocol %s\n", pvo->value);
417 mounts = mounts->mount_next;
420 #ifndef LWS_NO_EXTENSIONS
421 #ifdef LWS_WITH_PLUGINS
422 if (context->plugin_extension_count) {
425 while (info->extensions && info->extensions[m].callback)
429 * give the vhost a unified list of extensions including the
430 * ones that came from plugins
432 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
434 context->plugin_extension_count + 1));
438 memcpy((struct lws_extension *)vh->extensions, info->extensions,
439 sizeof(struct lws_extension) * m);
440 plugin = context->plugin_list;
442 memcpy((struct lws_extension *)&vh->extensions[m],
443 plugin->caps.extensions,
444 sizeof(struct lws_extension) *
445 plugin->caps.count_extensions);
446 m += plugin->caps.count_extensions;
447 plugin = plugin->list;
451 vh->extensions = info->extensions;
454 vh->listen_port = info->port;
455 vh->http_proxy_port = 0;
456 vh->http_proxy_address[0] = '\0';
458 /* either use proxy from info, or try get it from env var */
460 if (info->http_proxy_address) {
461 /* override for backwards compatibility */
462 if (info->http_proxy_port)
463 vh->http_proxy_port = info->http_proxy_port;
464 lws_set_proxy(vh, info->http_proxy_address);
466 #ifdef LWS_HAVE_GETENV
467 p = getenv("http_proxy");
469 lws_set_proxy(vh, p);
473 vh->ka_time = info->ka_time;
474 vh->ka_interval = info->ka_interval;
475 vh->ka_probes = info->ka_probes;
477 if (vh->options & LWS_SERVER_OPTION_STS)
478 lwsl_notice(" STS enabled\n");
480 #ifdef LWS_WITH_ACCESS_LOG
481 if (info->log_filepath) {
482 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
483 if (vh->log_fd == (int)LWS_INVALID_FILE) {
484 lwsl_err("unable to open log filepath %s\n",
489 if (context->uid != -1)
490 if (chown(info->log_filepath, context->uid,
492 lwsl_err("unable to chown log file %s\n",
496 vh->log_fd = (int)LWS_INVALID_FILE;
499 if (lws_context_init_server_ssl(info, vh))
502 if (lws_context_init_client_ssl(info, vh))
505 if (lws_context_init_server(info, vh))
513 vh1 = &(*vh1)->vhost_next;
525 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
526 struct lws_vhost *vhost)
528 struct lws_context_creation_info i;
530 memcpy(&i, info, sizeof(i));
531 i.port = CONTEXT_PORT_NO_LISTEN;
533 return lws_context_init_client_ssl(&i, vhost);
536 LWS_VISIBLE struct lws_context *
537 lws_create_context(struct lws_context_creation_info *info)
539 struct lws_context *context = NULL;
541 #ifndef LWS_NO_DAEMONIZE
542 int pid_daemon = get_daemonize_pid();
545 #if defined(__ANDROID__)
549 lwsl_notice("Initial logging level %d\n", log_level);
550 lwsl_notice("Libwebsockets version: %s\n", library_version);
553 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
554 lwsl_notice("IPV6 compiled in and enabled\n");
556 lwsl_notice("IPV6 compiled in but disabled\n");
558 lwsl_notice("IPV6 not compiled in\n");
560 lws_feature_status_libev(info);
561 lws_feature_status_libuv(info);
563 lwsl_info(" LWS_DEF_HEADER_LEN : %u\n", LWS_DEF_HEADER_LEN);
564 lwsl_info(" LWS_MAX_PROTOCOLS : %u\n", LWS_MAX_PROTOCOLS);
565 lwsl_info(" LWS_MAX_SMP : %u\n", LWS_MAX_SMP);
566 lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
567 lwsl_info(" sizeof (*info) : %u\n", sizeof(*info));
569 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
571 if (lws_plat_context_early_init())
574 context = lws_zalloc(sizeof(struct lws_context));
576 lwsl_err("No memory for websocket context\n");
580 if (info->pt_serv_buf_size)
581 context->pt_serv_buf_size = info->pt_serv_buf_size;
583 context->pt_serv_buf_size = 4096;
585 context->time_up = time(NULL);
586 #ifndef LWS_NO_DAEMONIZE
588 context->started_with_parent = pid_daemon;
589 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
592 #if defined(__ANDROID__)
593 n = getrlimit ( RLIMIT_NOFILE,&rt);
595 lwsl_err("Get RLIMIT_NOFILE failed!\n");
598 context->max_fds = rt.rlim_cur;
600 context->max_fds = getdtablesize();
603 if (info->count_threads)
604 context->count_threads = info->count_threads;
606 context->count_threads = 1;
608 if (context->count_threads > LWS_MAX_SMP)
609 context->count_threads = LWS_MAX_SMP;
611 context->token_limits = info->token_limits;
613 context->options = info->options;
615 if (info->timeout_secs)
616 context->timeout_secs = info->timeout_secs;
618 context->timeout_secs = AWAITING_TIMEOUT;
620 context->ws_ping_pong_interval = info->ws_ping_pong_interval;
622 lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
624 if (info->max_http_header_data)
625 context->max_http_header_data = info->max_http_header_data;
627 if (info->max_http_header_data2)
628 context->max_http_header_data =
629 info->max_http_header_data2;
631 context->max_http_header_data = LWS_DEF_HEADER_LEN;
632 if (info->max_http_header_pool)
633 context->max_http_header_pool = info->max_http_header_pool;
635 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
638 * Allocate the per-thread storage for scratchpad buffers,
639 * and header data pool
641 for (n = 0; n < context->count_threads; n++) {
642 context->pt[n].serv_buf = lws_zalloc(context->pt_serv_buf_size);
643 if (!context->pt[n].serv_buf) {
648 context->pt[n].context = context;
649 context->pt[n].tid = n;
650 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
651 context->max_http_header_pool);
652 if (!context->pt[n].http_header_data)
655 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
656 context->max_http_header_pool);
657 for (m = 0; m < context->max_http_header_pool; m++)
658 context->pt[n].ah_pool[m].data =
659 (char *)context->pt[n].http_header_data +
660 (m * context->max_http_header_data);
661 if (!context->pt[n].ah_pool)
664 lws_pt_mutex_init(&context->pt[n]);
667 if (info->fd_limit_per_thread)
668 context->fd_limit_per_thread = info->fd_limit_per_thread;
670 context->fd_limit_per_thread = context->max_fds /
671 context->count_threads;
673 lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
674 context->fd_limit_per_thread);
676 memset(&wsi, 0, sizeof(wsi));
677 wsi.context = context;
679 if (!info->ka_interval && info->ka_time > 0) {
680 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
685 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
686 * enable libev mediated SIGINT handling with a default handler of
687 * lws_sigint_cb. The handler can be overridden or disabled
688 * by invoking lws_sigint_cfg after creating the context, but
689 * before invoking lws_initloop:
691 context->use_ev_sigint = 1;
692 context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
693 #endif /* LWS_USE_LIBEV */
695 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
696 * enable libev mediated SIGINT handling with a default handler of
697 * lws_sigint_cb. The handler can be overridden or disabled
698 * by invoking lws_sigint_cfg after creating the context, but
699 * before invoking lws_initloop:
701 context->use_ev_sigint = 1;
702 context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
705 lwsl_info(" mem: context: %5u bytes (%d ctx + (%d thr x %d))\n",
706 sizeof(struct lws_context) +
707 (context->count_threads * context->pt_serv_buf_size),
708 sizeof(struct lws_context),
709 context->count_threads,
710 context->pt_serv_buf_size);
712 lwsl_info(" mem: http hdr rsvd: %5u bytes (%u thr x (%u + %u) x %u))\n",
713 (context->max_http_header_data +
714 sizeof(struct allocated_headers)) *
715 context->max_http_header_pool * context->count_threads,
716 context->count_threads,
717 context->max_http_header_data,
718 sizeof(struct allocated_headers),
719 context->max_http_header_pool);
720 n = sizeof(struct lws_pollfd) * context->count_threads *
721 context->fd_limit_per_thread;
722 context->pt[0].fds = lws_zalloc(n);
723 if (context->pt[0].fds == NULL) {
724 lwsl_err("OOM allocating %d fds\n", context->max_fds);
727 lwsl_info(" mem: pollfd map: %5u\n", n);
729 if (info->server_string) {
730 context->server_string = info->server_string;
731 context->server_string_len = (short)
732 strlen(context->server_string);
734 context->server_string = "libwebsockets";
735 context->server_string_len = 13;
739 /* each thread serves his own chunk of fds */
740 for (n = 1; n < (int)info->count_threads; n++)
741 context->pt[n].fds = context->pt[n - 1].fds +
742 context->fd_limit_per_thread;
745 if (lws_plat_init(context, info))
748 lws_context_init_ssl_library(info);
750 context->user_space = info->user;
753 * if he's not saying he'll make his own vhosts later then act
754 * compatibly and make a default vhost using the data in the info
756 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
757 if (!lws_create_vhost(context, info)) {
758 lwsl_err("Failed to create default vhost\n");
762 lws_context_init_extensions(info, context);
764 lwsl_notice(" mem: per-conn: %5u bytes + protocol rx buf\n",
767 strcpy(context->canonical_hostname, "unknown");
768 lws_server_get_canonical_hostname(context, info);
770 context->uid = info->uid;
771 context->gid = info->gid;
774 * drop any root privs for this process
775 * to listen on port < 1023 we would have needed root, but now we are
776 * listening, we don't want the power for anything else
778 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
779 lws_plat_drop_app_privileges(info);
782 * give all extensions a chance to create any per-context
783 * allocations they need
785 if (info->port != CONTEXT_PORT_NO_LISTEN) {
786 if (lws_ext_cb_all_exts(context, NULL,
787 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
790 if (lws_ext_cb_all_exts(context, NULL,
791 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
797 lws_context_destroy(context);
802 lws_context_destroy(struct lws_context *context)
804 const struct lws_protocols *protocol = NULL;
805 struct lws_context_per_thread *pt;
806 struct lws_vhost *vh = NULL, *vh1;
810 lwsl_notice("%s\n", __func__);
815 m = context->count_threads;
816 context->being_destroyed = 1;
818 memset(&wsi, 0, sizeof(wsi));
819 wsi.context = context;
822 if (context->worst_latency_info[0])
823 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
827 pt = &context->pt[m];
829 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
830 struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
834 lws_close_free_wsi(wsi,
835 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
836 /* no protocol close */);
839 lws_pt_mutex_destroy(pt);
842 * give all extensions a chance to clean up any per-context
843 * allocations they might have made
846 n = lws_ext_cb_all_exts(context, NULL,
847 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
849 n = lws_ext_cb_all_exts(context, NULL,
850 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
853 * inform all the protocols that they are done and will have no more
856 * We can't free things until after the event loop shuts down.
858 if (context->protocol_init_done)
859 vh = context->vhost_list;
862 protocol = vh->protocols;
865 while (n < vh->count_protocols) {
866 wsi.protocol = protocol;
867 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
877 for (n = 0; n < context->count_threads; n++) {
878 pt = &context->pt[n];
880 lws_libev_destroyloop(context, n);
881 lws_libuv_destroyloop(context, n);
883 lws_free_set_NULL(context->pt[n].serv_buf);
885 lws_free(pt->ah_pool);
886 if (pt->http_header_data)
887 lws_free(pt->http_header_data);
889 lws_plat_context_early_destroy(context);
890 lws_ssl_context_destroy(context);
892 if (context->pt[0].fds)
893 lws_free_set_NULL(context->pt[0].fds);
895 /* free all the vhost allocations */
897 vh = context->vhost_list;
899 protocol = vh->protocols;
902 while (n < vh->count_protocols) {
903 if (vh->protocol_vh_privs &&
904 vh->protocol_vh_privs[n]) {
905 lws_free(vh->protocol_vh_privs[n]);
906 vh->protocol_vh_privs[n] = NULL;
912 if (vh->protocol_vh_privs)
913 lws_free(vh->protocol_vh_privs);
914 lws_ssl_SSL_CTX_destroy(vh);
915 lws_free(vh->same_vh_protocol_list);
916 #ifdef LWS_WITH_PLUGINS
917 if (context->plugin_list)
918 lws_free((void *)vh->protocols);
919 #ifndef LWS_NO_EXTENSIONS
920 if (context->plugin_extension_count)
921 lws_free((void *)vh->extensions);
924 #ifdef LWS_WITH_ACCESS_LOG
925 if (vh->log_fd != (int)LWS_INVALID_FILE)
929 vh1 = vh->vhost_next;
934 lws_plat_context_late_destroy(context);