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[] = {
52 LWS_VISIBLE LWS_EXTERN int
53 lws_write_http_mount(struct lws_http_mount *next, struct lws_http_mount **res,
54 void *store, const char *mountpoint, const char *origin,
55 const char *def, struct lws_protocol_vhost_options *cgienv,
58 struct lws_http_mount *m;
60 unsigned long l = (unsigned long)store;
67 m = (struct lws_http_mount *)store;
71 m->mountpoint = mountpoint;
72 m->mountpoint_len = (unsigned char)strlen(mountpoint);
75 m->cgi_timeout = cgi_timeout;
80 for (n = 0; n < ARRAY_SIZE(mount_protocols); n++)
81 if (!strncmp(origin, mount_protocols[n],
82 strlen(mount_protocols[n]))) {
83 m->origin_protocol = n;
84 m->origin = origin + strlen(mount_protocols[n]);
88 if (n == ARRAY_SIZE(mount_protocols)) {
89 lwsl_err("unsupported protocol:// %s\n", origin);
90 return 0; /* ie, fail */
93 return ((char *)store + sizeof(*m)) - (char *)orig;
97 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
102 /* allocate the vh priv array only on demand */
103 if (!vhost->protocol_vh_privs) {
104 vhost->protocol_vh_privs = (void **)lws_zalloc(
105 vhost->count_protocols * sizeof(void *));
106 if (!vhost->protocol_vh_privs)
110 while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
113 if (n == vhost->count_protocols)
116 vhost->protocol_vh_privs[n] = lws_zalloc(size);
117 return vhost->protocol_vh_privs[n];
121 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot)
125 if (!vhost->protocol_vh_privs)
128 while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
131 if (n == vhost->count_protocols) {
132 lwsl_err("%s: unknown protocol %p\n", __func__, prot);
136 return vhost->protocol_vh_privs[n];
139 static struct lws_protocol_vhost_options *
140 lws_vhost_protocol_options(struct lws_vhost *vh, const char *name)
142 struct lws_protocol_vhost_options *pvo = vh->pvo;
145 // lwsl_notice("%s: '%s' '%s'\n", __func__, pvo->name, name);
146 if (!strcmp(pvo->name, name))
155 lws_protocol_init(struct lws_context *context)
157 struct lws_vhost *vh = context->vhost_list;
158 struct lws_protocol_vhost_options *pvo;
162 memset(&wsi, 0, sizeof(wsi));
163 wsi.context = context;
168 /* initialize supported protocols on this vhost */
170 for (n = 0; n < vh->count_protocols; n++) {
171 wsi.protocol = &vh->protocols[n];
173 pvo = lws_vhost_protocol_options(vh,
174 vh->protocols[n].name);
177 * linked list of options specific to
183 * inform all the protocols that they are doing their one-time
184 * initialization if they want to.
186 * NOTE the wsi is all zeros except for the context, vh and
187 * protocol ptrs so lws_get_context(wsi) etc can work
189 vh->protocols[n].callback(&wsi,
190 LWS_CALLBACK_PROTOCOL_INIT, NULL, pvo, 0);
196 context->protocol_init_done = 1;
201 LWS_VISIBLE struct lws_vhost *
202 lws_create_vhost(struct lws_context *context,
203 struct lws_context_creation_info *info,
204 struct lws_http_mount *mounts)
206 struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
207 **vh1 = &context->vhost_list;
208 #ifdef LWS_WITH_PLUGINS
209 struct lws_plugin *plugin = context->plugin_list;
210 struct lws_protocols *lwsp;
211 int m, n, f = !info->pvo;
218 vh->context = context;
219 if (!info->vhost_name)
220 vh->name = "default";
222 vh->name = info->vhost_name;
224 vh->iface = info->iface;
225 for (vh->count_protocols = 0;
226 info->protocols[vh->count_protocols].callback;
227 vh->count_protocols++)
231 vh->keepalive_timeout = info->keepalive_timeout;
233 #ifdef LWS_WITH_PLUGINS
236 * give the vhost a unified list of protocols including the
237 * ones that came from plugins
239 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
240 (vh->count_protocols +
241 context->plugin_protocol_count + 1));
245 m = vh->count_protocols;
246 memcpy(lwsp, info->protocols,
247 sizeof(struct lws_protocols) * m);
249 /* for compatibility, all protocols enabled on vhost if only
250 * the default vhost exists. Otherwise only vhosts who ask
251 * for a protocol get it enabled.
254 if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
258 for (n = 0; n < plugin->caps.count_protocols; n++) {
260 * for compatibility's sake, no pvo implies
261 * allow all protocols
263 if (f || lws_vhost_protocol_options(vh,
264 plugin->caps.protocols[n].name)) {
266 &plugin->caps.protocols[n],
267 sizeof(struct lws_protocols));
269 vh->count_protocols++;
272 plugin = plugin->list;
274 vh->protocols = lwsp;
277 vh->protocols = info->protocols;
279 vh->mount_list = mounts;
281 #ifdef LWS_USE_UNIX_SOCK
282 if (LWS_UNIX_SOCK_ENABLED(context)) {
283 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
284 vh->name, info->iface, vh->count_protocols);
287 lwsl_notice("Creating Vhost '%s' port %d, %d protocols\n",
288 vh->name, info->port, vh->count_protocols);
291 lwsl_notice(" mounting %s%s to %s\n",
292 mount_protocols[mounts->origin_protocol],
293 mounts->origin, mounts->mountpoint);
294 mounts = mounts->mount_next;
297 #ifndef LWS_NO_EXTENSIONS
298 #ifdef LWS_WITH_PLUGINS
299 if (context->plugin_extension_count) {
302 while (info->extensions && info->extensions[m].callback)
306 * give the vhost a unified list of extensions including the
307 * ones that came from plugins
309 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
311 context->plugin_extension_count + 1));
315 memcpy((struct lws_extension *)vh->extensions, info->extensions,
316 sizeof(struct lws_extension) * m);
318 memcpy((struct lws_extension *)&vh->extensions[m], plugin->caps.extensions,
319 sizeof(struct lws_extension) *
320 plugin->caps.count_extensions);
321 m += plugin->caps.count_extensions;
322 plugin = plugin->list;
326 vh->extensions = info->extensions;
329 vh->listen_port = info->port;
330 vh->http_proxy_port = 0;
331 vh->http_proxy_address[0] = '\0';
333 /* either use proxy from info, or try get it from env var */
335 if (info->http_proxy_address) {
336 /* override for backwards compatibility */
337 if (info->http_proxy_port)
338 vh->http_proxy_port = info->http_proxy_port;
339 lws_set_proxy(vh, info->http_proxy_address);
341 #ifdef LWS_HAVE_GETENV
342 p = getenv("http_proxy");
344 lws_set_proxy(vh, p);
348 vh->ka_time = info->ka_time;
349 vh->ka_interval = info->ka_interval;
350 vh->ka_probes = info->ka_probes;
352 if (lws_context_init_server_ssl(info, vh))
355 if (lws_context_init_client_ssl(info, vh))
358 if (lws_context_init_server(info, vh))
366 vh1 = &(*vh1)->vhost_next;
378 * lws_create_context() - Create the websocket handler
379 * @info: pointer to struct with parameters
381 * This function creates the listening socket (if serving) and takes care
382 * of all initialization in one step.
384 * After initialization, it returns a struct lws_context * that
385 * represents this server. After calling, user code needs to take care
386 * of calling lws_service() with the context pointer to get the
387 * server's sockets serviced. This must be done in the same process
388 * context as the initialization call.
390 * The protocol callback functions are called for a handful of events
391 * including http requests coming in, websocket connections becoming
392 * established, and data arriving; it's also called periodically to allow
393 * async transmission.
395 * HTTP requests are sent always to the FIRST protocol in @protocol, since
396 * at that time websocket protocol has not been negotiated. Other
397 * protocols after the first one never see any HTTP callack activity.
399 * The server created is a simple http server by default; part of the
400 * websocket standard is upgrading this http connection to a websocket one.
402 * This allows the same server to provide files like scripts and favicon /
403 * images or whatever over http and dynamic data over websockets all in
404 * one place; they're all handled in the user callback.
406 LWS_VISIBLE struct lws_context *
407 lws_create_context(struct lws_context_creation_info *info)
409 struct lws_context *context = NULL;
411 #ifndef LWS_NO_DAEMONIZE
412 int pid_daemon = get_daemonize_pid();
415 #if defined(__ANDROID__)
420 lwsl_notice("Initial logging level %d\n", log_level);
421 lwsl_notice("Libwebsockets version: %s\n", library_version);
424 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
425 lwsl_notice("IPV6 compiled in and enabled\n");
427 lwsl_notice("IPV6 compiled in but disabled\n");
429 lwsl_notice("IPV6 not compiled in\n");
431 lws_feature_status_libev(info);
432 lws_feature_status_libuv(info);
434 lwsl_info(" LWS_DEF_HEADER_LEN : %u\n", LWS_DEF_HEADER_LEN);
435 lwsl_info(" LWS_MAX_PROTOCOLS : %u\n", LWS_MAX_PROTOCOLS);
436 lwsl_info(" LWS_MAX_SMP : %u\n", LWS_MAX_SMP);
437 lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
438 lwsl_info(" sizeof (*info) : %u\n", sizeof(*info));
440 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
442 if (lws_plat_context_early_init())
445 context = lws_zalloc(sizeof(struct lws_context));
447 lwsl_err("No memory for websocket context\n");
450 #ifndef LWS_NO_DAEMONIZE
452 context->started_with_parent = pid_daemon;
453 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
456 #if defined(__ANDROID__)
457 n = getrlimit ( RLIMIT_NOFILE,&rt);
459 lwsl_err("Get RLIMIT_NOFILE failed!\n");
462 context->max_fds = rt.rlim_cur;
464 context->max_fds = getdtablesize();
467 if (info->count_threads)
468 context->count_threads = info->count_threads;
470 context->count_threads = 1;
472 if (context->count_threads > LWS_MAX_SMP)
473 context->count_threads = LWS_MAX_SMP;
475 context->token_limits = info->token_limits;
477 context->options = info->options;
479 if (info->timeout_secs)
480 context->timeout_secs = info->timeout_secs;
482 context->timeout_secs = AWAITING_TIMEOUT;
484 lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
486 if (info->max_http_header_data)
487 context->max_http_header_data = info->max_http_header_data;
489 context->max_http_header_data = LWS_DEF_HEADER_LEN;
490 if (info->max_http_header_pool)
491 context->max_http_header_pool = info->max_http_header_pool;
493 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
496 * Allocate the per-thread storage for scratchpad buffers,
497 * and header data pool
499 for (n = 0; n < context->count_threads; n++) {
500 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
501 if (!context->pt[n].serv_buf) {
506 context->pt[n].context = context;
507 context->pt[n].tid = n;
508 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
509 context->max_http_header_pool);
510 if (!context->pt[n].http_header_data)
513 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
514 context->max_http_header_pool);
515 for (m = 0; m < context->max_http_header_pool; m++)
516 context->pt[n].ah_pool[m].data =
517 (char *)context->pt[n].http_header_data +
518 (m * context->max_http_header_data);
519 if (!context->pt[n].ah_pool)
522 lws_pt_mutex_init(&context->pt[n]);
525 if (info->fd_limit_per_thread)
526 context->fd_limit_per_thread = info->fd_limit_per_thread;
528 context->fd_limit_per_thread = context->max_fds /
529 context->count_threads;
531 lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
532 context->fd_limit_per_thread);
534 memset(&wsi, 0, sizeof(wsi));
535 wsi.context = context;
537 if (!info->ka_interval && info->ka_time > 0) {
538 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
543 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
544 * enable libev mediated SIGINT handling with a default handler of
545 * lws_sigint_cb. The handler can be overridden or disabled
546 * by invoking lws_sigint_cfg after creating the context, but
547 * before invoking lws_initloop:
549 context->use_ev_sigint = 1;
550 context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
551 #endif /* LWS_USE_LIBEV */
553 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
554 * enable libev mediated SIGINT handling with a default handler of
555 * lws_sigint_cb. The handler can be overridden or disabled
556 * by invoking lws_sigint_cfg after creating the context, but
557 * before invoking lws_initloop:
559 context->use_ev_sigint = 1;
560 context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
563 lwsl_info(" mem: context: %5u bytes (%d ctx + (%d thr x %d))\n",
564 sizeof(struct lws_context) +
565 (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
566 sizeof(struct lws_context),
567 context->count_threads,
568 LWS_MAX_SOCKET_IO_BUF);
570 lwsl_info(" mem: http hdr rsvd: %5u bytes (%u thr x (%u + %u) x %u))\n",
571 (context->max_http_header_data +
572 sizeof(struct allocated_headers)) *
573 context->max_http_header_pool * context->count_threads,
574 context->count_threads,
575 context->max_http_header_data,
576 sizeof(struct allocated_headers),
577 context->max_http_header_pool);
578 n = sizeof(struct lws_pollfd) * context->count_threads *
579 context->fd_limit_per_thread;
580 context->pt[0].fds = lws_zalloc(n);
581 if (context->pt[0].fds == NULL) {
582 lwsl_err("OOM allocating %d fds\n", context->max_fds);
585 lwsl_info(" mem: pollfd map: %5u\n", n);
588 /* each thread serves his own chunk of fds */
589 for (n = 1; n < (int)info->count_threads; n++)
590 context->pt[n].fds = context->pt[n - 1].fds +
591 context->fd_limit_per_thread;
594 if (lws_plat_init(context, info))
597 lws_context_init_ssl_library(info);
599 context->user_space = info->user;
602 * if he's not saying he'll make his own vhosts later then act
603 * compatibly and make a default vhost using the data in the info
605 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
606 if (!lws_create_vhost(context, info, NULL)) {
607 lwsl_err("Failed to create default vhost\n");
611 lws_context_init_extensions(info, context);
613 lwsl_notice(" mem: per-conn: %5u bytes + protocol rx buf\n",
616 strcpy(context->canonical_hostname, "unknown");
617 lws_server_get_canonical_hostname(context, info);
619 context->uid = info->uid;
620 context->gid = info->gid;
623 * drop any root privs for this process
624 * to listen on port < 1023 we would have needed root, but now we are
625 * listening, we don't want the power for anything else
627 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
628 lws_plat_drop_app_privileges(info);
631 * give all extensions a chance to create any per-context
632 * allocations they need
634 if (info->port != CONTEXT_PORT_NO_LISTEN) {
635 if (lws_ext_cb_all_exts(context, NULL,
636 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
639 if (lws_ext_cb_all_exts(context, NULL,
640 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
646 lws_context_destroy(context);
651 * lws_context_destroy() - Destroy the websocket context
652 * @context: Websocket context
654 * This function closes any active connections and then frees the
655 * context. After calling this, any further use of the context is
659 lws_context_destroy(struct lws_context *context)
661 const struct lws_protocols *protocol = NULL;
662 struct lws_context_per_thread *pt;
663 struct lws_vhost *vh, *vh1;
667 lwsl_notice("%s\n", __func__);
672 m = context->count_threads;
673 context->being_destroyed = 1;
675 memset(&wsi, 0, sizeof(wsi));
676 wsi.context = context;
679 if (context->worst_latency_info[0])
680 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
684 pt = &context->pt[m];
686 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
687 struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
691 lws_close_free_wsi(wsi,
692 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
693 /* no protocol close */);
698 * give all extensions a chance to clean up any per-context
699 * allocations they might have made
702 n = lws_ext_cb_all_exts(context, NULL,
703 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
705 n = lws_ext_cb_all_exts(context, NULL,
706 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
709 * inform all the protocols that they are done and will have no more
712 * We can't free things until after the event loop shuts down.
714 vh = context->vhost_list;
717 protocol = vh->protocols;
720 while (n < vh->count_protocols) {
721 wsi.protocol = protocol;
722 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
732 for (n = 0; n < context->count_threads; n++) {
733 pt = &context->pt[n];
735 lws_libev_destroyloop(context, n);
736 lws_libuv_destroyloop(context, n);
738 lws_free_set_NULL(context->pt[n].serv_buf);
740 lws_free(pt->ah_pool);
741 if (pt->http_header_data)
742 lws_free(pt->http_header_data);
744 lws_plat_context_early_destroy(context);
745 lws_ssl_context_destroy(context);
747 if (context->pt[0].fds)
748 lws_free_set_NULL(context->pt[0].fds);
750 /* free all the vhost allocations */
752 vh = context->vhost_list;
754 protocol = vh->protocols;
757 while (n < vh->count_protocols) {
758 if (vh->protocol_vh_privs &&
759 vh->protocol_vh_privs[n]) {
760 lws_free(vh->protocol_vh_privs[n]);
761 vh->protocol_vh_privs[n] = NULL;
767 if (vh->protocol_vh_privs)
768 lws_free(vh->protocol_vh_privs);
769 lws_ssl_SSL_CTX_destroy(vh);
770 #ifdef LWS_WITH_PLUGINS
771 if (context->plugin_list)
772 lws_free((void *)vh->protocols);
773 #ifndef LWS_NO_EXTENSIONS
774 if (context->plugin_extension_count)
775 lws_free((void *)vh->extensions);
778 vh1 = vh->vhost_next;
783 lws_plat_context_late_destroy(context);