ws ping pong on idle connections
[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 static int
198 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                 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         char *p;
313         int n;
314
315         if (!vh)
316                 return NULL;
317
318         if (!info->protocols)
319                 info->protocols = &protocols_dummy[0];
320
321         vh->context = context;
322         if (!info->vhost_name)
323                 vh->name = "default";
324         else
325                 vh->name = info->vhost_name;
326
327         vh->iface = info->iface;
328         for (vh->count_protocols = 0;
329              info->protocols[vh->count_protocols].callback;
330              vh->count_protocols++)
331                 ;
332
333         vh->options = info->options;
334         vh->pvo = info->pvo;
335         vh->keepalive_timeout = info->keepalive_timeout;
336
337 #ifdef LWS_WITH_PLUGINS
338         if (plugin) {
339                 /*
340                  * give the vhost a unified list of protocols including the
341                  * ones that came from plugins
342                  */
343                 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
344                                            (vh->count_protocols +
345                                            context->plugin_protocol_count + 1));
346                 if (!lwsp)
347                         return NULL;
348
349                 m = vh->count_protocols;
350                 memcpy(lwsp, info->protocols,
351                        sizeof(struct lws_protocols) * m);
352
353                 /* for compatibility, all protocols enabled on vhost if only
354                  * the default vhost exists.  Otherwise only vhosts who ask
355                  * for a protocol get it enabled.
356                  */
357
358                 if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
359                         f = 0;
360
361                 while (plugin) {
362                         for (n = 0; n < plugin->caps.count_protocols; n++) {
363                                 /*
364                                  * for compatibility's sake, no pvo implies
365                                  * allow all protocols
366                                  */
367                                 if (f || lws_vhost_protocol_options(vh,
368                                     plugin->caps.protocols[n].name)) {
369                                         memcpy(&lwsp[m],
370                                                &plugin->caps.protocols[n],
371                                                sizeof(struct lws_protocols));
372                                         m++;
373                                         vh->count_protocols++;
374                                 }
375                         }
376                         plugin = plugin->list;
377                 }
378                 vh->protocols = lwsp;
379         } else
380 #endif
381                 vh->protocols = info->protocols;
382
383         vh->same_vh_protocol_list = (struct lws **)
384                         lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
385
386         vh->mount_list = info->mounts;
387
388 #ifdef LWS_USE_UNIX_SOCK
389         if (LWS_UNIX_SOCK_ENABLED(context)) {
390                 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
391                                 vh->name, info->iface, vh->count_protocols);
392         } else
393 #endif
394         lwsl_notice("Creating Vhost '%s' port %d, %d protocols, IPv6 %s\n",
395                         vh->name, info->port, vh->count_protocols, LWS_IPV6_ENABLED(vh) ? "on" : "off");
396
397         mounts = info->mounts;
398         while (mounts) {
399                 lwsl_notice("   mounting %s%s to %s\n",
400                                 mount_protocols[mounts->origin_protocol],
401                                 mounts->origin, mounts->mountpoint);
402
403                 /* convert interpreter protocol names to pointers */
404                 pvo = mounts->interpret;
405                 while (pvo) {
406                         for (n = 0; n < vh->count_protocols; n++)
407                                 if (!strcmp(pvo->value, vh->protocols[n].name)) {
408                                         ((struct lws_protocol_vhost_options *)pvo)->value =
409                                                         (const char *)(long)n;
410                                         break;
411                                 }
412                         if (n == vh->count_protocols)
413                                 lwsl_err("ignoring unknown interpret protocol %s\n", pvo->value);
414                         pvo = pvo->next;
415                 }
416
417                 mounts = mounts->mount_next;
418         }
419
420 #ifndef LWS_NO_EXTENSIONS
421 #ifdef LWS_WITH_PLUGINS
422         if (context->plugin_extension_count) {
423
424                 m = 0;
425                 while (info->extensions && info->extensions[m].callback)
426                         m++;
427
428                 /*
429                  * give the vhost a unified list of extensions including the
430                  * ones that came from plugins
431                  */
432                 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
433                                            (m +
434                                            context->plugin_extension_count + 1));
435                 if (!vh->extensions)
436                         return NULL;
437
438                 memcpy((struct lws_extension *)vh->extensions, info->extensions,
439                        sizeof(struct lws_extension) * m);
440                 plugin = context->plugin_list;
441                 while (plugin) {
442                         memcpy((struct lws_extension *)&vh->extensions[m],
443                                 plugin->caps.extensions,
444                                sizeof(struct lws_extension) *
445                                plugin->caps.count_extensions);
446                         m += plugin->caps.count_extensions;
447                         plugin = plugin->list;
448                 }
449         } else
450 #endif
451                 vh->extensions = info->extensions;
452 #endif
453
454         vh->listen_port = info->port;
455         vh->http_proxy_port = 0;
456         vh->http_proxy_address[0] = '\0';
457
458         /* either use proxy from info, or try get it from env var */
459
460         if (info->http_proxy_address) {
461                 /* override for backwards compatibility */
462                 if (info->http_proxy_port)
463                         vh->http_proxy_port = info->http_proxy_port;
464                 lws_set_proxy(vh, info->http_proxy_address);
465         } else {
466 #ifdef LWS_HAVE_GETENV
467                 p = getenv("http_proxy");
468                 if (p)
469                         lws_set_proxy(vh, p);
470 #endif
471         }
472
473         vh->ka_time = info->ka_time;
474         vh->ka_interval = info->ka_interval;
475         vh->ka_probes = info->ka_probes;
476
477         if (vh->options & LWS_SERVER_OPTION_STS)
478                 lwsl_notice("   STS enabled\n");
479
480 #ifdef LWS_WITH_ACCESS_LOG
481         if (info->log_filepath) {
482                 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
483                 if (vh->log_fd == (int)LWS_INVALID_FILE) {
484                         lwsl_err("unable to open log filepath %s\n",
485                                  info->log_filepath);
486                         goto bail;
487                 }
488 #ifndef WIN32
489                 if (context->uid != -1)
490                         if (chown(info->log_filepath, context->uid,
491                                   context->gid) == -1)
492                                 lwsl_err("unable to chown log file %s\n",
493                                                 info->log_filepath);
494 #endif
495         } else
496                 vh->log_fd = (int)LWS_INVALID_FILE;
497 #endif
498
499         if (lws_context_init_server_ssl(info, vh))
500                 goto bail;
501
502         if (lws_context_init_client_ssl(info, vh))
503                 goto bail;
504
505         if (lws_context_init_server(info, vh))
506                 goto bail;
507
508         while (1) {
509                 if (!(*vh1)) {
510                         *vh1 = vh;
511                         break;
512                 }
513                 vh1 = &(*vh1)->vhost_next;
514         };
515
516         return vh;
517
518 bail:
519         lws_free(vh);
520
521         return NULL;
522 }
523
524 LWS_VISIBLE int
525 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
526                           struct lws_vhost *vhost)
527 {
528         struct lws_context_creation_info i;
529
530         memcpy(&i, info, sizeof(i));
531         i.port = CONTEXT_PORT_NO_LISTEN;
532
533         return lws_context_init_client_ssl(&i, vhost);
534 }
535
536 LWS_VISIBLE struct lws_context *
537 lws_create_context(struct lws_context_creation_info *info)
538 {
539         struct lws_context *context = NULL;
540         struct lws wsi;
541 #ifndef LWS_NO_DAEMONIZE
542         int pid_daemon = get_daemonize_pid();
543 #endif
544         int n, m;
545 #if defined(__ANDROID__)
546         struct rlimit rt;
547 #endif
548
549         lwsl_notice("Initial logging level %d\n", log_level);
550         lwsl_notice("Libwebsockets version: %s\n", library_version);
551 #if LWS_POSIX
552 #ifdef LWS_USE_IPV6
553         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
554                 lwsl_notice("IPV6 compiled in and enabled\n");
555         else
556                 lwsl_notice("IPV6 compiled in but disabled\n");
557 #else
558         lwsl_notice("IPV6 not compiled in\n");
559 #endif
560         lws_feature_status_libev(info);
561         lws_feature_status_libuv(info);
562 #endif
563         lwsl_info(" LWS_DEF_HEADER_LEN    : %u\n", LWS_DEF_HEADER_LEN);
564         lwsl_info(" LWS_MAX_PROTOCOLS     : %u\n", LWS_MAX_PROTOCOLS);
565         lwsl_info(" LWS_MAX_SMP           : %u\n", LWS_MAX_SMP);
566         lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
567         lwsl_info(" sizeof (*info)        : %u\n", sizeof(*info));
568 #if LWS_POSIX
569         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
570 #endif
571         if (lws_plat_context_early_init())
572                 return NULL;
573
574         context = lws_zalloc(sizeof(struct lws_context));
575         if (!context) {
576                 lwsl_err("No memory for websocket context\n");
577                 return NULL;
578         }
579
580         if (info->pt_serv_buf_size)
581                 context->pt_serv_buf_size = info->pt_serv_buf_size;
582         else
583                 context->pt_serv_buf_size = 4096;
584
585         context->time_up = time(NULL);
586 #ifndef LWS_NO_DAEMONIZE
587         if (pid_daemon) {
588                 context->started_with_parent = pid_daemon;
589                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
590         }
591 #endif
592 #if defined(__ANDROID__)
593                 n = getrlimit ( RLIMIT_NOFILE,&rt);
594                 if (-1 == n) {
595                         lwsl_err("Get RLIMIT_NOFILE failed!\n");
596                         return NULL;
597                 }
598                 context->max_fds = rt.rlim_cur;
599 #else
600                 context->max_fds = getdtablesize();
601 #endif
602
603         if (info->count_threads)
604                 context->count_threads = info->count_threads;
605         else
606                 context->count_threads = 1;
607
608         if (context->count_threads > LWS_MAX_SMP)
609                 context->count_threads = LWS_MAX_SMP;
610
611         context->token_limits = info->token_limits;
612
613         context->options = info->options;
614
615         if (info->timeout_secs)
616                 context->timeout_secs = info->timeout_secs;
617         else
618                 context->timeout_secs = AWAITING_TIMEOUT;
619
620         context->ws_ping_pong_interval = info->ws_ping_pong_interval;
621
622         lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
623
624         if (info->max_http_header_data)
625                 context->max_http_header_data = info->max_http_header_data;
626         else
627                 if (info->max_http_header_data2)
628                         context->max_http_header_data =
629                                         info->max_http_header_data2;
630                 else
631                         context->max_http_header_data = LWS_DEF_HEADER_LEN;
632         if (info->max_http_header_pool)
633                 context->max_http_header_pool = info->max_http_header_pool;
634         else
635                 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
636
637         /*
638          * Allocate the per-thread storage for scratchpad buffers,
639          * and header data pool
640          */
641         for (n = 0; n < context->count_threads; n++) {
642                 context->pt[n].serv_buf = lws_zalloc(context->pt_serv_buf_size);
643                 if (!context->pt[n].serv_buf) {
644                         lwsl_err("OOM\n");
645                         return NULL;
646                 }
647
648                 context->pt[n].context = context;
649                 context->pt[n].tid = n;
650                 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
651                                                        context->max_http_header_pool);
652                 if (!context->pt[n].http_header_data)
653                         goto bail;
654
655                 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
656                                               context->max_http_header_pool);
657                 for (m = 0; m < context->max_http_header_pool; m++)
658                         context->pt[n].ah_pool[m].data =
659                                 (char *)context->pt[n].http_header_data +
660                                 (m * context->max_http_header_data);
661                 if (!context->pt[n].ah_pool)
662                         goto bail;
663
664                 lws_pt_mutex_init(&context->pt[n]);
665         }
666
667         if (info->fd_limit_per_thread)
668                 context->fd_limit_per_thread = info->fd_limit_per_thread;
669         else
670                 context->fd_limit_per_thread = context->max_fds /
671                                                context->count_threads;
672
673         lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
674                     context->fd_limit_per_thread);
675
676         memset(&wsi, 0, sizeof(wsi));
677         wsi.context = context;
678
679         if (!info->ka_interval && info->ka_time > 0) {
680                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
681                 return NULL;
682         }
683
684 #ifdef LWS_USE_LIBEV
685         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
686          * enable libev mediated SIGINT handling with a default handler of
687          * lws_sigint_cb. The handler can be overridden or disabled
688          * by invoking lws_sigint_cfg after creating the context, but
689          * before invoking lws_initloop:
690          */
691         context->use_ev_sigint = 1;
692         context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
693 #endif /* LWS_USE_LIBEV */
694 #ifdef LWS_USE_LIBUV
695         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
696          * enable libev mediated SIGINT handling with a default handler of
697          * lws_sigint_cb. The handler can be overridden or disabled
698          * by invoking lws_sigint_cfg after creating the context, but
699          * before invoking lws_initloop:
700          */
701         context->use_ev_sigint = 1;
702         context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
703 #endif
704
705         lwsl_info(" mem: context:         %5u bytes (%d ctx + (%d thr x %d))\n",
706                   sizeof(struct lws_context) +
707                   (context->count_threads * context->pt_serv_buf_size),
708                   sizeof(struct lws_context),
709                   context->count_threads,
710                   context->pt_serv_buf_size);
711
712         lwsl_info(" mem: http hdr rsvd:   %5u bytes (%u thr x (%u + %u) x %u))\n",
713                     (context->max_http_header_data +
714                      sizeof(struct allocated_headers)) *
715                     context->max_http_header_pool * context->count_threads,
716                     context->count_threads,
717                     context->max_http_header_data,
718                     sizeof(struct allocated_headers),
719                     context->max_http_header_pool);
720         n = sizeof(struct lws_pollfd) * context->count_threads *
721             context->fd_limit_per_thread;
722         context->pt[0].fds = lws_zalloc(n);
723         if (context->pt[0].fds == NULL) {
724                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
725                 goto bail;
726         }
727         lwsl_info(" mem: pollfd map:      %5u\n", n);
728
729         if (info->server_string) {
730                 context->server_string = info->server_string;
731                 context->server_string_len = (short)
732                                 strlen(context->server_string);
733         } else {
734                 context->server_string = "libwebsockets";
735                 context->server_string_len = 13;
736         }
737
738 #if LWS_MAX_SMP > 1
739         /* each thread serves his own chunk of fds */
740         for (n = 1; n < (int)info->count_threads; n++)
741                 context->pt[n].fds = context->pt[n - 1].fds +
742                                      context->fd_limit_per_thread;
743 #endif
744
745         if (lws_plat_init(context, info))
746                 goto bail;
747
748         lws_context_init_ssl_library(info);
749
750         context->user_space = info->user;
751
752         /*
753          * if he's not saying he'll make his own vhosts later then act
754          * compatibly and make a default vhost using the data in the info
755          */
756         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
757                 if (!lws_create_vhost(context, info)) {
758                         lwsl_err("Failed to create default vhost\n");
759                         return NULL;
760                 }
761
762         lws_context_init_extensions(info, context);
763
764         lwsl_notice(" mem: per-conn:        %5u bytes + protocol rx buf\n",
765                     sizeof(struct lws));
766
767         strcpy(context->canonical_hostname, "unknown");
768         lws_server_get_canonical_hostname(context, info);
769
770         context->uid = info->uid;
771         context->gid = info->gid;
772
773         /*
774          * drop any root privs for this process
775          * to listen on port < 1023 we would have needed root, but now we are
776          * listening, we don't want the power for anything else
777          */
778         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
779                 lws_plat_drop_app_privileges(info);
780
781         /*
782          * give all extensions a chance to create any per-context
783          * allocations they need
784          */
785         if (info->port != CONTEXT_PORT_NO_LISTEN) {
786                 if (lws_ext_cb_all_exts(context, NULL,
787                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
788                         goto bail;
789         } else
790                 if (lws_ext_cb_all_exts(context, NULL,
791                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
792                         goto bail;
793
794         return context;
795
796 bail:
797         lws_context_destroy(context);
798         return NULL;
799 }
800
801 LWS_VISIBLE void
802 lws_context_destroy(struct lws_context *context)
803 {
804         const struct lws_protocols *protocol = NULL;
805         struct lws_context_per_thread *pt;
806         struct lws_vhost *vh = NULL, *vh1;
807         struct lws wsi;
808         int n, m;
809
810         lwsl_notice("%s\n", __func__);
811
812         if (!context)
813                 return;
814
815         m = context->count_threads;
816         context->being_destroyed = 1;
817
818         memset(&wsi, 0, sizeof(wsi));
819         wsi.context = context;
820
821 #ifdef LWS_LATENCY
822         if (context->worst_latency_info[0])
823                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
824 #endif
825
826         while (m--) {
827                 pt = &context->pt[m];
828
829                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
830                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
831                         if (!wsi)
832                                 continue;
833
834                         lws_close_free_wsi(wsi,
835                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
836                                 /* no protocol close */);
837                         n--;
838                 }
839                 lws_pt_mutex_destroy(pt);
840         }
841         /*
842          * give all extensions a chance to clean up any per-context
843          * allocations they might have made
844          */
845
846         n = lws_ext_cb_all_exts(context, NULL,
847                                 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
848
849         n = lws_ext_cb_all_exts(context, NULL,
850                                 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
851
852         /*
853          * inform all the protocols that they are done and will have no more
854          * callbacks.
855          *
856          * We can't free things until after the event loop shuts down.
857          */
858         if (context->protocol_init_done)
859                 vh = context->vhost_list;
860         while (vh) {
861                 wsi.vhost = vh;
862                 protocol = vh->protocols;
863                 if (protocol) {
864                         n = 0;
865                         while (n < vh->count_protocols) {
866                                 wsi.protocol = protocol;
867                                 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
868                                                    NULL, NULL, 0);
869                                 protocol++;
870                                 n++;
871                         }
872                 }
873
874                 vh = vh->vhost_next;
875         }
876
877         for (n = 0; n < context->count_threads; n++) {
878                 pt = &context->pt[n];
879
880                 lws_libev_destroyloop(context, n);
881                 lws_libuv_destroyloop(context, n);
882
883                 lws_free_set_NULL(context->pt[n].serv_buf);
884                 if (pt->ah_pool)
885                         lws_free(pt->ah_pool);
886                 if (pt->http_header_data)
887                         lws_free(pt->http_header_data);
888         }
889         lws_plat_context_early_destroy(context);
890         lws_ssl_context_destroy(context);
891
892         if (context->pt[0].fds)
893                 lws_free_set_NULL(context->pt[0].fds);
894
895         /* free all the vhost allocations */
896
897         vh = context->vhost_list;
898         while (vh) {
899                 protocol = vh->protocols;
900                 if (protocol) {
901                         n = 0;
902                         while (n < vh->count_protocols) {
903                                 if (vh->protocol_vh_privs &&
904                                     vh->protocol_vh_privs[n]) {
905                                         lws_free(vh->protocol_vh_privs[n]);
906                                         vh->protocol_vh_privs[n] = NULL;
907                                 }
908                                 protocol++;
909                                 n++;
910                         }
911                 }
912                 if (vh->protocol_vh_privs)
913                         lws_free(vh->protocol_vh_privs);
914                 lws_ssl_SSL_CTX_destroy(vh);
915                 lws_free(vh->same_vh_protocol_list);
916 #ifdef LWS_WITH_PLUGINS
917                 if (context->plugin_list)
918                         lws_free((void *)vh->protocols);
919 #ifndef LWS_NO_EXTENSIONS
920                 if (context->plugin_extension_count)
921                         lws_free((void *)vh->extensions);
922 #endif
923 #endif
924 #ifdef LWS_WITH_ACCESS_LOG
925                 if (vh->log_fd != (int)LWS_INVALID_FILE)
926                         close(vh->log_fd);
927 #endif
928
929                 vh1 = vh->vhost_next;
930                 lws_free(vh);
931                 vh = vh1;
932         }
933
934         lws_plat_context_late_destroy(context);
935
936         lws_free(context);
937 }