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