esp8266 initial support
[platform/upstream/libwebsockets.git] / lib / context.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2015 Andy Green <andy@warmcat.com>
5  *
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.
10  *
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.
15  *
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,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23
24 #ifndef LWS_BUILD_HASH
25 #define LWS_BUILD_HASH "unknown-build-hash"
26 #endif
27
28 static const char *library_version = LWS_LIBRARY_VERSION " " LWS_BUILD_HASH;
29
30 /**
31  * lws_get_library_version: get version and git hash library built from
32  *
33  *      returns a const char * to a string like "1.1 178d78c"
34  *      representing the library version followed by the git head hash it
35  *      was built from
36  */
37 LWS_VISIBLE const char *
38 lws_get_library_version(void)
39 {
40         return library_version;
41 }
42
43 static const char * const mount_protocols[] = {
44         "http://",
45         "https://",
46         "file://",
47         "cgi://",
48         ">http://",
49         ">https://",
50         "callback://"
51 };
52
53 LWS_VISIBLE void *
54 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
55                             int size)
56 {
57         int n = 0;
58
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)
64                         return NULL;
65         }
66
67         while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
68                 n++;
69
70         if (n == vhost->count_protocols) {
71                 n = 0;
72                 while (n < vhost->count_protocols &&
73                        strcmp(vhost->protocols[n].name, prot->name))
74                         n++;
75
76                 if (n == vhost->count_protocols)
77                         return NULL;
78         }
79
80         vhost->protocol_vh_privs[n] = lws_zalloc(size);
81         return vhost->protocol_vh_privs[n];
82 }
83
84 LWS_VISIBLE void *
85 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot)
86 {
87         int n = 0;
88
89         if (!vhost->protocol_vh_privs)
90                 return NULL;
91
92         while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
93                 n++;
94
95         if (n == vhost->count_protocols) {
96                 n = 0;
97                 while (n < vhost->count_protocols &&
98                        strcmp(vhost->protocols[n].name, prot->name))
99                         n++;
100
101                 if (n == vhost->count_protocols) {
102                         lwsl_err("%s: unknown protocol %p\n", __func__, prot);
103                         return NULL;
104                 }
105         }
106
107         return vhost->protocol_vh_privs[n];
108 }
109
110 static const struct lws_protocol_vhost_options *
111 lws_vhost_protocol_options(struct lws_vhost *vh, const char *name)
112 {
113         const struct lws_protocol_vhost_options *pvo = vh->pvo;
114
115         while (pvo) {
116                 // lwsl_notice("%s: '%s' '%s'\n", __func__, pvo->name, name);
117                 if (!strcmp(pvo->name, name))
118                         return pvo;
119                 pvo = pvo->next;
120         }
121
122         return NULL;
123 }
124
125 int
126 lws_protocol_init(struct lws_context *context)
127 {
128         struct lws_vhost *vh = context->vhost_list;
129         const struct lws_protocol_vhost_options *pvo, *pvo1;
130         struct lws wsi;
131         int n;
132
133         memset(&wsi, 0, sizeof(wsi));
134         wsi.context = context;
135
136         lwsl_notice("%s\n", __func__);
137
138         while (vh) {
139                 wsi.vhost = vh;
140
141                 /* initialize supported protocols on this vhost */
142
143                 for (n = 0; n < vh->count_protocols; n++) {
144                         wsi.protocol = &vh->protocols[n];
145
146                         pvo = lws_vhost_protocol_options(vh,
147                                                          vh->protocols[n].name);
148                         if (pvo) {
149                                 /*
150                                  * linked list of options specific to
151                                  * vh + protocol
152                                  */
153                                 pvo1 = pvo;
154                                 pvo = pvo1->options;
155
156                                 while (pvo) {
157                                         lwsl_notice("    vh %s prot %s opt %s\n",
158                                                         vh->name,
159                                                         vh->protocols[n].name,
160                                                         pvo->name);
161
162                                         if (!strcmp(pvo->name, "default")) {
163                                                 lwsl_notice("Setting default "
164                                                    "protocol for vh %s to %s\n",
165                                                    vh->name,
166                                                    vh->protocols[n].name);
167                                                 vh->default_protocol_index = n;
168                                         }
169                                         pvo = pvo->next;
170                                 }
171
172                                 pvo = pvo1->options;
173                         }
174
175                         /*
176                          * inform all the protocols that they are doing their one-time
177                          * initialization if they want to.
178                          *
179                          * NOTE the wsi is all zeros except for the context, vh and
180                          * protocol ptrs so lws_get_context(wsi) etc can work
181                          */
182                         if (vh->protocols[n].callback(&wsi,
183                                 LWS_CALLBACK_PROTOCOL_INIT, NULL,
184                                 (void *)pvo, 0))
185                                 return 1;
186                 }
187
188                 vh = vh->vhost_next;
189         }
190
191         context->protocol_init_done = 1;
192         lws_finalize_startup(context);
193
194         return 0;
195 }
196
197 LWS_VISIBLE int
198 lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
199                     void *user, void *in, size_t len)
200 {
201 #ifdef LWS_WITH_CGI
202         struct lws_cgi_args *args;
203         char buf[128];
204         int n;
205 #endif
206
207         switch (reason) {
208         case LWS_CALLBACK_HTTP:
209 #ifndef LWS_NO_SERVER
210                 if (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL))
211                         return -1;
212
213                 if (lws_http_transaction_completed(wsi))
214 #endif
215                         return -1;
216                 break;
217
218         case LWS_CALLBACK_HTTP_WRITEABLE:
219 #ifdef LWS_WITH_CGI
220                 if (wsi->reason_bf & 1) {
221                         if (lws_cgi_write_split_stdout_headers(wsi) < 0)
222                                 return -1;
223
224                         wsi->reason_bf &= ~1;
225                         break;
226                 }
227 #endif
228
229                 break;
230
231 #ifdef LWS_WITH_CGI
232         /* CGI IO events (POLLIN/OUT) appear here, our default policy is:
233          *
234          *  - POST data goes on subprocess stdin
235          *  - subprocess stdout goes on http via writeable callback
236          *  - subprocess stderr goes to the logs
237          */
238         case LWS_CALLBACK_CGI:
239                 args = (struct lws_cgi_args *)in;
240                 switch (args->ch) { /* which of stdin/out/err ? */
241                 case LWS_STDIN:
242                         /* TBD stdin rx flow control */
243                         break;
244                 case LWS_STDOUT:
245                         wsi->reason_bf |= 1;
246                         /* when writing to MASTER would not block */
247                         lws_callback_on_writable(wsi);
248                         break;
249                 case LWS_STDERR:
250                         n = read(lws_get_socket_fd(args->stdwsi[LWS_STDERR]),
251                                                    buf, sizeof(buf) - 1);
252                         if (n > 0) {
253                                 if (buf[n - 1] != '\n')
254                                         buf[n++] = '\n';
255                                 buf[n] = '\0';
256                                 lwsl_notice("CGI-stderr: %s\n", buf);
257                         }
258                         break;
259                 }
260                 break;
261
262         case LWS_CALLBACK_CGI_TERMINATED:
263                 return -1;
264
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);
270                 if (n < args->len)
271                         lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: "
272                                     "sent %d only %d went", n, args->len);
273                 return n;
274 #endif
275         default:
276                 break;
277         }
278
279         return 0;
280 }
281
282 /* list of supported protocols and callbacks */
283
284 static const struct lws_protocols protocols_dummy[] = {
285         /* first protocol must always be HTTP handler */
286
287         {
288                 "http-only",            /* name */
289                 lws_callback_http_dummy,                /* callback */
290                 0,      /* per_session_data_size */
291                 0,                      /* max frame size / rx buffer */
292         },
293         /*
294          * the other protocols are provided by lws plugins
295          */
296         { NULL, NULL, 0, 0 } /* terminator */
297 };
298
299 LWS_VISIBLE struct lws_vhost *
300 lws_create_vhost(struct lws_context *context,
301                  struct lws_context_creation_info *info)
302 {
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;
311 #endif
312 #ifdef LWS_HAVE_GETENV
313         char *p;
314 #endif
315         int n;
316
317         if (!vh)
318                 return NULL;
319
320         if (!info->protocols)
321                 info->protocols = &protocols_dummy[0];
322
323         vh->context = context;
324         if (!info->vhost_name)
325                 vh->name = "default";
326         else
327                 vh->name = info->vhost_name;
328
329         vh->iface = info->iface;
330         for (vh->count_protocols = 0;
331              info->protocols[vh->count_protocols].callback;
332              vh->count_protocols++)
333                 ;
334
335         vh->options = info->options;
336         vh->pvo = info->pvo;
337         if (info->keepalive_timeout)
338                 vh->keepalive_timeout = info->keepalive_timeout;
339         else
340                 vh->keepalive_timeout = 5;
341
342 #ifdef LWS_WITH_PLUGINS
343         if (plugin) {
344                 /*
345                  * give the vhost a unified list of protocols including the
346                  * ones that came from plugins
347                  */
348                 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
349                                            (vh->count_protocols +
350                                            context->plugin_protocol_count + 1));
351                 if (!lwsp)
352                         return NULL;
353
354                 m = vh->count_protocols;
355                 memcpy(lwsp, info->protocols,
356                        sizeof(struct lws_protocols) * m);
357
358                 /* for compatibility, all protocols enabled on vhost if only
359                  * the default vhost exists.  Otherwise only vhosts who ask
360                  * for a protocol get it enabled.
361                  */
362
363                 if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
364                         f = 0;
365
366                 while (plugin) {
367                         for (n = 0; n < plugin->caps.count_protocols; n++) {
368                                 /*
369                                  * for compatibility's sake, no pvo implies
370                                  * allow all protocols
371                                  */
372                                 if (f || lws_vhost_protocol_options(vh,
373                                     plugin->caps.protocols[n].name)) {
374                                         memcpy(&lwsp[m],
375                                                &plugin->caps.protocols[n],
376                                                sizeof(struct lws_protocols));
377                                         m++;
378                                         vh->count_protocols++;
379                                 }
380                         }
381                         plugin = plugin->list;
382                 }
383                 vh->protocols = lwsp;
384         } else
385 #endif
386                 vh->protocols = info->protocols;
387
388         vh->same_vh_protocol_list = (struct lws **)
389                         lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
390
391         vh->mount_list = info->mounts;
392
393 #ifdef LWS_USE_UNIX_SOCK
394         if (LWS_UNIX_SOCK_ENABLED(context)) {
395                 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
396                                 vh->name, info->iface, vh->count_protocols);
397         } else
398 #endif
399         lwsl_notice("Creating Vhost '%s' port %d, %d protocols, IPv6 %s\n",
400                         vh->name, info->port, vh->count_protocols, LWS_IPV6_ENABLED(vh) ? "on" : "off");
401
402         mounts = info->mounts;
403         while (mounts) {
404                 lwsl_notice("   mounting %s%s to %s\n",
405                                 mount_protocols[mounts->origin_protocol],
406                                 mounts->origin, mounts->mountpoint);
407
408                 /* convert interpreter protocol names to pointers */
409                 pvo = mounts->interpret;
410                 while (pvo) {
411                         for (n = 0; n < vh->count_protocols; n++)
412                                 if (!strcmp(pvo->value, vh->protocols[n].name)) {
413                                         ((struct lws_protocol_vhost_options *)pvo)->value =
414                                                         (const char *)(long)n;
415                                         break;
416                                 }
417                         if (n == vh->count_protocols)
418                                 lwsl_err("ignoring unknown interpret protocol %s\n", pvo->value);
419                         pvo = pvo->next;
420                 }
421
422                 mounts = mounts->mount_next;
423         }
424
425 #ifndef LWS_NO_EXTENSIONS
426 #ifdef LWS_WITH_PLUGINS
427         if (context->plugin_extension_count) {
428
429                 m = 0;
430                 while (info->extensions && info->extensions[m].callback)
431                         m++;
432
433                 /*
434                  * give the vhost a unified list of extensions including the
435                  * ones that came from plugins
436                  */
437                 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
438                                            (m +
439                                            context->plugin_extension_count + 1));
440                 if (!vh->extensions)
441                         return NULL;
442
443                 memcpy((struct lws_extension *)vh->extensions, info->extensions,
444                        sizeof(struct lws_extension) * m);
445                 plugin = context->plugin_list;
446                 while (plugin) {
447                         memcpy((struct lws_extension *)&vh->extensions[m],
448                                 plugin->caps.extensions,
449                                sizeof(struct lws_extension) *
450                                plugin->caps.count_extensions);
451                         m += plugin->caps.count_extensions;
452                         plugin = plugin->list;
453                 }
454         } else
455 #endif
456                 vh->extensions = info->extensions;
457 #endif
458
459         vh->listen_port = info->port;
460 #if !defined(LWS_WITH_ESP8266)
461         vh->http_proxy_port = 0;
462         vh->http_proxy_address[0] = '\0';
463
464         /* either use proxy from info, or try get it from env var */
465
466         if (info->http_proxy_address) {
467                 /* override for backwards compatibility */
468                 if (info->http_proxy_port)
469                         vh->http_proxy_port = info->http_proxy_port;
470                 lws_set_proxy(vh, info->http_proxy_address);
471         } else {
472 #ifdef LWS_HAVE_GETENV
473                 p = getenv("http_proxy");
474                 if (p)
475                         lws_set_proxy(vh, p);
476 #endif
477         }
478 #endif
479         vh->ka_time = info->ka_time;
480         vh->ka_interval = info->ka_interval;
481         vh->ka_probes = info->ka_probes;
482
483         if (vh->options & LWS_SERVER_OPTION_STS)
484                 lwsl_notice("   STS enabled\n");
485
486 #ifdef LWS_WITH_ACCESS_LOG
487         if (info->log_filepath) {
488                 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
489                 if (vh->log_fd == (int)LWS_INVALID_FILE) {
490                         lwsl_err("unable to open log filepath %s\n",
491                                  info->log_filepath);
492                         goto bail;
493                 }
494 #ifndef WIN32
495                 if (context->uid != -1)
496                         if (chown(info->log_filepath, context->uid,
497                                   context->gid) == -1)
498                                 lwsl_err("unable to chown log file %s\n",
499                                                 info->log_filepath);
500 #endif
501         } else
502                 vh->log_fd = (int)LWS_INVALID_FILE;
503 #endif
504
505         if (lws_context_init_server_ssl(info, vh))
506                 goto bail;
507
508         if (lws_context_init_client_ssl(info, vh))
509                 goto bail;
510
511         if (lws_context_init_server(info, vh))
512                 goto bail;
513
514         while (1) {
515                 if (!(*vh1)) {
516                         *vh1 = vh;
517                         break;
518                 }
519                 vh1 = &(*vh1)->vhost_next;
520         };
521
522         return vh;
523
524 bail:
525         lws_free(vh);
526
527         return NULL;
528 }
529
530 LWS_VISIBLE int
531 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
532                           struct lws_vhost *vhost)
533 {
534         struct lws_context_creation_info i;
535
536         memcpy(&i, info, sizeof(i));
537         i.port = CONTEXT_PORT_NO_LISTEN;
538
539         return lws_context_init_client_ssl(&i, vhost);
540 }
541         struct lws wsi;
542
543 LWS_VISIBLE struct lws_context *
544 lws_create_context(struct lws_context_creation_info *info)
545 {
546         struct lws_context *context = NULL;
547 #ifndef LWS_NO_DAEMONIZE
548         int pid_daemon = get_daemonize_pid();
549 #endif
550         int n, m;
551 #if defined(__ANDROID__)
552         struct rlimit rt;
553 #endif
554
555         lwsl_notice("Initial logging level %d\n", log_level);
556         lwsl_notice("Libwebsockets version: %s\n", library_version);
557 #if LWS_POSIX
558 #ifdef LWS_USE_IPV6
559         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
560                 lwsl_notice("IPV6 compiled in and enabled\n");
561         else
562                 lwsl_notice("IPV6 compiled in but disabled\n");
563 #else
564         lwsl_notice("IPV6 not compiled in\n");
565 #endif
566         lws_feature_status_libev(info);
567         lws_feature_status_libuv(info);
568 #endif
569         lwsl_info(" LWS_DEF_HEADER_LEN    : %u\n", LWS_DEF_HEADER_LEN);
570         lwsl_info(" LWS_MAX_PROTOCOLS     : %u\n", LWS_MAX_PROTOCOLS);
571         lwsl_info(" LWS_MAX_SMP           : %u\n", LWS_MAX_SMP);
572         lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
573         lwsl_info(" sizeof (*info)        : %u\n", sizeof(*info));
574 #if LWS_POSIX
575         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
576 #endif
577         if (lws_plat_context_early_init())
578                 return NULL;
579
580         context = lws_zalloc(sizeof(struct lws_context));
581         if (!context) {
582                 lwsl_err("No memory for websocket context\n");
583                 return NULL;
584         }
585         if (info->pt_serv_buf_size)
586                 context->pt_serv_buf_size = info->pt_serv_buf_size;
587         else
588                 context->pt_serv_buf_size = 4096;
589
590         context->time_up = time(NULL);
591 #ifndef LWS_NO_DAEMONIZE
592         if (pid_daemon) {
593                 context->started_with_parent = pid_daemon;
594                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
595         }
596 #endif
597 #if defined(__ANDROID__)
598                 n = getrlimit ( RLIMIT_NOFILE,&rt);
599                 if (-1 == n) {
600                         lwsl_err("Get RLIMIT_NOFILE failed!\n");
601                         return NULL;
602                 }
603                 context->max_fds = rt.rlim_cur;
604 #else
605                 context->max_fds = getdtablesize();
606 #endif
607
608         if (info->count_threads)
609                 context->count_threads = info->count_threads;
610         else
611                 context->count_threads = 1;
612
613         if (context->count_threads > LWS_MAX_SMP)
614                 context->count_threads = LWS_MAX_SMP;
615
616         context->token_limits = info->token_limits;
617
618         context->options = info->options;
619
620         if (info->timeout_secs)
621                 context->timeout_secs = info->timeout_secs;
622         else
623                 context->timeout_secs = AWAITING_TIMEOUT;
624
625         context->ws_ping_pong_interval = info->ws_ping_pong_interval;
626
627         lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
628
629         if (info->max_http_header_data)
630                 context->max_http_header_data = info->max_http_header_data;
631         else
632                 if (info->max_http_header_data2)
633                         context->max_http_header_data =
634                                         info->max_http_header_data2;
635                 else
636                         context->max_http_header_data = LWS_DEF_HEADER_LEN;
637         if (info->max_http_header_pool)
638                 context->max_http_header_pool = info->max_http_header_pool;
639         else
640                 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
641
642         /*
643          * Allocate the per-thread storage for scratchpad buffers,
644          * and header data pool
645          */
646         for (n = 0; n < context->count_threads; n++) {
647                 context->pt[n].serv_buf = lws_zalloc(context->pt_serv_buf_size);
648                 if (!context->pt[n].serv_buf) {
649                         lwsl_err("OOM\n");
650                         return NULL;
651                 }
652
653                 context->pt[n].context = context;
654                 context->pt[n].tid = n;
655                 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
656                                                        context->max_http_header_pool);
657                 if (!context->pt[n].http_header_data)
658                         goto bail;
659
660                 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
661                                               context->max_http_header_pool);
662                 for (m = 0; m < context->max_http_header_pool; m++)
663                         context->pt[n].ah_pool[m].data =
664                                 (char *)context->pt[n].http_header_data +
665                                 (m * context->max_http_header_data);
666                 if (!context->pt[n].ah_pool)
667                         goto bail;
668
669                 lws_pt_mutex_init(&context->pt[n]);
670         }
671
672         if (info->fd_limit_per_thread)
673                 context->fd_limit_per_thread = info->fd_limit_per_thread;
674         else
675                 context->fd_limit_per_thread = context->max_fds /
676                                                context->count_threads;
677
678         lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
679                     context->fd_limit_per_thread);
680
681         memset(&wsi, 0, sizeof(wsi));
682         wsi.context = context;
683
684         if (!info->ka_interval && info->ka_time > 0) {
685                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
686                 return NULL;
687         }
688
689 #ifdef LWS_USE_LIBEV
690         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
691          * enable libev mediated SIGINT handling with a default handler of
692          * lws_sigint_cb. The handler can be overridden or disabled
693          * by invoking lws_sigint_cfg after creating the context, but
694          * before invoking lws_initloop:
695          */
696         context->use_ev_sigint = 1;
697         context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
698 #endif /* LWS_USE_LIBEV */
699 #ifdef LWS_USE_LIBUV
700         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
701          * enable libev mediated SIGINT handling with a default handler of
702          * lws_sigint_cb. The handler can be overridden or disabled
703          * by invoking lws_sigint_cfg after creating the context, but
704          * before invoking lws_initloop:
705          */
706         context->use_ev_sigint = 1;
707         context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
708 #endif
709
710         lwsl_info(" mem: context:         %5u bytes (%d ctx + (%d thr x %d))\n",
711                   sizeof(struct lws_context) +
712                   (context->count_threads * context->pt_serv_buf_size),
713                   sizeof(struct lws_context),
714                   context->count_threads,
715                   context->pt_serv_buf_size);
716
717         lwsl_info(" mem: http hdr rsvd:   %5u bytes (%u thr x (%u + %u) x %u))\n",
718                     (context->max_http_header_data +
719                      sizeof(struct allocated_headers)) *
720                     context->max_http_header_pool * context->count_threads,
721                     context->count_threads,
722                     context->max_http_header_data,
723                     sizeof(struct allocated_headers),
724                     context->max_http_header_pool);
725         n = sizeof(struct lws_pollfd) * context->count_threads *
726             context->fd_limit_per_thread;
727         context->pt[0].fds = lws_zalloc(n);
728         if (context->pt[0].fds == NULL) {
729                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
730                 goto bail;
731         }
732         lwsl_info(" mem: pollfd map:      %5u\n", n);
733
734         if (info->server_string) {
735                 context->server_string = info->server_string;
736                 context->server_string_len = (short)
737                                 strlen(context->server_string);
738         } else {
739                 context->server_string = "libwebsockets";
740                 context->server_string_len = 13;
741         }
742
743 #if LWS_MAX_SMP > 1
744         /* each thread serves his own chunk of fds */
745         for (n = 1; n < (int)info->count_threads; n++)
746                 context->pt[n].fds = context->pt[n - 1].fds +
747                                      context->fd_limit_per_thread;
748 #endif
749
750         if (lws_plat_init(context, info))
751                 goto bail;
752
753         lws_context_init_ssl_library(info);
754
755         context->user_space = info->user;
756
757         /*
758          * if he's not saying he'll make his own vhosts later then act
759          * compatibly and make a default vhost using the data in the info
760          */
761         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
762                 if (!lws_create_vhost(context, info)) {
763                         lwsl_err("Failed to create default vhost\n");
764                         return NULL;
765                 }
766
767         lws_context_init_extensions(info, context);
768
769         lwsl_notice(" mem: per-conn:        %5u bytes + protocol rx buf\n",
770                     sizeof(struct lws));
771
772         strcpy(context->canonical_hostname, "unknown");
773         lws_server_get_canonical_hostname(context, info);
774
775         context->uid = info->uid;
776         context->gid = info->gid;
777
778         /*
779          * drop any root privs for this process
780          * to listen on port < 1023 we would have needed root, but now we are
781          * listening, we don't want the power for anything else
782          */
783         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
784                 lws_plat_drop_app_privileges(info);
785
786         /*
787          * give all extensions a chance to create any per-context
788          * allocations they need
789          */
790         if (info->port != CONTEXT_PORT_NO_LISTEN) {
791                 if (lws_ext_cb_all_exts(context, NULL,
792                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
793                         goto bail;
794         } else
795                 if (lws_ext_cb_all_exts(context, NULL,
796                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
797                         goto bail;
798
799         return context;
800
801 bail:
802         lws_context_destroy(context);
803         return NULL;
804 }
805
806 LWS_VISIBLE void
807 lws_context_destroy(struct lws_context *context)
808 {
809         const struct lws_protocols *protocol = NULL;
810         struct lws_context_per_thread *pt;
811         struct lws_vhost *vh = NULL, *vh1;
812         struct lws wsi;
813         int n, m;
814
815         lwsl_notice("%s\n", __func__);
816
817         if (!context)
818                 return;
819
820         m = context->count_threads;
821         context->being_destroyed = 1;
822
823         memset(&wsi, 0, sizeof(wsi));
824         wsi.context = context;
825
826 #ifdef LWS_LATENCY
827         if (context->worst_latency_info[0])
828                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
829 #endif
830
831         while (m--) {
832                 pt = &context->pt[m];
833
834                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
835                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
836                         if (!wsi)
837                                 continue;
838
839                         lws_close_free_wsi(wsi,
840                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
841                                 /* no protocol close */);
842                         n--;
843                 }
844                 lws_pt_mutex_destroy(pt);
845         }
846         /*
847          * give all extensions a chance to clean up any per-context
848          * allocations they might have made
849          */
850
851         n = lws_ext_cb_all_exts(context, NULL,
852                                 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
853
854         n = lws_ext_cb_all_exts(context, NULL,
855                                 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
856
857         /*
858          * inform all the protocols that they are done and will have no more
859          * callbacks.
860          *
861          * We can't free things until after the event loop shuts down.
862          */
863         if (context->protocol_init_done)
864                 vh = context->vhost_list;
865         while (vh) {
866                 wsi.vhost = vh;
867                 protocol = vh->protocols;
868                 if (protocol) {
869                         n = 0;
870                         while (n < vh->count_protocols) {
871                                 wsi.protocol = protocol;
872                                 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
873                                                    NULL, NULL, 0);
874                                 protocol++;
875                                 n++;
876                         }
877                 }
878
879                 vh = vh->vhost_next;
880         }
881
882         for (n = 0; n < context->count_threads; n++) {
883                 pt = &context->pt[n];
884
885                 lws_libev_destroyloop(context, n);
886                 lws_libuv_destroyloop(context, n);
887
888                 lws_free_set_NULL(context->pt[n].serv_buf);
889                 if (pt->ah_pool)
890                         lws_free(pt->ah_pool);
891                 if (pt->http_header_data)
892                         lws_free(pt->http_header_data);
893         }
894         lws_plat_context_early_destroy(context);
895         lws_ssl_context_destroy(context);
896
897         if (context->pt[0].fds)
898                 lws_free_set_NULL(context->pt[0].fds);
899
900         /* free all the vhost allocations */
901
902         vh = context->vhost_list;
903         while (vh) {
904                 protocol = vh->protocols;
905                 if (protocol) {
906                         n = 0;
907                         while (n < vh->count_protocols) {
908                                 if (vh->protocol_vh_privs &&
909                                     vh->protocol_vh_privs[n]) {
910                                         lws_free(vh->protocol_vh_privs[n]);
911                                         vh->protocol_vh_privs[n] = NULL;
912                                 }
913                                 protocol++;
914                                 n++;
915                         }
916                 }
917                 if (vh->protocol_vh_privs)
918                         lws_free(vh->protocol_vh_privs);
919                 lws_ssl_SSL_CTX_destroy(vh);
920                 lws_free(vh->same_vh_protocol_list);
921 #ifdef LWS_WITH_PLUGINS
922                 if (context->plugin_list)
923                         lws_free((void *)vh->protocols);
924 #ifndef LWS_NO_EXTENSIONS
925                 if (context->plugin_extension_count)
926                         lws_free((void *)vh->extensions);
927 #endif
928 #endif
929 #ifdef LWS_WITH_ACCESS_LOG
930                 if (vh->log_fd != (int)LWS_INVALID_FILE)
931                         close(vh->log_fd);
932 #endif
933
934                 vh1 = vh->vhost_next;
935                 lws_free(vh);
936                 vh = vh1;
937         }
938
939         lws_plat_context_late_destroy(context);
940
941         lws_free(context);
942 }