ah: allow configurable ah hold timeout
[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 /*
126  * inform every vhost that hasn't already done it, that
127  * his protocols are initializing
128  */
129 LWS_VISIBLE int
130 lws_protocol_init(struct lws_context *context)
131 {
132         struct lws_vhost *vh = context->vhost_list;
133         const struct lws_protocol_vhost_options *pvo, *pvo1;
134         struct lws wsi;
135         int n;
136
137         memset(&wsi, 0, sizeof(wsi));
138         wsi.context = context;
139
140         lwsl_info("%s\n", __func__);
141
142         while (vh) {
143                 wsi.vhost = vh;
144
145                 /* only do the protocol init once for a given vhost */
146                 if (vh->created_vhost_protocols)
147                         goto next;
148
149                 /* initialize supported protocols on this vhost */
150
151                 for (n = 0; n < vh->count_protocols; n++) {
152                         wsi.protocol = &vh->protocols[n];
153                         if (!vh->protocols[n].name)
154                                 continue;
155                         pvo = lws_vhost_protocol_options(vh,
156                                                          vh->protocols[n].name);
157                         if (pvo) {
158                                 /*
159                                  * linked list of options specific to
160                                  * vh + protocol
161                                  */
162                                 pvo1 = pvo;
163                                 pvo = pvo1->options;
164
165                                 while (pvo) {
166                                         lwsl_notice("    vh %s prot %s opt %s\n",
167                                                         vh->name,
168                                                         vh->protocols[n].name,
169                                                         pvo->name);
170
171                                         if (!strcmp(pvo->name, "default")) {
172                                                 lwsl_notice("Setting default "
173                                                    "protocol for vh %s to %s\n",
174                                                    vh->name,
175                                                    vh->protocols[n].name);
176                                                 vh->default_protocol_index = n;
177                                         }
178                                         if (!strcmp(pvo->name, "raw")) {
179                                                 lwsl_notice("Setting raw "
180                                                    "protocol for vh %s to %s\n",
181                                                    vh->name,
182                                                    vh->protocols[n].name);
183                                                 vh->raw_protocol_index = n;
184                                         }
185                                         pvo = pvo->next;
186                                 }
187
188                                 pvo = pvo1->options;
189                         }
190
191                         /*
192                          * inform all the protocols that they are doing their one-time
193                          * initialization if they want to.
194                          *
195                          * NOTE the wsi is all zeros except for the context, vh and
196                          * protocol ptrs so lws_get_context(wsi) etc can work
197                          */
198                         if (vh->protocols[n].callback(&wsi,
199                                 LWS_CALLBACK_PROTOCOL_INIT, NULL,
200                                 (void *)pvo, 0))
201                                 return 1;
202                 }
203
204                 vh->created_vhost_protocols = 1;
205 next:
206                 vh = vh->vhost_next;
207         }
208
209         if (!context->protocol_init_done)
210                 lws_finalize_startup(context);
211
212         context->protocol_init_done = 1;
213
214         return 0;
215 }
216
217 LWS_VISIBLE int
218 lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
219                     void *user, void *in, size_t len)
220 {
221 #ifdef LWS_WITH_CGI
222         struct lws_cgi_args *args;
223 #endif
224 #if defined(LWS_WITH_CGI) || defined(LWS_WITH_HTTP_PROXY)
225         char buf[512];
226         int n;
227 #endif
228
229
230         switch (reason) {
231         case LWS_CALLBACK_HTTP:
232 #ifndef LWS_NO_SERVER
233                 if (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL))
234                         return -1;
235
236                 if (lws_http_transaction_completed(wsi))
237 #endif
238                         return -1;
239                 break;
240
241         case LWS_CALLBACK_HTTP_WRITEABLE:
242 #ifdef LWS_WITH_CGI
243                 if (wsi->reason_bf & 1) {
244                         if (lws_cgi_write_split_stdout_headers(wsi) < 0)
245                                 return -1;
246
247                         if (wsi->reason_bf & 8)
248                                 wsi->reason_bf &= ~8;
249                         else
250                                 wsi->reason_bf &= ~1;
251                         break;
252                 }
253 #endif
254 #if defined(LWS_WITH_HTTP_PROXY)
255                 if (wsi->reason_bf & 2) {
256                         char *px = buf + LWS_PRE;
257                         int lenx = sizeof(buf) - LWS_PRE;
258                         /*
259                          * our sink is writeable and our source has something
260                          * to read.  So read a lump of source material of
261                          * suitable size to send or what's available, whichever
262                          * is the smaller.
263                          */
264
265
266                         wsi->reason_bf &= ~2;
267                         if (!lws_get_child(wsi))
268                                 break;
269                         if (lws_http_client_read(lws_get_child(wsi), &px, &lenx) < 0)
270                                 return -1;
271                         break;
272                 }
273 #endif
274                 break;
275
276 #if defined(LWS_WITH_HTTP_PROXY)
277         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
278                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
279                 assert(lws_get_parent(wsi));
280                 if (!lws_get_parent(wsi))
281                         break;
282                 lws_get_parent(wsi)->reason_bf |= 2;
283                 lws_callback_on_writable(lws_get_parent(wsi));
284                 break;
285
286         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
287                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", (int)len);
288                 assert(lws_get_parent(wsi));
289                 n = lws_write(lws_get_parent(wsi), (unsigned char *)in,
290                                 len, LWS_WRITE_HTTP);
291                 if (n < 0)
292                         return -1;
293                 break;
294
295         case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
296                 unsigned char *p, *end;
297                 char ctype[64], ctlen = 0;
298
299                 //lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
300         
301                 p = (unsigned char *)buf + LWS_PRE;
302                 end = p + sizeof(buf) - LWS_PRE;
303
304                 if (lws_add_http_header_status(lws_get_parent(wsi), HTTP_STATUS_OK, &p, end))
305                         return 1;
306                 if (lws_add_http_header_by_token(lws_get_parent(wsi),
307                                 WSI_TOKEN_HTTP_SERVER,
308                                 (unsigned char *)"libwebsockets",
309                                 13, &p, end))
310                         return 1;
311
312                 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
313                 if (ctlen > 0) {
314                         if (lws_add_http_header_by_token(lws_get_parent(wsi),
315                                 WSI_TOKEN_HTTP_CONTENT_TYPE,
316                                 (unsigned char *)ctype, ctlen, &p, end))
317                                 return 1;
318                 }
319 #if 0
320                 if (lws_add_http_header_content_length(lws_get_parent(wsi),
321                                                        file_len, &p, end))
322                         return 1;
323 #endif
324                 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
325                         return 1;
326
327                 *p = '\0';
328 //              lwsl_info("%s\n", buf + LWS_PRE);
329
330                 n = lws_write(lws_get_parent(wsi), (unsigned char *)buf + LWS_PRE,
331                               p - ((unsigned char *)buf + LWS_PRE),
332                               LWS_WRITE_HTTP_HEADERS);
333                 if (n < 0)
334                         return -1;
335
336                 break; }
337
338 #endif
339
340 #ifdef LWS_WITH_CGI
341         /* CGI IO events (POLLIN/OUT) appear here, our default policy is:
342          *
343          *  - POST data goes on subprocess stdin
344          *  - subprocess stdout goes on http via writeable callback
345          *  - subprocess stderr goes to the logs
346          */
347         case LWS_CALLBACK_CGI:
348                 args = (struct lws_cgi_args *)in;
349                 switch (args->ch) { /* which of stdin/out/err ? */
350                 case LWS_STDIN:
351                         /* TBD stdin rx flow control */
352                         break;
353                 case LWS_STDOUT:
354                         wsi->reason_bf |= 1;
355                         /* when writing to MASTER would not block */
356                         lws_callback_on_writable(wsi);
357                         break;
358                 case LWS_STDERR:
359                         n = read(lws_get_socket_fd(args->stdwsi[LWS_STDERR]),
360                                                    buf, sizeof(buf) - 2);
361                         if (n > 0) {
362                                 if (buf[n - 1] != '\n')
363                                         buf[n++] = '\n';
364                                 buf[n] = '\0';
365                                 lwsl_notice("CGI-stderr: %s\n", buf);
366                         }
367                         break;
368                 }
369                 break;
370
371         case LWS_CALLBACK_CGI_TERMINATED:
372                 return -1;
373
374         case LWS_CALLBACK_CGI_STDIN_DATA:  /* POST body for stdin */
375                 args = (struct lws_cgi_args *)in;
376                 args->data[args->len] = '\0';
377                 n = write(lws_get_socket_fd(args->stdwsi[LWS_STDIN]),
378                           args->data, args->len);
379                 if (n < args->len)
380                         lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: "
381                                     "sent %d only %d went", n, args->len);
382                 return n;
383 #endif
384
385         case LWS_CALLBACK_SSL_INFO:
386                 {
387                         struct lws_ssl_info *si = in;
388
389                         (void)si;
390                         lwsl_notice("LWS_CALLBACK_SSL_INFO: where: 0x%x, ret: 0x%x\n",
391                                         si->where, si->ret);
392                 }
393                 break;
394
395         default:
396                 break;
397         }
398
399         return 0;
400 }
401
402 /* list of supported protocols and callbacks */
403
404 static const struct lws_protocols protocols_dummy[] = {
405         /* first protocol must always be HTTP handler */
406
407         {
408                 "http-only",            /* name */
409                 lws_callback_http_dummy,                /* callback */
410                 0,      /* per_session_data_size */
411                 0,                      /* max frame size / rx buffer */
412                 0, NULL, 0
413         },
414         /*
415          * the other protocols are provided by lws plugins
416          */
417         { NULL, NULL, 0, 0, 0, NULL, 0} /* terminator */
418 };
419
420 #ifdef LWS_PLAT_OPTEE
421 #undef LWS_HAVE_GETENV
422 #endif
423
424 LWS_VISIBLE struct lws_vhost *
425 lws_create_vhost(struct lws_context *context,
426                  struct lws_context_creation_info *info)
427 {
428         struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
429                          **vh1 = &context->vhost_list;
430         const struct lws_http_mount *mounts;
431         const struct lws_protocol_vhost_options *pvo;
432 #ifdef LWS_WITH_PLUGINS
433         struct lws_plugin *plugin = context->plugin_list;
434 #endif
435         struct lws_protocols *lwsp;
436         int m, f = !info->pvo;
437 #ifdef LWS_HAVE_GETENV
438         char *p;
439 #endif
440         int n;
441
442         if (!vh)
443                 return NULL;
444
445         if (!info->protocols)
446                 info->protocols = &protocols_dummy[0];
447
448         vh->context = context;
449         if (!info->vhost_name)
450                 vh->name = "default";
451         else
452                 vh->name = info->vhost_name;
453
454         vh->iface = info->iface;
455 #if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32) && !defined(OPTEE_TA) && !defined(WIN32)
456         vh->bind_iface = info->bind_iface;
457 #endif
458
459         for (vh->count_protocols = 0;
460              info->protocols[vh->count_protocols].callback;
461              vh->count_protocols++)
462                 ;
463
464         vh->options = info->options;
465         vh->pvo = info->pvo;
466         vh->headers = info->headers;
467         vh->ssl_info_event_mask = info->ssl_info_event_mask;
468         if (info->keepalive_timeout)
469                 vh->keepalive_timeout = info->keepalive_timeout;
470         else
471                 vh->keepalive_timeout = 5;
472
473         if (info->timeout_secs_ah_idle)
474                 vh->timeout_secs_ah_idle = info->timeout_secs_ah_idle;
475         else
476                 vh->timeout_secs_ah_idle = 10;
477
478         /*
479          * give the vhost a unified list of protocols including the
480          * ones that came from plugins
481          */
482         lwsp = lws_zalloc(sizeof(struct lws_protocols) *
483                                    (vh->count_protocols +
484                                    context->plugin_protocol_count + 1));
485         if (!lwsp) {
486                 lwsl_err("OOM\n");
487                 return NULL;
488         }
489
490         m = vh->count_protocols;
491         memcpy(lwsp, info->protocols, sizeof(struct lws_protocols) * m);
492
493         /* for compatibility, all protocols enabled on vhost if only
494          * the default vhost exists.  Otherwise only vhosts who ask
495          * for a protocol get it enabled.
496          */
497
498         if (context->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
499                 f = 0;
500         (void)f;
501 #ifdef LWS_WITH_PLUGINS
502         if (plugin) {
503
504                 while (plugin) {
505                         for (n = 0; n < plugin->caps.count_protocols; n++) {
506                                 /*
507                                  * for compatibility's sake, no pvo implies
508                                  * allow all protocols
509                                  */
510                                 if (f || lws_vhost_protocol_options(vh,
511                                     plugin->caps.protocols[n].name)) {
512                                         memcpy(&lwsp[m],
513                                                &plugin->caps.protocols[n],
514                                                sizeof(struct lws_protocols));
515                                         m++;
516                                         vh->count_protocols++;
517                                 }
518                         }
519                         plugin = plugin->list;
520                 }
521         }
522 #endif
523
524         if (
525 #ifdef LWS_WITH_PLUGINS
526             (context->plugin_list) ||
527 #endif
528             context->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
529                 vh->protocols = lwsp;
530         else {
531                 vh->protocols = info->protocols;
532                 free(lwsp);
533         }
534
535         vh->same_vh_protocol_list = (struct lws **)
536                         lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
537
538         vh->mount_list = info->mounts;
539
540 #ifdef LWS_USE_UNIX_SOCK
541         if (LWS_UNIX_SOCK_ENABLED(context)) {
542                 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
543                                 vh->name, info->iface, vh->count_protocols);
544         } else
545 #endif
546         lwsl_notice("Creating Vhost '%s' port %d, %d protocols, IPv6 %s\n",
547                         vh->name, info->port, vh->count_protocols, LWS_IPV6_ENABLED(vh) ? "on" : "off");
548
549         mounts = info->mounts;
550         while (mounts) {
551                 (void)mount_protocols[0];
552                 lwsl_notice("   mounting %s%s to %s\n",
553                                 mount_protocols[mounts->origin_protocol],
554                                 mounts->origin, mounts->mountpoint);
555
556                 /* convert interpreter protocol names to pointers */
557                 pvo = mounts->interpret;
558                 while (pvo) {
559                         for (n = 0; n < vh->count_protocols; n++)
560                                 if (!strcmp(pvo->value, vh->protocols[n].name)) {
561                                         ((struct lws_protocol_vhost_options *)pvo)->value =
562                                                         (const char *)(lws_intptr_t)n;
563                                         break;
564                                 }
565                         if (n == vh->count_protocols)
566                                 lwsl_err("ignoring unknown interpret protocol %s\n", pvo->value);
567                         pvo = pvo->next;
568                 }
569
570                 mounts = mounts->mount_next;
571         }
572
573 #ifndef LWS_NO_EXTENSIONS
574 #ifdef LWS_WITH_PLUGINS
575         if (context->plugin_extension_count) {
576
577                 m = 0;
578                 while (info->extensions && info->extensions[m].callback)
579                         m++;
580
581                 /*
582                  * give the vhost a unified list of extensions including the
583                  * ones that came from plugins
584                  */
585                 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
586                                            (m +
587                                            context->plugin_extension_count + 1));
588                 if (!vh->extensions)
589                         return NULL;
590
591                 memcpy((struct lws_extension *)vh->extensions, info->extensions,
592                        sizeof(struct lws_extension) * m);
593                 plugin = context->plugin_list;
594                 while (plugin) {
595                         memcpy((struct lws_extension *)&vh->extensions[m],
596                                 plugin->caps.extensions,
597                                sizeof(struct lws_extension) *
598                                plugin->caps.count_extensions);
599                         m += plugin->caps.count_extensions;
600                         plugin = plugin->list;
601                 }
602         } else
603 #endif
604                 vh->extensions = info->extensions;
605 #endif
606
607         vh->listen_port = info->port;
608 #if !defined(LWS_WITH_ESP8266)
609         vh->http_proxy_port = 0;
610         vh->http_proxy_address[0] = '\0';
611 #if defined(LWS_WITH_SOCKS5)
612         vh->socks_proxy_port = 0;
613         vh->socks_proxy_address[0] = '\0';
614 #endif
615
616         /* either use proxy from info, or try get it from env var */
617
618         /* http proxy */
619         if (info->http_proxy_address) {
620                 /* override for backwards compatibility */
621                 if (info->http_proxy_port)
622                         vh->http_proxy_port = info->http_proxy_port;
623                 lws_set_proxy(vh, info->http_proxy_address);
624         } else {
625 #ifdef LWS_HAVE_GETENV
626                 p = getenv("http_proxy");
627                 if (p)
628                         lws_set_proxy(vh, p);
629 #endif
630         }
631 #if defined(LWS_WITH_SOCKS5)
632         /* socks proxy */
633         if (info->socks_proxy_address) {
634                 /* override for backwards compatibility */
635                 if (info->socks_proxy_port)
636                         vh->socks_proxy_port = info->socks_proxy_port;
637                 lws_set_socks(vh, info->socks_proxy_address);
638         } else {
639 #ifdef LWS_HAVE_GETENV
640                 p = getenv("socks_proxy");
641                 if (p)
642                         lws_set_socks(vh, p);
643 #endif
644         }
645 #endif
646 #endif
647
648         vh->ka_time = info->ka_time;
649         vh->ka_interval = info->ka_interval;
650         vh->ka_probes = info->ka_probes;
651
652         if (vh->options & LWS_SERVER_OPTION_STS)
653                 lwsl_notice("   STS enabled\n");
654
655 #ifdef LWS_WITH_ACCESS_LOG
656         if (info->log_filepath) {
657                 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
658                 if (vh->log_fd == (int)LWS_INVALID_FILE) {
659                         lwsl_err("unable to open log filepath %s\n",
660                                  info->log_filepath);
661                         goto bail;
662                 }
663 #ifndef WIN32
664                 if (context->uid != -1)
665                         if (chown(info->log_filepath, context->uid,
666                                   context->gid) == -1)
667                                 lwsl_err("unable to chown log file %s\n",
668                                                 info->log_filepath);
669 #endif
670         } else
671                 vh->log_fd = (int)LWS_INVALID_FILE;
672 #endif
673         if (lws_context_init_server_ssl(info, vh))
674                 goto bail;
675         if (lws_context_init_client_ssl(info, vh))
676                 goto bail;
677         if (lws_context_init_server(info, vh)) {
678                 lwsl_err("init server failed\n");
679                 goto bail;
680         }
681
682         while (1) {
683                 if (!(*vh1)) {
684                         *vh1 = vh;
685                         break;
686                 }
687                 vh1 = &(*vh1)->vhost_next;
688         };
689         /* for the case we are adding a vhost much later, after server init */
690
691         if (context->protocol_init_done)
692                 lws_protocol_init(context);
693
694         return vh;
695
696 bail:
697         lws_free(vh);
698
699         return NULL;
700 }
701
702 LWS_VISIBLE int
703 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
704                           struct lws_vhost *vhost)
705 {
706         struct lws_context_creation_info i;
707
708         memcpy(&i, info, sizeof(i));
709         i.port = CONTEXT_PORT_NO_LISTEN;
710
711         return lws_context_init_client_ssl(&i, vhost);
712 }
713
714 LWS_VISIBLE struct lws_context *
715 lws_create_context(struct lws_context_creation_info *info)
716 {
717         struct lws_context *context = NULL;
718         struct lws_plat_file_ops *prev;
719 #ifndef LWS_NO_DAEMONIZE
720         int pid_daemon = get_daemonize_pid();
721 #endif
722         int n, m;
723 #if defined(__ANDROID__)
724         struct rlimit rt;
725 #endif
726
727         lwsl_notice("Initial logging level %d\n", log_level);
728         lwsl_notice("Libwebsockets version: %s\n", library_version);
729 #if defined(GCC_VER)
730         lwsl_notice("Compiled with  %s\n", GCC_VER);
731 #endif
732 #if LWS_POSIX
733 #ifdef LWS_USE_IPV6
734         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
735                 lwsl_notice("IPV6 compiled in and enabled\n");
736         else
737                 lwsl_notice("IPV6 compiled in but disabled\n");
738 #else
739         lwsl_notice("IPV6 not compiled in\n");
740 #endif
741 #if !defined(LWS_PLAT_OPTEE) && !defined(LWS_PLAT_ESP32)
742         lws_feature_status_libev(info);
743         lws_feature_status_libuv(info);
744 #endif
745 #endif
746         lwsl_info(" LWS_DEF_HEADER_LEN    : %u\n", LWS_DEF_HEADER_LEN);
747         lwsl_info(" LWS_MAX_PROTOCOLS     : %u\n", LWS_MAX_PROTOCOLS);
748         lwsl_info(" LWS_MAX_SMP           : %u\n", LWS_MAX_SMP);
749         lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
750         lwsl_info(" sizeof (*info)        : %ld\n", (long)sizeof(*info));
751 #if defined(LWS_WITH_STATS)
752         lwsl_notice(" LWS_WITH_STATS        : on\n");
753 #endif
754 #if LWS_POSIX
755         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
756 #endif
757         if (lws_plat_context_early_init())
758                 return NULL;
759
760         context = lws_zalloc(sizeof(struct lws_context));
761         if (!context) {
762                 lwsl_err("No memory for websocket context\n");
763                 return NULL;
764         }
765         if (info->pt_serv_buf_size)
766                 context->pt_serv_buf_size = info->pt_serv_buf_size;
767         else
768                 context->pt_serv_buf_size = 4096;
769
770         /* default to just the platform fops implementation */
771
772         context->fops_platform.LWS_FOP_OPEN     = _lws_plat_file_open;
773         context->fops_platform.LWS_FOP_CLOSE    = _lws_plat_file_close;
774         context->fops_platform.LWS_FOP_SEEK_CUR = _lws_plat_file_seek_cur;
775         context->fops_platform.LWS_FOP_READ     = _lws_plat_file_read;
776         context->fops_platform.LWS_FOP_WRITE    = _lws_plat_file_write;
777         context->fops_platform.fi[0].sig        = NULL;
778
779         /*
780          *  arrange a linear linked-list of fops starting from context->fops
781          *
782          * platform fops
783          * [ -> fops_zip (copied into context so .next settable) ]
784          * [ -> info->fops ]
785          */
786
787         context->fops = &context->fops_platform;
788         prev = (struct lws_plat_file_ops *)context->fops;
789
790 #if defined(LWS_WITH_ZIP_FOPS)
791         /* make a soft copy so we can set .next */
792         context->fops_zip = fops_zip;
793         prev->next = &context->fops_zip;
794         prev = (struct lws_plat_file_ops *)prev->next;
795 #endif
796
797         /* if user provided fops, tack them on the end of the list */
798         if (info->fops)
799                 prev->next = info->fops;
800
801         context->reject_service_keywords = info->reject_service_keywords;
802         if (info->external_baggage_free_on_destroy)
803                 context->external_baggage_free_on_destroy =
804                         info->external_baggage_free_on_destroy;
805
806         context->time_up = time(NULL);
807
808         context->simultaneous_ssl_restriction = info->simultaneous_ssl_restriction;
809
810 #ifndef LWS_NO_DAEMONIZE
811         if (pid_daemon) {
812                 context->started_with_parent = pid_daemon;
813                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
814         }
815 #endif
816 #if defined(__ANDROID__)
817                 n = getrlimit ( RLIMIT_NOFILE,&rt);
818                 if (-1 == n) {
819                         lwsl_err("Get RLIMIT_NOFILE failed!\n");
820                         return NULL;
821                 }
822                 context->max_fds = rt.rlim_cur;
823 #else
824                 context->max_fds = getdtablesize();
825 #endif
826
827         if (info->count_threads)
828                 context->count_threads = info->count_threads;
829         else
830                 context->count_threads = 1;
831
832         if (context->count_threads > LWS_MAX_SMP)
833                 context->count_threads = LWS_MAX_SMP;
834
835         context->token_limits = info->token_limits;
836
837         context->options = info->options;
838
839         if (info->timeout_secs)
840                 context->timeout_secs = info->timeout_secs;
841         else
842                 context->timeout_secs = AWAITING_TIMEOUT;
843
844         context->ws_ping_pong_interval = info->ws_ping_pong_interval;
845
846         lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
847
848         if (info->max_http_header_data)
849                 context->max_http_header_data = info->max_http_header_data;
850         else
851                 if (info->max_http_header_data2)
852                         context->max_http_header_data =
853                                         info->max_http_header_data2;
854                 else
855                         context->max_http_header_data = LWS_DEF_HEADER_LEN;
856         if (info->max_http_header_pool)
857                 context->max_http_header_pool = info->max_http_header_pool;
858         else
859                 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
860
861         /*
862          * Allocate the per-thread storage for scratchpad buffers,
863          * and header data pool
864          */
865         for (n = 0; n < context->count_threads; n++) {
866                 context->pt[n].serv_buf = lws_zalloc(context->pt_serv_buf_size);
867                 if (!context->pt[n].serv_buf) {
868                         lwsl_err("OOM\n");
869                         return NULL;
870                 }
871
872 #ifdef LWS_USE_LIBUV
873                 context->pt[n].context = context;
874 #endif
875                 context->pt[n].tid = n;
876                 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
877                                                        context->max_http_header_pool);
878                 if (!context->pt[n].http_header_data)
879                         goto bail;
880
881                 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
882                                               context->max_http_header_pool);
883                 for (m = 0; m < context->max_http_header_pool; m++)
884                         context->pt[n].ah_pool[m].data =
885                                 (char *)context->pt[n].http_header_data +
886                                 (m * context->max_http_header_data);
887                 if (!context->pt[n].ah_pool)
888                         goto bail;
889
890                 lws_pt_mutex_init(&context->pt[n]);
891         }
892
893         if (info->fd_limit_per_thread)
894                 context->fd_limit_per_thread = info->fd_limit_per_thread;
895         else
896                 context->fd_limit_per_thread = context->max_fds /
897                                                context->count_threads;
898
899         lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
900                     context->fd_limit_per_thread);
901
902         if (!info->ka_interval && info->ka_time > 0) {
903                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
904                 return NULL;
905         }
906
907 #ifdef LWS_USE_LIBEV
908         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
909          * enable libev mediated SIGINT handling with a default handler of
910          * lws_sigint_cb. The handler can be overridden or disabled
911          * by invoking lws_sigint_cfg after creating the context, but
912          * before invoking lws_initloop:
913          */
914         context->use_ev_sigint = 1;
915         context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
916 #endif /* LWS_USE_LIBEV */
917 #ifdef LWS_USE_LIBUV
918         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
919          * enable libev mediated SIGINT handling with a default handler of
920          * lws_sigint_cb. The handler can be overridden or disabled
921          * by invoking lws_sigint_cfg after creating the context, but
922          * before invoking lws_initloop:
923          */
924         context->use_ev_sigint = 1;
925         context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
926 #endif
927 #ifdef LWS_USE_LIBEVENT
928         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
929          * enable libev mediated SIGINT handling with a default handler of
930          * lws_sigint_cb. The handler can be overridden or disabled
931          * by invoking lws_sigint_cfg after creating the context, but
932          * before invoking lws_initloop:
933          */
934         context->use_ev_sigint = 1;
935         context->lws_event_sigint_cb = &lws_event_sigint_cb;
936 #endif /* LWS_USE_LIBEVENT */
937
938         lwsl_info(" mem: context:         %5lu bytes (%ld ctx + (%ld thr x %d))\n",
939                   (long)sizeof(struct lws_context) +
940                   (context->count_threads * context->pt_serv_buf_size),
941                   (long)sizeof(struct lws_context),
942                   (long)context->count_threads,
943                   context->pt_serv_buf_size);
944
945         lwsl_info(" mem: http hdr rsvd:   %5lu bytes (%u thr x (%u + %lu) x %u))\n",
946                     (long)(context->max_http_header_data +
947                      sizeof(struct allocated_headers)) *
948                     context->max_http_header_pool * context->count_threads,
949                     context->count_threads,
950                     context->max_http_header_data,
951                     (long)sizeof(struct allocated_headers),
952                     context->max_http_header_pool);
953         n = sizeof(struct lws_pollfd) * context->count_threads *
954             context->fd_limit_per_thread;
955         context->pt[0].fds = lws_zalloc(n);
956         if (context->pt[0].fds == NULL) {
957                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
958                 goto bail;
959         }
960         lwsl_info(" mem: pollfd map:      %5u\n", n);
961
962         if (info->server_string) {
963                 context->server_string = info->server_string;
964                 context->server_string_len = (short)
965                                 strlen(context->server_string);
966         }
967
968 #if LWS_MAX_SMP > 1
969         /* each thread serves his own chunk of fds */
970         for (n = 1; n < (int)info->count_threads; n++)
971                 context->pt[n].fds = context->pt[n - 1].fds +
972                                      context->fd_limit_per_thread;
973 #endif
974
975         if (lws_plat_init(context, info))
976                 goto bail;
977
978         lws_context_init_ssl_library(info);
979
980         context->user_space = info->user;
981
982         /*
983          * if he's not saying he'll make his own vhosts later then act
984          * compatibly and make a default vhost using the data in the info
985          */
986         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
987                 if (!lws_create_vhost(context, info)) {
988                         lwsl_err("Failed to create default vhost\n");
989                         return NULL;
990                 }
991
992         lws_context_init_extensions(info, context);
993
994         lwsl_notice(" mem: per-conn:        %5lu bytes + protocol rx buf\n",
995                     (unsigned long)sizeof(struct lws));
996
997         strcpy(context->canonical_hostname, "unknown");
998         lws_server_get_canonical_hostname(context, info);
999
1000         context->uid = info->uid;
1001         context->gid = info->gid;
1002
1003 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
1004         memcpy(context->caps, info->caps, sizeof(context->caps));
1005         context->count_caps = info->count_caps;
1006 #endif
1007
1008         /*
1009          * drop any root privs for this process
1010          * to listen on port < 1023 we would have needed root, but now we are
1011          * listening, we don't want the power for anything else
1012          */
1013         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
1014                 lws_plat_drop_app_privileges(info);
1015
1016         /*
1017          * give all extensions a chance to create any per-context
1018          * allocations they need
1019          */
1020         if (info->port != CONTEXT_PORT_NO_LISTEN) {
1021                 if (lws_ext_cb_all_exts(context, NULL,
1022                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
1023                         goto bail;
1024         } else
1025                 if (lws_ext_cb_all_exts(context, NULL,
1026                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
1027                         goto bail;
1028
1029         return context;
1030
1031 bail:
1032         lws_context_destroy(context);
1033         return NULL;
1034 }
1035
1036 LWS_VISIBLE LWS_EXTERN void
1037 lws_context_deprecate(struct lws_context *context, lws_reload_func cb)
1038 {
1039         struct lws_vhost *vh = context->vhost_list, *vh1;
1040         struct lws *wsi;
1041
1042         /*
1043          * "deprecation" means disable the context from accepting any new
1044          * connections and free up listen sockets to be used by a replacement
1045          * context.
1046          *
1047          * Otherwise the deprecated context remains operational, until its
1048          * number of connected sockets falls to zero, when it is deleted.
1049          */
1050
1051         /* for each vhost, close his listen socket */
1052
1053         while (vh) {
1054                 wsi = vh->lserv_wsi;
1055                 if (wsi) {
1056                         wsi->socket_is_permanently_unusable = 1;
1057                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1058                         wsi->context->deprecation_pending_listen_close_count++;
1059                         /*
1060                          * other vhosts can share the listen port, they
1061                          * point to the same wsi.  So zap those too.
1062                          */
1063                         vh1 = context->vhost_list;
1064                         while (vh1) {
1065                                 if (vh1->lserv_wsi == wsi)
1066                                         vh1->lserv_wsi = NULL;
1067                                 vh1 = vh1->vhost_next;
1068                         }
1069                 }
1070                 vh = vh->vhost_next;
1071         }
1072
1073         context->deprecated = 1;
1074         context->deprecation_cb = cb;
1075 }
1076
1077 LWS_VISIBLE LWS_EXTERN int
1078 lws_context_is_deprecated(struct lws_context *context)
1079 {
1080         return context->deprecated;
1081 }
1082
1083 LWS_VISIBLE void
1084 lws_context_destroy2(struct lws_context *context);
1085
1086
1087 static void
1088 lws_vhost_destroy1(struct lws_vhost *vh)
1089 {
1090         const struct lws_protocols *protocol = NULL;
1091         struct lws_context_per_thread *pt;
1092         int n, m = vh->context->count_threads;
1093         struct lws_context *context = vh->context;
1094         struct lws wsi;
1095
1096         lwsl_notice("%s\n", __func__);
1097
1098         if (vh->being_destroyed)
1099                 return;
1100
1101         vh->being_destroyed = 1;
1102
1103         /*
1104          * Are there other vhosts that are piggybacking on our listen socket?
1105          * If so we need to hand the listen socket off to one of the others
1106          * so it will remain open.  If not, leave it attached to the closing
1107          * vhost and it will get closed.
1108          */
1109
1110         if (vh->lserv_wsi)
1111                 lws_start_foreach_ll(struct lws_vhost *, v, context->vhost_list) {
1112                         if (v != vh &&
1113                             !v->being_destroyed &&
1114                             v->listen_port == vh->listen_port &&
1115                             ((!v->iface && !vh->iface) ||
1116                             (v->iface && vh->iface &&
1117                             !strcmp(v->iface, vh->iface)))) {
1118                                 /*
1119                                  * this can only be a listen wsi, which is
1120                                  * restricted... it has no protocol or other
1121                                  * bindings or states.  So we can simply
1122                                  * swap it to a vhost that has the same
1123                                  * iface + port, but is not closing.
1124                                  */
1125                                 assert(v->lserv_wsi == NULL);
1126                                 v->lserv_wsi = vh->lserv_wsi;
1127                                 vh->lserv_wsi = NULL;
1128                                 v->lserv_wsi->vhost = v;
1129
1130                                 lwsl_notice("%s: listen skt from %s to %s\n",
1131                                             __func__, vh->name, v->name);
1132                                 break;
1133                         }
1134                 } lws_end_foreach_ll(v, vhost_next);
1135
1136         /*
1137          * Forcibly close every wsi assoicated with this vhost.  That will
1138          * include the listen socket if it is still associated with the closing
1139          * vhost.
1140          */
1141
1142         while (m--) {
1143                 pt = &context->pt[m];
1144
1145                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
1146                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
1147                         if (!wsi)
1148                                 continue;
1149                         if (wsi->vhost != vh)
1150                                 continue;
1151
1152                         lws_close_free_wsi(wsi,
1153                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
1154                                 /* no protocol close */);
1155                         n--;
1156                 }
1157         }
1158
1159         /*
1160          * let the protocols destroy the per-vhost protocol objects
1161          */
1162
1163         memset(&wsi, 0, sizeof(wsi));
1164         wsi.context = vh->context;
1165         wsi.vhost = vh;
1166         protocol = vh->protocols;
1167         if (protocol) {
1168                 n = 0;
1169                 while (n < vh->count_protocols) {
1170                         wsi.protocol = protocol;
1171                         protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
1172                                            NULL, NULL, 0);
1173                         protocol++;
1174                         n++;
1175                 }
1176         }
1177
1178         /*
1179          * remove vhost from context list of vhosts
1180          */
1181
1182         lws_start_foreach_llp(struct lws_vhost **, pv, context->vhost_list) {
1183                 if (*pv == vh) {
1184                         *pv = vh->vhost_next;
1185                         break;
1186                 }
1187         } lws_end_foreach_llp(pv, vhost_next);
1188
1189         /* add ourselves to the pending destruction list */
1190
1191         vh->vhost_next = vh->context->vhost_pending_destruction_list;
1192         vh->context->vhost_pending_destruction_list = vh;
1193 }
1194
1195 static void
1196 lws_vhost_destroy2(struct lws_vhost *vh)
1197 {
1198         const struct lws_protocols *protocol = NULL;
1199         struct lws_context *context = vh->context;
1200         struct lws_deferred_free *df;
1201         int n;
1202
1203         lwsl_notice("%s: %p\n", __func__, vh);
1204
1205         /* if we are still on deferred free list, remove ourselves */
1206
1207         lws_start_foreach_llp(struct lws_deferred_free **, pdf, context->deferred_free_list) {
1208                 if ((*pdf)->payload == vh) {
1209                         df = *pdf;
1210                         *pdf = df->next;
1211                         lws_free(df);
1212                         break;
1213                 }
1214         } lws_end_foreach_llp(pdf, next);
1215
1216         /* remove ourselves from the pending destruction list */
1217
1218         lws_start_foreach_llp(struct lws_vhost **, pv, context->vhost_pending_destruction_list) {
1219                 if ((*pv) == vh) {
1220                         *pv = (*pv)->vhost_next;
1221                         break;
1222                 }
1223         } lws_end_foreach_llp(pv, vhost_next);
1224
1225         /*
1226          * Free all the allocations associated with the vhost
1227          */
1228
1229         protocol = vh->protocols;
1230         if (protocol) {
1231                 n = 0;
1232                 while (n < vh->count_protocols) {
1233                         if (vh->protocol_vh_privs &&
1234                             vh->protocol_vh_privs[n]) {
1235                                 lws_free(vh->protocol_vh_privs[n]);
1236                                 vh->protocol_vh_privs[n] = NULL;
1237                         }
1238                         protocol++;
1239                         n++;
1240                 }
1241         }
1242         if (vh->protocol_vh_privs)
1243                 lws_free(vh->protocol_vh_privs);
1244         lws_ssl_SSL_CTX_destroy(vh);
1245         lws_free(vh->same_vh_protocol_list);
1246 #ifdef LWS_WITH_PLUGINS
1247         if (LWS_LIBUV_ENABLED(context)) {
1248                 if (context->plugin_list)
1249                         lws_free((void *)vh->protocols);
1250         } else
1251 #endif
1252         {
1253                 if (context->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
1254                         lws_free((void *)vh->protocols);
1255         }
1256
1257 #ifdef LWS_WITH_PLUGINS
1258 #ifndef LWS_NO_EXTENSIONS
1259         if (context->plugin_extension_count)
1260                 lws_free((void *)vh->extensions);
1261 #endif
1262 #endif
1263 #ifdef LWS_WITH_ACCESS_LOG
1264         if (vh->log_fd != (int)LWS_INVALID_FILE)
1265                 close(vh->log_fd);
1266 #endif
1267
1268         /*
1269          * although async event callbacks may still come for wsi handles with
1270          * pending close in the case of asycn event library like libuv,
1271          * they do not refer to the vhost.  So it's safe to free.
1272          */
1273
1274         lwsl_notice("  %s: Freeing vhost %p\n", __func__, vh);
1275
1276         memset(vh, 0, sizeof(*vh));
1277         free(vh);
1278 }
1279
1280 int
1281 lws_check_deferred_free(struct lws_context *context, int force)
1282 {
1283         struct lws_deferred_free *df;
1284         time_t now = lws_now_secs();
1285
1286         lws_start_foreach_llp(struct lws_deferred_free **, pdf, context->deferred_free_list) {
1287                 if (now > (*pdf)->deadline || force) {
1288                         df = *pdf;
1289                         *pdf = df->next;
1290                         /* finalize vh destruction */
1291                         lwsl_notice("doing deferred vh %p destroy\n", df->payload);
1292                         lws_vhost_destroy2(df->payload);
1293                         lws_free(df);
1294                         continue; /* after deletion we already point to next */
1295                 }
1296         } lws_end_foreach_llp(pdf, next);
1297
1298         return 0;
1299 }
1300
1301 LWS_VISIBLE void
1302 lws_vhost_destroy(struct lws_vhost *vh)
1303 {
1304         struct lws_deferred_free *df = malloc(sizeof(*df));
1305
1306         if (!df)
1307                 return;
1308
1309         lws_vhost_destroy1(vh);
1310
1311         /* part 2 is deferred to allow all the handle closes to complete */
1312
1313         df->next = vh->context->deferred_free_list;
1314         df->deadline = lws_now_secs() + 5;
1315         df->payload = vh;
1316         vh->context->deferred_free_list = df;
1317 }
1318
1319 LWS_VISIBLE void
1320 lws_context_destroy(struct lws_context *context)
1321 {
1322         struct lws_context_per_thread *pt;
1323         struct lws_vhost *vh = NULL;
1324         struct lws wsi;
1325         int n, m;
1326
1327         if (!context) {
1328                 lwsl_notice("%s: ctx %p\n", __func__, context);
1329                 return;
1330         }
1331         if (context->being_destroyed1) {
1332                 lwsl_notice("%s: ctx %p: already being destroyed\n", __func__, context);
1333                 return;
1334         }
1335
1336         lwsl_notice("%s: ctx %p\n", __func__, context);
1337
1338         m = context->count_threads;
1339         context->being_destroyed = 1;
1340         context->being_destroyed1 = 1;
1341
1342         memset(&wsi, 0, sizeof(wsi));
1343         wsi.context = context;
1344
1345 #ifdef LWS_LATENCY
1346         if (context->worst_latency_info[0])
1347                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
1348 #endif
1349
1350         while (m--) {
1351                 pt = &context->pt[m];
1352
1353                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
1354                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
1355                         if (!wsi)
1356                                 continue;
1357
1358                         lws_close_free_wsi(wsi,
1359                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
1360                                 /* no protocol close */);
1361                         n--;
1362                 }
1363                 lws_pt_mutex_destroy(pt);
1364         }
1365
1366         /*
1367          * give all extensions a chance to clean up any per-context
1368          * allocations they might have made
1369          */
1370
1371         n = lws_ext_cb_all_exts(context, NULL,
1372                                 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
1373
1374         n = lws_ext_cb_all_exts(context, NULL,
1375                                 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
1376
1377         /*
1378          * inform all the protocols that they are done and will have no more
1379          * callbacks.
1380          *
1381          * We can't free things until after the event loop shuts down.
1382          */
1383         if (context->protocol_init_done)
1384                 vh = context->vhost_list;
1385         while (vh) {
1386                 lws_vhost_destroy1(vh);
1387                 vh = vh->vhost_next;
1388         }
1389
1390         for (n = 0; n < context->count_threads; n++) {
1391                 pt = &context->pt[n];
1392
1393                 lws_libev_destroyloop(context, n);
1394                 lws_libuv_destroyloop(context, n);
1395                 lws_libevent_destroyloop(context, n);
1396
1397                 lws_free_set_NULL(context->pt[n].serv_buf);
1398                 if (pt->ah_pool)
1399                         lws_free(pt->ah_pool);
1400                 if (pt->http_header_data)
1401                         lws_free(pt->http_header_data);
1402         }
1403         lws_plat_context_early_destroy(context);
1404
1405         if (context->pt[0].fds)
1406                 lws_free_set_NULL(context->pt[0].fds);
1407
1408         if (!LWS_LIBUV_ENABLED(context))
1409                 lws_context_destroy2(context);
1410 }
1411
1412 /*
1413  * call the second one after the event loop has been shut down cleanly
1414  */
1415
1416 LWS_VISIBLE void
1417 lws_context_destroy2(struct lws_context *context)
1418 {
1419         struct lws_vhost *vh = NULL, *vh1;
1420
1421         lwsl_notice("%s: ctx %p\n", __func__, context);
1422
1423         /*
1424          * free all the per-vhost allocations
1425          */
1426
1427         vh = context->vhost_list;
1428         while (vh) {
1429                 vh1 = vh->vhost_next;
1430                 lws_vhost_destroy2(vh);
1431                 vh = vh1;
1432         }
1433
1434         /* remove ourselves from the pending destruction list */
1435
1436         while (context->vhost_pending_destruction_list)
1437                 /* removes itself from list */
1438                 lws_vhost_destroy2(context->vhost_pending_destruction_list);
1439
1440
1441         lws_stats_log_dump(context);
1442
1443         lws_ssl_context_destroy(context);
1444         lws_plat_context_late_destroy(context);
1445
1446         if (context->external_baggage_free_on_destroy)
1447                 free(context->external_baggage_free_on_destroy);
1448
1449         lws_check_deferred_free(context, 1);
1450
1451         lws_free(context);
1452 }