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,
57 struct lws_http_mount *m;
59 unsigned long l = (unsigned long)store;
66 m = (struct lws_http_mount *)store;
70 m->mountpoint = mountpoint;
71 m->mountpoint_len = (unsigned char)strlen(mountpoint);
76 for (n = 0; n < ARRAY_SIZE(mount_protocols); n++)
77 if (!strncmp(origin, mount_protocols[n],
78 strlen(mount_protocols[n]))) {
79 m->origin_protocol = n;
80 m->origin = origin + strlen(mount_protocols[n]);
84 if (n == ARRAY_SIZE(mount_protocols)) {
85 lwsl_err("unsupported protocol://\n");
86 return 0; /* ie, fail */
89 return ((char *)store + sizeof(*m)) - (char *)orig;
93 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
98 /* allocate the vh priv array only on demand */
99 if (!vhost->protocol_vh_privs) {
100 vhost->protocol_vh_privs = (void **)lws_zalloc(
101 vhost->count_protocols * sizeof(void *));
102 if (!vhost->protocol_vh_privs)
106 while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
109 if (n == vhost->count_protocols)
112 vhost->protocol_vh_privs[n] = lws_zalloc(size);
113 return vhost->protocol_vh_privs[n];
117 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot)
121 if (!vhost->protocol_vh_privs)
124 while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
127 if (n == vhost->count_protocols) {
128 lwsl_err("%s: unknown protocol %p\n", __func__, prot);
132 return vhost->protocol_vh_privs[n];
135 static struct lws_protocol_vhost_options *
136 lws_vhost_protocol_options(struct lws_vhost *vh, const char *name)
138 struct lws_protocol_vhost_options *pvo = vh->pvo;
141 // lwsl_notice("%s: '%s' '%s'\n", __func__, pvo->name, name);
142 if (!strcmp(pvo->name, name))
151 lws_protocol_init(struct lws_context *context)
153 struct lws_vhost *vh = context->vhost_list;
154 struct lws_protocol_vhost_options *pvo;
158 memset(&wsi, 0, sizeof(wsi));
159 wsi.context = context;
164 /* initialize supported protocols on this vhost */
166 for (n = 0; n < vh->count_protocols; n++) {
167 wsi.protocol = &vh->protocols[n];
169 pvo = lws_vhost_protocol_options(vh,
170 vh->protocols[n].name);
173 * linked list of options specific to
179 * inform all the protocols that they are doing their one-time
180 * initialization if they want to.
182 * NOTE the wsi is all zeros except for the context, vh and
183 * protocol ptrs so lws_get_context(wsi) etc can work
185 vh->protocols[n].callback(&wsi,
186 LWS_CALLBACK_PROTOCOL_INIT, NULL, pvo, 0);
192 context->protocol_init_done = 1;
197 LWS_VISIBLE struct lws_vhost *
198 lws_create_vhost(struct lws_context *context,
199 struct lws_context_creation_info *info,
200 struct lws_http_mount *mounts)
202 struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
203 **vh1 = &context->vhost_list;
204 #ifdef LWS_WITH_PLUGINS
205 struct lws_plugin *plugin = context->plugin_list;
206 struct lws_protocols *lwsp;
207 int m, n, f = !info->pvo;
214 vh->context = context;
215 if (!info->vhost_name)
216 vh->name = "default";
218 vh->name = info->vhost_name;
220 vh->iface = info->iface;
221 for (vh->count_protocols = 0;
222 info->protocols[vh->count_protocols].callback;
223 vh->count_protocols++)
228 #ifdef LWS_WITH_PLUGINS
231 * give the vhost a unified list of protocols including the
232 * ones that came from plugins
234 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
235 (vh->count_protocols +
236 context->plugin_protocol_count + 1));
240 m = vh->count_protocols;
241 memcpy(lwsp, info->protocols,
242 sizeof(struct lws_protocols) * m);
244 /* for compatibility, all protocols enabled on vhost if only
245 * the default vhost exists. Otherwise only vhosts who ask
246 * for a protocol get it enabled.
249 if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
253 for (n = 0; n < plugin->caps.count_protocols; n++) {
255 * for compatibility's sake, no pvo implies
256 * allow all protocols
258 if (f || lws_vhost_protocol_options(vh,
259 plugin->caps.protocols[n].name)) {
261 &plugin->caps.protocols[n],
262 sizeof(struct lws_protocols));
264 vh->count_protocols++;
267 plugin = plugin->list;
269 vh->protocols = lwsp;
272 vh->protocols = info->protocols;
274 vh->mount_list = mounts;
276 lwsl_notice("Creating Vhost '%s' port %d, %d protocols\n",
277 vh->name, info->port, vh->count_protocols);
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);
307 memcpy((struct lws_extension *)&vh->extensions[m], plugin->caps.extensions,
308 sizeof(struct lws_extension) *
309 plugin->caps.count_extensions);
310 m += plugin->caps.count_extensions;
311 plugin = plugin->list;
315 vh->extensions = info->extensions;
318 vh->listen_port = info->port;
319 vh->http_proxy_port = 0;
320 vh->http_proxy_address[0] = '\0';
322 /* either use proxy from info, or try get it from env var */
324 if (info->http_proxy_address) {
325 /* override for backwards compatibility */
326 if (info->http_proxy_port)
327 vh->http_proxy_port = info->http_proxy_port;
328 lws_set_proxy(vh, info->http_proxy_address);
330 #ifdef LWS_HAVE_GETENV
331 p = getenv("http_proxy");
333 lws_set_proxy(vh, p);
337 vh->ka_time = info->ka_time;
338 vh->ka_interval = info->ka_interval;
339 vh->ka_probes = info->ka_probes;
341 if (lws_context_init_server_ssl(info, vh))
344 if (lws_context_init_client_ssl(info, vh))
347 if (lws_context_init_server(info, vh))
355 vh1 = &(*vh1)->vhost_next;
367 * lws_create_context() - Create the websocket handler
368 * @info: pointer to struct with parameters
370 * This function creates the listening socket (if serving) and takes care
371 * of all initialization in one step.
373 * After initialization, it returns a struct lws_context * that
374 * represents this server. After calling, user code needs to take care
375 * of calling lws_service() with the context pointer to get the
376 * server's sockets serviced. This must be done in the same process
377 * context as the initialization call.
379 * The protocol callback functions are called for a handful of events
380 * including http requests coming in, websocket connections becoming
381 * established, and data arriving; it's also called periodically to allow
382 * async transmission.
384 * HTTP requests are sent always to the FIRST protocol in @protocol, since
385 * at that time websocket protocol has not been negotiated. Other
386 * protocols after the first one never see any HTTP callack activity.
388 * The server created is a simple http server by default; part of the
389 * websocket standard is upgrading this http connection to a websocket one.
391 * This allows the same server to provide files like scripts and favicon /
392 * images or whatever over http and dynamic data over websockets all in
393 * one place; they're all handled in the user callback.
395 LWS_VISIBLE struct lws_context *
396 lws_create_context(struct lws_context_creation_info *info)
398 struct lws_context *context = NULL;
400 #ifndef LWS_NO_DAEMONIZE
401 int pid_daemon = get_daemonize_pid();
404 #if defined(__ANDROID__)
409 lwsl_notice("Initial logging level %d\n", log_level);
410 lwsl_notice("Libwebsockets version: %s\n", library_version);
413 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
414 lwsl_notice("IPV6 compiled in and enabled\n");
416 lwsl_notice("IPV6 compiled in but disabled\n");
418 lwsl_notice("IPV6 not compiled in\n");
420 lws_feature_status_libev(info);
421 lws_feature_status_libuv(info);
423 lwsl_info(" LWS_DEF_HEADER_LEN : %u\n", LWS_DEF_HEADER_LEN);
424 lwsl_info(" LWS_MAX_PROTOCOLS : %u\n", LWS_MAX_PROTOCOLS);
425 lwsl_info(" LWS_MAX_SMP : %u\n", LWS_MAX_SMP);
426 lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
427 lwsl_info(" sizeof (*info) : %u\n", sizeof(*info));
429 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
431 if (lws_plat_context_early_init())
434 context = lws_zalloc(sizeof(struct lws_context));
436 lwsl_err("No memory for websocket context\n");
439 #ifndef LWS_NO_DAEMONIZE
441 context->started_with_parent = pid_daemon;
442 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
445 #if defined(__ANDROID__)
446 n = getrlimit ( RLIMIT_NOFILE,&rt);
448 lwsl_err("Get RLIMIT_NOFILE failed!\n");
451 context->max_fds = rt.rlim_cur;
453 context->max_fds = getdtablesize();
456 if (info->count_threads)
457 context->count_threads = info->count_threads;
459 context->count_threads = 1;
461 if (context->count_threads > LWS_MAX_SMP)
462 context->count_threads = LWS_MAX_SMP;
464 context->token_limits = info->token_limits;
466 context->options = info->options;
468 if (info->timeout_secs)
469 context->timeout_secs = info->timeout_secs;
471 context->timeout_secs = AWAITING_TIMEOUT;
473 lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
475 if (info->max_http_header_data)
476 context->max_http_header_data = info->max_http_header_data;
478 context->max_http_header_data = LWS_DEF_HEADER_LEN;
479 if (info->max_http_header_pool)
480 context->max_http_header_pool = info->max_http_header_pool;
482 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
485 * Allocate the per-thread storage for scratchpad buffers,
486 * and header data pool
488 for (n = 0; n < context->count_threads; n++) {
489 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
490 if (!context->pt[n].serv_buf) {
495 context->pt[n].context = context;
496 context->pt[n].tid = n;
497 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
498 context->max_http_header_pool);
499 if (!context->pt[n].http_header_data)
502 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
503 context->max_http_header_pool);
504 for (m = 0; m < context->max_http_header_pool; m++)
505 context->pt[n].ah_pool[m].data =
506 (char *)context->pt[n].http_header_data +
507 (m * context->max_http_header_data);
508 if (!context->pt[n].ah_pool)
511 lws_pt_mutex_init(&context->pt[n]);
514 if (info->fd_limit_per_thread)
515 context->fd_limit_per_thread = info->fd_limit_per_thread;
517 context->fd_limit_per_thread = context->max_fds /
518 context->count_threads;
520 lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
521 context->fd_limit_per_thread);
523 memset(&wsi, 0, sizeof(wsi));
524 wsi.context = context;
526 if (!info->ka_interval && info->ka_time > 0) {
527 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
532 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
533 * enable libev mediated SIGINT handling with a default handler of
534 * lws_sigint_cb. The handler can be overridden or disabled
535 * by invoking lws_sigint_cfg after creating the context, but
536 * before invoking lws_initloop:
538 context->use_ev_sigint = 1;
539 context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
540 #endif /* LWS_USE_LIBEV */
542 /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
543 * enable libev mediated SIGINT handling with a default handler of
544 * lws_sigint_cb. The handler can be overridden or disabled
545 * by invoking lws_sigint_cfg after creating the context, but
546 * before invoking lws_initloop:
548 context->use_ev_sigint = 1;
549 context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
552 lwsl_info(" mem: context: %5u bytes (%d ctx + (%d thr x %d))\n",
553 sizeof(struct lws_context) +
554 (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
555 sizeof(struct lws_context),
556 context->count_threads,
557 LWS_MAX_SOCKET_IO_BUF);
559 lwsl_info(" mem: http hdr rsvd: %5u bytes (%u thr x (%u + %u) x %u))\n",
560 (context->max_http_header_data +
561 sizeof(struct allocated_headers)) *
562 context->max_http_header_pool * context->count_threads,
563 context->count_threads,
564 context->max_http_header_data,
565 sizeof(struct allocated_headers),
566 context->max_http_header_pool);
567 n = sizeof(struct lws_pollfd) * context->count_threads *
568 context->fd_limit_per_thread;
569 context->pt[0].fds = lws_zalloc(n);
570 if (context->pt[0].fds == NULL) {
571 lwsl_err("OOM allocating %d fds\n", context->max_fds);
574 lwsl_info(" mem: pollfd map: %5u\n", n);
577 /* each thread serves his own chunk of fds */
578 for (n = 1; n < (int)info->count_threads; n++)
579 context->pt[n].fds = context->pt[n - 1].fds +
580 context->fd_limit_per_thread;
583 if (lws_plat_init(context, info))
586 lws_context_init_ssl_library(info);
589 * if he's not saying he'll make his own vhosts later then act
590 * compatibly and make a default vhost using the data in the info
592 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
593 if (!lws_create_vhost(context, info, NULL)) {
594 lwsl_err("Failed to create default vhost\n");
598 lws_context_init_extensions(info, context);
600 context->user_space = info->user;
602 lwsl_notice(" mem: per-conn: %5u bytes + protocol rx buf\n",
605 strcpy(context->canonical_hostname, "unknown");
606 lws_server_get_canonical_hostname(context, info);
608 context->uid = info->uid;
609 context->gid = info->gid;
612 * drop any root privs for this process
613 * to listen on port < 1023 we would have needed root, but now we are
614 * listening, we don't want the power for anything else
616 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
617 lws_plat_drop_app_privileges(info);
620 * give all extensions a chance to create any per-context
621 * allocations they need
623 if (info->port != CONTEXT_PORT_NO_LISTEN) {
624 if (lws_ext_cb_all_exts(context, NULL,
625 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
628 if (lws_ext_cb_all_exts(context, NULL,
629 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
635 lws_context_destroy(context);
640 * lws_context_destroy() - Destroy the websocket context
641 * @context: Websocket context
643 * This function closes any active connections and then frees the
644 * context. After calling this, any further use of the context is
648 lws_context_destroy(struct lws_context *context)
650 const struct lws_protocols *protocol = NULL;
651 struct lws_context_per_thread *pt;
652 struct lws_vhost *vh, *vh1;
656 lwsl_notice("%s\n", __func__);
661 m = context->count_threads;
662 context->being_destroyed = 1;
664 memset(&wsi, 0, sizeof(wsi));
665 wsi.context = context;
668 if (context->worst_latency_info[0])
669 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
673 pt = &context->pt[m];
675 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
676 struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
680 lws_close_free_wsi(wsi,
681 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
682 /* no protocol close */);
687 * give all extensions a chance to clean up any per-context
688 * allocations they might have made
691 n = lws_ext_cb_all_exts(context, NULL,
692 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
694 n = lws_ext_cb_all_exts(context, NULL,
695 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
698 * inform all the protocols that they are done and will have no more
701 * We can't free things until after the event loop shuts down.
703 vh = context->vhost_list;
706 protocol = vh->protocols;
709 while (n < vh->count_protocols) {
710 wsi.protocol = protocol;
711 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
721 for (n = 0; n < context->count_threads; n++) {
722 pt = &context->pt[n];
724 lws_libev_destroyloop(context, n);
725 lws_libuv_destroyloop(context, n);
727 lws_free_set_NULL(context->pt[n].serv_buf);
729 lws_free(pt->ah_pool);
730 if (pt->http_header_data)
731 lws_free(pt->http_header_data);
733 lws_plat_context_early_destroy(context);
734 lws_ssl_context_destroy(context);
736 if (context->pt[0].fds)
737 lws_free_set_NULL(context->pt[0].fds);
739 /* free all the vhost allocations */
741 vh = context->vhost_list;
743 protocol = vh->protocols;
746 while (n < vh->count_protocols) {
747 if (vh->protocol_vh_privs &&
748 vh->protocol_vh_privs[n]) {
749 lws_free(vh->protocol_vh_privs[n]);
750 vh->protocol_vh_privs[n] = NULL;
756 if (vh->protocol_vh_privs)
757 lws_free(vh->protocol_vh_privs);
758 lws_ssl_SSL_CTX_destroy(vh);
759 #ifdef LWS_WITH_PLUGINS
760 if (context->plugin_list)
761 lws_free((void *)vh->protocols);
762 #ifndef LWS_NO_EXTENSIONS
763 if (context->plugin_extension_count)
764 lws_free((void *)vh->extensions);
767 vh1 = vh->vhost_next;
772 lws_plat_context_late_destroy(context);