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;
182 callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
183 void *user, void *in, size_t len)
186 struct lws_cgi_args *args;
192 case LWS_CALLBACK_HTTP:
193 #ifndef LWS_NO_SERVER
194 if (lws_http_transaction_completed(wsi))
199 case LWS_CALLBACK_HTTP_WRITEABLE:
201 if (wsi->reason_bf & 1) {
202 if (lws_cgi_write_split_stdout_headers(wsi) < 0)
205 wsi->reason_bf &= ~1;
212 /* CGI IO events (POLLIN/OUT) appear here, our default policy is:
214 * - POST data goes on subprocess stdin
215 * - subprocess stdout goes on http via writeable callback
216 * - subprocess stderr goes to the logs
218 case LWS_CALLBACK_CGI:
219 args = (struct lws_cgi_args *)in;
220 switch (args->ch) { /* which of stdin/out/err ? */
222 /* TBD stdin rx flow control */
226 /* when writing to MASTER would not block */
227 lws_callback_on_writable(wsi);
230 n = read(lws_get_socket_fd(args->stdwsi[LWS_STDERR]),
231 buf, sizeof(buf) - 1);
233 if (buf[n - 1] != '\n')
236 lwsl_notice("CGI-stderr: %s\n", buf);
242 case LWS_CALLBACK_CGI_TERMINATED:
245 case LWS_CALLBACK_CGI_STDIN_DATA: /* POST body for stdin */
246 args = (struct lws_cgi_args *)in;
247 args->data[args->len] = '\0';
248 n = write(lws_get_socket_fd(args->stdwsi[LWS_STDIN]),
249 args->data, args->len);
251 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: "
252 "sent %d only %d went", n, args->len);
262 /* list of supported protocols and callbacks */
264 static const struct lws_protocols protocols_dummy[] = {
265 /* first protocol must always be HTTP handler */
268 "http-only", /* name */
269 callback_http_dummy, /* callback */
270 0, /* per_session_data_size */
271 0, /* max frame size / rx buffer */
274 * the other protocols are provided by lws plugins
276 { NULL, NULL, 0, 0 } /* terminator */
279 LWS_VISIBLE struct lws_vhost *
280 lws_create_vhost(struct lws_context *context,
281 struct lws_context_creation_info *info)
283 struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
284 **vh1 = &context->vhost_list;
285 const struct lws_http_mount *mounts;
286 #ifdef LWS_WITH_PLUGINS
287 struct lws_plugin *plugin = context->plugin_list;
288 struct lws_protocols *lwsp;
289 int m, n, f = !info->pvo;
296 if (!info->protocols)
297 info->protocols = &protocols_dummy[0];
299 vh->context = context;
300 if (!info->vhost_name)
301 vh->name = "default";
303 vh->name = info->vhost_name;
305 vh->iface = info->iface;
306 for (vh->count_protocols = 0;
307 info->protocols[vh->count_protocols].callback;
308 vh->count_protocols++)
311 vh->options = info->options;
313 vh->keepalive_timeout = info->keepalive_timeout;
315 #ifdef LWS_WITH_PLUGINS
318 * give the vhost a unified list of protocols including the
319 * ones that came from plugins
321 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
322 (vh->count_protocols +
323 context->plugin_protocol_count + 1));
327 m = vh->count_protocols;
328 memcpy(lwsp, info->protocols,
329 sizeof(struct lws_protocols) * m);
331 /* for compatibility, all protocols enabled on vhost if only
332 * the default vhost exists. Otherwise only vhosts who ask
333 * for a protocol get it enabled.
336 if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
340 for (n = 0; n < plugin->caps.count_protocols; n++) {
342 * for compatibility's sake, no pvo implies
343 * allow all protocols
345 if (f || lws_vhost_protocol_options(vh,
346 plugin->caps.protocols[n].name)) {
348 &plugin->caps.protocols[n],
349 sizeof(struct lws_protocols));
351 vh->count_protocols++;
354 plugin = plugin->list;
356 vh->protocols = lwsp;
359 vh->protocols = info->protocols;
361 vh->same_vh_protocol_list = (struct lws **)
362 lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
364 vh->mount_list = info->mounts;
366 #ifdef LWS_USE_UNIX_SOCK
367 if (LWS_UNIX_SOCK_ENABLED(context)) {
368 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
369 vh->name, info->iface, vh->count_protocols);
372 lwsl_notice("Creating Vhost '%s' port %d, %d protocols\n",
373 vh->name, info->port, vh->count_protocols);
375 mounts = info->mounts;
377 lwsl_notice(" mounting %s%s to %s\n",
378 mount_protocols[mounts->origin_protocol],
379 mounts->origin, mounts->mountpoint);
380 mounts = mounts->mount_next;
383 #ifndef LWS_NO_EXTENSIONS
384 #ifdef LWS_WITH_PLUGINS
385 if (context->plugin_extension_count) {
388 while (info->extensions && info->extensions[m].callback)
392 * give the vhost a unified list of extensions including the
393 * ones that came from plugins
395 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
397 context->plugin_extension_count + 1));
401 memcpy((struct lws_extension *)vh->extensions, info->extensions,
402 sizeof(struct lws_extension) * m);
403 plugin = context->plugin_list;
405 memcpy((struct lws_extension *)&vh->extensions[m],
406 plugin->caps.extensions,
407 sizeof(struct lws_extension) *
408 plugin->caps.count_extensions);
409 m += plugin->caps.count_extensions;
410 plugin = plugin->list;
414 vh->extensions = info->extensions;
417 vh->listen_port = info->port;
418 vh->http_proxy_port = 0;
419 vh->http_proxy_address[0] = '\0';
421 /* either use proxy from info, or try get it from env var */
423 if (info->http_proxy_address) {
424 /* override for backwards compatibility */
425 if (info->http_proxy_port)
426 vh->http_proxy_port = info->http_proxy_port;
427 lws_set_proxy(vh, info->http_proxy_address);
429 #ifdef LWS_HAVE_GETENV
430 p = getenv("http_proxy");
432 lws_set_proxy(vh, p);
436 vh->ka_time = info->ka_time;
437 vh->ka_interval = info->ka_interval;
438 vh->ka_probes = info->ka_probes;
440 if (vh->options & LWS_SERVER_OPTION_STS)
441 lwsl_notice(" STS enabled\n");
443 #ifdef LWS_WITH_ACCESS_LOG
444 if (info->log_filepath) {
445 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
446 if (vh->log_fd == LWS_INVALID_FILE) {
447 lwsl_err("unable to open log filepath %s\n",
452 if (context->uid != -1)
453 if (chown(info->log_filepath, context->uid,
455 lwsl_err("unable to chown log file %s\n",
459 vh->log_fd = LWS_INVALID_FILE;
462 if (lws_context_init_server_ssl(info, vh))
465 if (lws_context_init_client_ssl(info, vh))
468 if (lws_context_init_server(info, vh))
476 vh1 = &(*vh1)->vhost_next;
488 * lws_create_context() - Create the websocket handler
489 * @info: pointer to struct with parameters
491 * This function creates the listening socket (if serving) and takes care
492 * of all initialization in one step.
494 * After initialization, it returns a struct lws_context * that
495 * represents this server. After calling, user code needs to take care
496 * of calling lws_service() with the context pointer to get the
497 * server's sockets serviced. This must be done in the same process
498 * context as the initialization call.
500 * The protocol callback functions are called for a handful of events
501 * including http requests coming in, websocket connections becoming
502 * established, and data arriving; it's also called periodically to allow
503 * async transmission.
505 * HTTP requests are sent always to the FIRST protocol in @protocol, since
506 * at that time websocket protocol has not been negotiated. Other
507 * protocols after the first one never see any HTTP callack activity.
509 * The server created is a simple http server by default; part of the
510 * websocket standard is upgrading this http connection to a websocket one.
512 * This allows the same server to provide files like scripts and favicon /
513 * images or whatever over http and dynamic data over websockets all in
514 * one place; they're all handled in the user callback.
516 LWS_VISIBLE struct lws_context *
517 lws_create_context(struct lws_context_creation_info *info)
519 struct lws_context *context = NULL;
521 #ifndef LWS_NO_DAEMONIZE
522 int pid_daemon = get_daemonize_pid();
525 #if defined(__ANDROID__)
529 lwsl_notice("Initial logging level %d\n", log_level);
530 lwsl_notice("Libwebsockets version: %s\n", library_version);
533 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
534 lwsl_notice("IPV6 compiled in and enabled\n");
536 lwsl_notice("IPV6 compiled in but disabled\n");
538 lwsl_notice("IPV6 not compiled in\n");
540 lws_feature_status_libev(info);
541 lws_feature_status_libuv(info);
543 lwsl_info(" LWS_DEF_HEADER_LEN : %u\n", LWS_DEF_HEADER_LEN);
544 lwsl_info(" LWS_MAX_PROTOCOLS : %u\n", LWS_MAX_PROTOCOLS);
545 lwsl_info(" LWS_MAX_SMP : %u\n", LWS_MAX_SMP);
546 lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
547 lwsl_info(" sizeof (*info) : %u\n", sizeof(*info));
549 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
551 if (lws_plat_context_early_init())
554 context = lws_zalloc(sizeof(struct lws_context));
556 lwsl_err("No memory for websocket context\n");
560 context->time_up = time(NULL);
561 #ifndef LWS_NO_DAEMONIZE
563 context->started_with_parent = pid_daemon;
564 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
567 #if defined(__ANDROID__)
568 n = getrlimit ( RLIMIT_NOFILE,&rt);
570 lwsl_err("Get RLIMIT_NOFILE failed!\n");
573 context->max_fds = rt.rlim_cur;
575 context->max_fds = getdtablesize();
578 if (info->count_threads)
579 context->count_threads = info->count_threads;
581 context->count_threads = 1;
583 if (context->count_threads > LWS_MAX_SMP)
584 context->count_threads = LWS_MAX_SMP;
586 context->token_limits = info->token_limits;
588 context->options = info->options;
590 if (info->timeout_secs)
591 context->timeout_secs = info->timeout_secs;
593 context->timeout_secs = AWAITING_TIMEOUT;
595 lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
597 if (info->max_http_header_data)
598 context->max_http_header_data = info->max_http_header_data;
600 context->max_http_header_data = LWS_DEF_HEADER_LEN;
601 if (info->max_http_header_pool)
602 context->max_http_header_pool = info->max_http_header_pool;
604 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
607 * Allocate the per-thread storage for scratchpad buffers,
608 * and header data pool
610 for (n = 0; n < context->count_threads; n++) {
611 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
612 if (!context->pt[n].serv_buf) {
617 context->pt[n].context = context;
618 context->pt[n].tid = n;
619 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
620 context->max_http_header_pool);
621 if (!context->pt[n].http_header_data)
624 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
625 context->max_http_header_pool);
626 for (m = 0; m < context->max_http_header_pool; m++)
627 context->pt[n].ah_pool[m].data =
628 (char *)context->pt[n].http_header_data +
629 (m * context->max_http_header_data);
630 if (!context->pt[n].ah_pool)
633 lws_pt_mutex_init(&context->pt[n]);
636 if (info->fd_limit_per_thread)
637 context->fd_limit_per_thread = info->fd_limit_per_thread;
639 context->fd_limit_per_thread = context->max_fds /
640 context->count_threads;
642 lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
643 context->fd_limit_per_thread);
645 memset(&wsi, 0, sizeof(wsi));
646 wsi.context = context;
648 if (!info->ka_interval && info->ka_time > 0) {
649 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
654 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
655 * enable libev mediated SIGINT handling with a default handler of
656 * lws_sigint_cb. The handler can be overridden or disabled
657 * by invoking lws_sigint_cfg after creating the context, but
658 * before invoking lws_initloop:
660 context->use_ev_sigint = 1;
661 context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
662 #endif /* LWS_USE_LIBEV */
664 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
665 * enable libev mediated SIGINT handling with a default handler of
666 * lws_sigint_cb. The handler can be overridden or disabled
667 * by invoking lws_sigint_cfg after creating the context, but
668 * before invoking lws_initloop:
670 context->use_ev_sigint = 1;
671 context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
674 lwsl_info(" mem: context: %5u bytes (%d ctx + (%d thr x %d))\n",
675 sizeof(struct lws_context) +
676 (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
677 sizeof(struct lws_context),
678 context->count_threads,
679 LWS_MAX_SOCKET_IO_BUF);
681 lwsl_info(" mem: http hdr rsvd: %5u bytes (%u thr x (%u + %u) x %u))\n",
682 (context->max_http_header_data +
683 sizeof(struct allocated_headers)) *
684 context->max_http_header_pool * context->count_threads,
685 context->count_threads,
686 context->max_http_header_data,
687 sizeof(struct allocated_headers),
688 context->max_http_header_pool);
689 n = sizeof(struct lws_pollfd) * context->count_threads *
690 context->fd_limit_per_thread;
691 context->pt[0].fds = lws_zalloc(n);
692 if (context->pt[0].fds == NULL) {
693 lwsl_err("OOM allocating %d fds\n", context->max_fds);
696 lwsl_info(" mem: pollfd map: %5u\n", n);
698 if (info->server_string) {
699 context->server_string = info->server_string;
700 context->server_string_len = (short)
701 strlen(context->server_string);
703 context->server_string = "libwebsockets";
704 context->server_string_len = 13;
708 /* each thread serves his own chunk of fds */
709 for (n = 1; n < (int)info->count_threads; n++)
710 context->pt[n].fds = context->pt[n - 1].fds +
711 context->fd_limit_per_thread;
714 if (lws_plat_init(context, info))
717 lws_context_init_ssl_library(info);
719 context->user_space = info->user;
722 * if he's not saying he'll make his own vhosts later then act
723 * compatibly and make a default vhost using the data in the info
725 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
726 if (!lws_create_vhost(context, info)) {
727 lwsl_err("Failed to create default vhost\n");
731 lws_context_init_extensions(info, context);
733 lwsl_notice(" mem: per-conn: %5u bytes + protocol rx buf\n",
736 strcpy(context->canonical_hostname, "unknown");
737 lws_server_get_canonical_hostname(context, info);
739 context->uid = info->uid;
740 context->gid = info->gid;
743 * drop any root privs for this process
744 * to listen on port < 1023 we would have needed root, but now we are
745 * listening, we don't want the power for anything else
747 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
748 lws_plat_drop_app_privileges(info);
751 * give all extensions a chance to create any per-context
752 * allocations they need
754 if (info->port != CONTEXT_PORT_NO_LISTEN) {
755 if (lws_ext_cb_all_exts(context, NULL,
756 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
759 if (lws_ext_cb_all_exts(context, NULL,
760 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
766 lws_context_destroy(context);
771 * lws_context_destroy() - Destroy the websocket context
772 * @context: Websocket context
774 * This function closes any active connections and then frees the
775 * context. After calling this, any further use of the context is
779 lws_context_destroy(struct lws_context *context)
781 const struct lws_protocols *protocol = NULL;
782 struct lws_context_per_thread *pt;
783 struct lws_vhost *vh = NULL, *vh1;
787 lwsl_notice("%s\n", __func__);
792 m = context->count_threads;
793 context->being_destroyed = 1;
795 memset(&wsi, 0, sizeof(wsi));
796 wsi.context = context;
799 if (context->worst_latency_info[0])
800 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
804 pt = &context->pt[m];
806 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
807 struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
811 lws_close_free_wsi(wsi,
812 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
813 /* no protocol close */);
818 * give all extensions a chance to clean up any per-context
819 * allocations they might have made
822 n = lws_ext_cb_all_exts(context, NULL,
823 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
825 n = lws_ext_cb_all_exts(context, NULL,
826 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
829 * inform all the protocols that they are done and will have no more
832 * We can't free things until after the event loop shuts down.
834 if (context->protocol_init_done)
835 vh = context->vhost_list;
838 protocol = vh->protocols;
841 while (n < vh->count_protocols) {
842 wsi.protocol = protocol;
843 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
853 for (n = 0; n < context->count_threads; n++) {
854 pt = &context->pt[n];
856 lws_libev_destroyloop(context, n);
857 lws_libuv_destroyloop(context, n);
859 lws_free_set_NULL(context->pt[n].serv_buf);
861 lws_free(pt->ah_pool);
862 if (pt->http_header_data)
863 lws_free(pt->http_header_data);
865 lws_plat_context_early_destroy(context);
866 lws_ssl_context_destroy(context);
868 if (context->pt[0].fds)
869 lws_free_set_NULL(context->pt[0].fds);
871 /* free all the vhost allocations */
873 vh = context->vhost_list;
875 protocol = vh->protocols;
878 while (n < vh->count_protocols) {
879 if (vh->protocol_vh_privs &&
880 vh->protocol_vh_privs[n]) {
881 lws_free(vh->protocol_vh_privs[n]);
882 vh->protocol_vh_privs[n] = NULL;
888 if (vh->protocol_vh_privs)
889 lws_free(vh->protocol_vh_privs);
890 lws_ssl_SSL_CTX_destroy(vh);
891 lws_free(vh->same_vh_protocol_list);
892 #ifdef LWS_WITH_PLUGINS
893 if (context->plugin_list)
894 lws_free((void *)vh->protocols);
895 #ifndef LWS_NO_EXTENSIONS
896 if (context->plugin_extension_count)
897 lws_free((void *)vh->extensions);
900 #ifdef LWS_WITH_ACCESS_LOG
901 if (vh->log_fd != LWS_INVALID_FILE)
905 vh1 = vh->vhost_next;
910 lws_plat_context_late_destroy(context);