add protocol plugin for post demo
[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                 return NULL;
72
73         vhost->protocol_vh_privs[n] = lws_zalloc(size);
74         return vhost->protocol_vh_privs[n];
75 }
76
77 LWS_VISIBLE void *
78 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot)
79 {
80         int n = 0;
81
82         if (!vhost->protocol_vh_privs)
83                 return NULL;
84
85         while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
86                 n++;
87
88         if (n == vhost->count_protocols) {
89                 lwsl_err("%s: unknown protocol %p\n", __func__, prot);
90                 return NULL;
91         }
92
93         return vhost->protocol_vh_privs[n];
94 }
95
96 static const struct lws_protocol_vhost_options *
97 lws_vhost_protocol_options(struct lws_vhost *vh, const char *name)
98 {
99         const struct lws_protocol_vhost_options *pvo = vh->pvo;
100
101         while (pvo) {
102                 // lwsl_notice("%s: '%s' '%s'\n", __func__, pvo->name, name);
103                 if (!strcmp(pvo->name, name))
104                         return pvo;
105                 pvo = pvo->next;
106         }
107
108         return NULL;
109 }
110
111 int
112 lws_protocol_init(struct lws_context *context)
113 {
114         struct lws_vhost *vh = context->vhost_list;
115         const struct lws_protocol_vhost_options *pvo, *pvo1;
116         struct lws wsi;
117         int n;
118
119         memset(&wsi, 0, sizeof(wsi));
120         wsi.context = context;
121
122         lwsl_notice("%s\n", __func__);
123
124         while (vh) {
125                 wsi.vhost = vh;
126
127                 /* initialize supported protocols on this vhost */
128
129                 for (n = 0; n < vh->count_protocols; n++) {
130                         wsi.protocol = &vh->protocols[n];
131
132                         pvo = lws_vhost_protocol_options(vh,
133                                                          vh->protocols[n].name);
134                         if (pvo) {
135                                 /*
136                                  * linked list of options specific to
137                                  * vh + protocol
138                                  */
139                                 pvo1 = pvo;
140                                 pvo = pvo1->options;
141
142                                 while (pvo) {
143                                         lwsl_notice("    vh %s prot %s opt %s\n",
144                                                         vh->name,
145                                                         vh->protocols[n].name,
146                                                         pvo->name);
147
148                                         if (!strcmp(pvo->name, "default")) {
149                                                 lwsl_notice("Setting default "
150                                                    "protocol for vh %s to %s\n",
151                                                    vh->name,
152                                                    vh->protocols[n].name);
153                                                 vh->default_protocol_index = n;
154                                         }
155                                         pvo = pvo->next;
156                                 }
157
158                                 pvo = pvo1->options;
159                         }
160
161                         /*
162                          * inform all the protocols that they are doing their one-time
163                          * initialization if they want to.
164                          *
165                          * NOTE the wsi is all zeros except for the context, vh and
166                          * protocol ptrs so lws_get_context(wsi) etc can work
167                          */
168                         vh->protocols[n].callback(&wsi,
169                                 LWS_CALLBACK_PROTOCOL_INIT, NULL,
170                                 (void *)pvo, 0);
171                 }
172
173                 vh = vh->vhost_next;
174         }
175
176         context->protocol_init_done = 1;
177
178         return 0;
179 }
180
181 static int callback_http_dummy(
182                 struct lws *wsi, enum lws_callback_reasons reason, void *user,
183                   void *in, size_t len)
184 {
185         return 0;
186 }
187
188 /* list of supported protocols and callbacks */
189
190 static const struct lws_protocols protocols_dummy[] = {
191         /* first protocol must always be HTTP handler */
192
193         {
194                 "http-only",            /* name */
195                 callback_http_dummy,            /* callback */
196                 0,      /* per_session_data_size */
197                 0,                      /* max frame size / rx buffer */
198         },
199         /*
200          * the other protocols are provided by lws plugins
201          */
202         { NULL, NULL, 0, 0 } /* terminator */
203 };
204
205 LWS_VISIBLE struct lws_vhost *
206 lws_create_vhost(struct lws_context *context,
207                  struct lws_context_creation_info *info)
208 {
209         struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
210                          **vh1 = &context->vhost_list;
211         const struct lws_http_mount *mounts;
212 #ifdef LWS_WITH_PLUGINS
213         struct lws_plugin *plugin = context->plugin_list;
214         struct lws_protocols *lwsp;
215         int m, n, f = !info->pvo;
216 #endif
217         char *p;
218
219         if (!vh)
220                 return NULL;
221
222         if (!info->protocols)
223                 info->protocols = &protocols_dummy[0];
224
225         vh->context = context;
226         if (!info->vhost_name)
227                 vh->name = "default";
228         else
229                 vh->name = info->vhost_name;
230
231         vh->iface = info->iface;
232         for (vh->count_protocols = 0;
233              info->protocols[vh->count_protocols].callback;
234              vh->count_protocols++)
235                 ;
236
237         vh->options = info->options;
238         vh->pvo = info->pvo;
239         vh->keepalive_timeout = info->keepalive_timeout;
240
241 #ifdef LWS_WITH_PLUGINS
242         if (plugin) {
243                 /*
244                  * give the vhost a unified list of protocols including the
245                  * ones that came from plugins
246                  */
247                 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
248                                            (vh->count_protocols +
249                                            context->plugin_protocol_count + 1));
250                 if (!lwsp)
251                         return NULL;
252
253                 m = vh->count_protocols;
254                 memcpy(lwsp, info->protocols,
255                        sizeof(struct lws_protocols) * m);
256
257                 /* for compatibility, all protocols enabled on vhost if only
258                  * the default vhost exists.  Otherwise only vhosts who ask
259                  * for a protocol get it enabled.
260                  */
261
262                 if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
263                         f = 0;
264
265                 while (plugin) {
266                         for (n = 0; n < plugin->caps.count_protocols; n++) {
267                                 /*
268                                  * for compatibility's sake, no pvo implies
269                                  * allow all protocols
270                                  */
271                                 if (f || lws_vhost_protocol_options(vh,
272                                     plugin->caps.protocols[n].name)) {
273                                         memcpy(&lwsp[m],
274                                                &plugin->caps.protocols[n],
275                                                sizeof(struct lws_protocols));
276                                         m++;
277                                         vh->count_protocols++;
278                                 }
279                         }
280                         plugin = plugin->list;
281                 }
282                 vh->protocols = lwsp;
283         } else
284 #endif
285                 vh->protocols = info->protocols;
286
287         vh->same_vh_protocol_list = (struct lws **)
288                         lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
289
290         vh->mount_list = info->mounts;
291
292 #ifdef LWS_USE_UNIX_SOCK
293         if (LWS_UNIX_SOCK_ENABLED(context)) {
294                 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
295                                 vh->name, info->iface, vh->count_protocols);
296         } else
297 #endif
298         lwsl_notice("Creating Vhost '%s' port %d, %d protocols\n",
299                         vh->name, info->port, vh->count_protocols);
300
301         mounts = info->mounts;
302         while (mounts) {
303                 lwsl_notice("   mounting %s%s to %s\n",
304                                 mount_protocols[mounts->origin_protocol],
305                                 mounts->origin, mounts->mountpoint);
306                 mounts = mounts->mount_next;
307         }
308
309 #ifndef LWS_NO_EXTENSIONS
310 #ifdef LWS_WITH_PLUGINS
311         if (context->plugin_extension_count) {
312
313                 m = 0;
314                 while (info->extensions && info->extensions[m].callback)
315                         m++;
316
317                 /*
318                  * give the vhost a unified list of extensions including the
319                  * ones that came from plugins
320                  */
321                 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
322                                            (m +
323                                            context->plugin_extension_count + 1));
324                 if (!vh->extensions)
325                         return NULL;
326
327                 memcpy((struct lws_extension *)vh->extensions, info->extensions,
328                        sizeof(struct lws_extension) * m);
329                 plugin = context->plugin_list;
330                 while (plugin) {
331                         memcpy((struct lws_extension *)&vh->extensions[m],
332                                 plugin->caps.extensions,
333                                sizeof(struct lws_extension) *
334                                plugin->caps.count_extensions);
335                         m += plugin->caps.count_extensions;
336                         plugin = plugin->list;
337                 }
338         } else
339 #endif
340                 vh->extensions = info->extensions;
341 #endif
342
343         vh->listen_port = info->port;
344         vh->http_proxy_port = 0;
345         vh->http_proxy_address[0] = '\0';
346
347         /* either use proxy from info, or try get it from env var */
348
349         if (info->http_proxy_address) {
350                 /* override for backwards compatibility */
351                 if (info->http_proxy_port)
352                         vh->http_proxy_port = info->http_proxy_port;
353                 lws_set_proxy(vh, info->http_proxy_address);
354         } else {
355 #ifdef LWS_HAVE_GETENV
356                 p = getenv("http_proxy");
357                 if (p)
358                         lws_set_proxy(vh, p);
359 #endif
360         }
361
362         vh->ka_time = info->ka_time;
363         vh->ka_interval = info->ka_interval;
364         vh->ka_probes = info->ka_probes;
365
366         if (vh->options & LWS_SERVER_OPTION_STS)
367                 lwsl_notice("   STS enabled\n");
368
369 #ifdef LWS_WITH_ACCESS_LOG
370         if (info->log_filepath) {
371                 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
372                 if (vh->log_fd == LWS_INVALID_FILE) {
373                         lwsl_err("unable to open log filepath %s\n",
374                                  info->log_filepath);
375                         goto bail;
376                 }
377                 if (context->uid != -1)
378                         if (chown(info->log_filepath, context->uid,
379                                   context->gid) == -1)
380                                 lwsl_err("unable to chown log file %s\n",
381                                                 info->log_filepath);
382         } else
383                 vh->log_fd = LWS_INVALID_FILE;
384 #endif
385
386         if (lws_context_init_server_ssl(info, vh))
387                 goto bail;
388
389         if (lws_context_init_client_ssl(info, vh))
390                 goto bail;
391
392         if (lws_context_init_server(info, vh))
393                 goto bail;
394
395         while (1) {
396                 if (!(*vh1)) {
397                         *vh1 = vh;
398                         break;
399                 }
400                 vh1 = &(*vh1)->vhost_next;
401         };
402
403         return vh;
404
405 bail:
406         lws_free(vh);
407
408         return NULL;
409 }
410
411 /**
412  * lws_create_context() - Create the websocket handler
413  * @info:       pointer to struct with parameters
414  *
415  *      This function creates the listening socket (if serving) and takes care
416  *      of all initialization in one step.
417  *
418  *      After initialization, it returns a struct lws_context * that
419  *      represents this server.  After calling, user code needs to take care
420  *      of calling lws_service() with the context pointer to get the
421  *      server's sockets serviced.  This must be done in the same process
422  *      context as the initialization call.
423  *
424  *      The protocol callback functions are called for a handful of events
425  *      including http requests coming in, websocket connections becoming
426  *      established, and data arriving; it's also called periodically to allow
427  *      async transmission.
428  *
429  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
430  *      at that time websocket protocol has not been negotiated.  Other
431  *      protocols after the first one never see any HTTP callack activity.
432  *
433  *      The server created is a simple http server by default; part of the
434  *      websocket standard is upgrading this http connection to a websocket one.
435  *
436  *      This allows the same server to provide files like scripts and favicon /
437  *      images or whatever over http and dynamic data over websockets all in
438  *      one place; they're all handled in the user callback.
439  */
440 LWS_VISIBLE struct lws_context *
441 lws_create_context(struct lws_context_creation_info *info)
442 {
443         struct lws_context *context = NULL;
444         struct lws wsi;
445 #ifndef LWS_NO_DAEMONIZE
446         int pid_daemon = get_daemonize_pid();
447 #endif
448         int n, m;
449 #if defined(__ANDROID__)
450         struct rlimit rt;
451 #endif
452
453         lwsl_notice("Initial logging level %d\n", log_level);
454         lwsl_notice("Libwebsockets version: %s\n", library_version);
455 #if LWS_POSIX
456 #ifdef LWS_USE_IPV6
457         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
458                 lwsl_notice("IPV6 compiled in and enabled\n");
459         else
460                 lwsl_notice("IPV6 compiled in but disabled\n");
461 #else
462         lwsl_notice("IPV6 not compiled in\n");
463 #endif
464         lws_feature_status_libev(info);
465         lws_feature_status_libuv(info);
466 #endif
467         lwsl_info(" LWS_DEF_HEADER_LEN    : %u\n", LWS_DEF_HEADER_LEN);
468         lwsl_info(" LWS_MAX_PROTOCOLS     : %u\n", LWS_MAX_PROTOCOLS);
469         lwsl_info(" LWS_MAX_SMP           : %u\n", LWS_MAX_SMP);
470         lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
471         lwsl_info(" sizeof (*info)        : %u\n", sizeof(*info));
472 #if LWS_POSIX
473         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
474 #endif
475         if (lws_plat_context_early_init())
476                 return NULL;
477
478         context = lws_zalloc(sizeof(struct lws_context));
479         if (!context) {
480                 lwsl_err("No memory for websocket context\n");
481                 return NULL;
482         }
483
484         context->time_up = time(NULL);
485 #ifndef LWS_NO_DAEMONIZE
486         if (pid_daemon) {
487                 context->started_with_parent = pid_daemon;
488                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
489         }
490 #endif
491 #if defined(__ANDROID__)
492                 n = getrlimit ( RLIMIT_NOFILE,&rt);
493                 if (-1 == n) {
494                         lwsl_err("Get RLIMIT_NOFILE failed!\n");
495                         return NULL;
496                 }
497                 context->max_fds = rt.rlim_cur;
498 #else
499                 context->max_fds = getdtablesize();
500 #endif
501
502         if (info->count_threads)
503                 context->count_threads = info->count_threads;
504         else
505                 context->count_threads = 1;
506
507         if (context->count_threads > LWS_MAX_SMP)
508                 context->count_threads = LWS_MAX_SMP;
509
510         context->token_limits = info->token_limits;
511
512         context->options = info->options;
513
514         if (info->timeout_secs)
515                 context->timeout_secs = info->timeout_secs;
516         else
517                 context->timeout_secs = AWAITING_TIMEOUT;
518
519         lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
520
521         if (info->max_http_header_data)
522                 context->max_http_header_data = info->max_http_header_data;
523         else
524                 context->max_http_header_data = LWS_DEF_HEADER_LEN;
525         if (info->max_http_header_pool)
526                 context->max_http_header_pool = info->max_http_header_pool;
527         else
528                 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
529
530         /*
531          * Allocate the per-thread storage for scratchpad buffers,
532          * and header data pool
533          */
534         for (n = 0; n < context->count_threads; n++) {
535                 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
536                 if (!context->pt[n].serv_buf) {
537                         lwsl_err("OOM\n");
538                         return NULL;
539                 }
540
541                 context->pt[n].context = context;
542                 context->pt[n].tid = n;
543                 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
544                                                        context->max_http_header_pool);
545                 if (!context->pt[n].http_header_data)
546                         goto bail;
547
548                 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
549                                               context->max_http_header_pool);
550                 for (m = 0; m < context->max_http_header_pool; m++)
551                         context->pt[n].ah_pool[m].data =
552                                 (char *)context->pt[n].http_header_data +
553                                 (m * context->max_http_header_data);
554                 if (!context->pt[n].ah_pool)
555                         goto bail;
556
557                 lws_pt_mutex_init(&context->pt[n]);
558         }
559
560         if (info->fd_limit_per_thread)
561                 context->fd_limit_per_thread = info->fd_limit_per_thread;
562         else
563                 context->fd_limit_per_thread = context->max_fds /
564                                                context->count_threads;
565
566         lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
567                     context->fd_limit_per_thread);
568
569         memset(&wsi, 0, sizeof(wsi));
570         wsi.context = context;
571
572         if (!info->ka_interval && info->ka_time > 0) {
573                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
574                 return NULL;
575         }
576
577 #ifdef LWS_USE_LIBEV
578         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
579          * enable libev mediated SIGINT handling with a default handler of
580          * lws_sigint_cb. The handler can be overridden or disabled
581          * by invoking lws_sigint_cfg after creating the context, but
582          * before invoking lws_initloop:
583          */
584         context->use_ev_sigint = 1;
585         context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
586 #endif /* LWS_USE_LIBEV */
587 #ifdef LWS_USE_LIBUV
588         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
589          * enable libev mediated SIGINT handling with a default handler of
590          * lws_sigint_cb. The handler can be overridden or disabled
591          * by invoking lws_sigint_cfg after creating the context, but
592          * before invoking lws_initloop:
593          */
594         context->use_ev_sigint = 1;
595         context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
596 #endif
597
598         lwsl_info(" mem: context:         %5u bytes (%d ctx + (%d thr x %d))\n",
599                   sizeof(struct lws_context) +
600                   (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
601                   sizeof(struct lws_context),
602                   context->count_threads,
603                   LWS_MAX_SOCKET_IO_BUF);
604
605         lwsl_info(" mem: http hdr rsvd:   %5u bytes (%u thr x (%u + %u) x %u))\n",
606                     (context->max_http_header_data +
607                      sizeof(struct allocated_headers)) *
608                     context->max_http_header_pool * context->count_threads,
609                     context->count_threads,
610                     context->max_http_header_data,
611                     sizeof(struct allocated_headers),
612                     context->max_http_header_pool);
613         n = sizeof(struct lws_pollfd) * context->count_threads *
614             context->fd_limit_per_thread;
615         context->pt[0].fds = lws_zalloc(n);
616         if (context->pt[0].fds == NULL) {
617                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
618                 goto bail;
619         }
620         lwsl_info(" mem: pollfd map:      %5u\n", n);
621
622         if (info->server_string) {
623                 context->server_string = info->server_string;
624                 context->server_string_len = (short)
625                                 strlen(context->server_string);
626         } else {
627                 context->server_string = "libwebsockets";
628                 context->server_string_len = 13;
629         }
630
631 #if LWS_MAX_SMP > 1
632         /* each thread serves his own chunk of fds */
633         for (n = 1; n < (int)info->count_threads; n++)
634                 context->pt[n].fds = context->pt[n - 1].fds +
635                                      context->fd_limit_per_thread;
636 #endif
637
638         if (lws_plat_init(context, info))
639                 goto bail;
640
641         lws_context_init_ssl_library(info);
642
643         context->user_space = info->user;
644
645         /*
646          * if he's not saying he'll make his own vhosts later then act
647          * compatibly and make a default vhost using the data in the info
648          */
649         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
650                 if (!lws_create_vhost(context, info)) {
651                         lwsl_err("Failed to create default vhost\n");
652                         return NULL;
653                 }
654
655         lws_context_init_extensions(info, context);
656
657         lwsl_notice(" mem: per-conn:        %5u bytes + protocol rx buf\n",
658                     sizeof(struct lws));
659
660         strcpy(context->canonical_hostname, "unknown");
661         lws_server_get_canonical_hostname(context, info);
662
663         context->uid = info->uid;
664         context->gid = info->gid;
665
666         /*
667          * drop any root privs for this process
668          * to listen on port < 1023 we would have needed root, but now we are
669          * listening, we don't want the power for anything else
670          */
671         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
672                 lws_plat_drop_app_privileges(info);
673
674         /*
675          * give all extensions a chance to create any per-context
676          * allocations they need
677          */
678         if (info->port != CONTEXT_PORT_NO_LISTEN) {
679                 if (lws_ext_cb_all_exts(context, NULL,
680                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
681                         goto bail;
682         } else
683                 if (lws_ext_cb_all_exts(context, NULL,
684                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
685                         goto bail;
686
687         return context;
688
689 bail:
690         lws_context_destroy(context);
691         return NULL;
692 }
693
694 /**
695  * lws_context_destroy() - Destroy the websocket context
696  * @context:    Websocket context
697  *
698  *      This function closes any active connections and then frees the
699  *      context.  After calling this, any further use of the context is
700  *      undefined.
701  */
702 LWS_VISIBLE void
703 lws_context_destroy(struct lws_context *context)
704 {
705         const struct lws_protocols *protocol = NULL;
706         struct lws_context_per_thread *pt;
707         struct lws_vhost *vh = NULL, *vh1;
708         struct lws wsi;
709         int n, m;
710
711         lwsl_notice("%s\n", __func__);
712
713         if (!context)
714                 return;
715
716         m = context->count_threads;
717         context->being_destroyed = 1;
718
719         memset(&wsi, 0, sizeof(wsi));
720         wsi.context = context;
721
722 #ifdef LWS_LATENCY
723         if (context->worst_latency_info[0])
724                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
725 #endif
726
727         while (m--) {
728                 pt = &context->pt[m];
729
730                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
731                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
732                         if (!wsi)
733                                 continue;
734
735                         lws_close_free_wsi(wsi,
736                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
737                                 /* no protocol close */);
738                         n--;
739                 }
740         }
741         /*
742          * give all extensions a chance to clean up any per-context
743          * allocations they might have made
744          */
745
746         n = lws_ext_cb_all_exts(context, NULL,
747                                 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
748
749         n = lws_ext_cb_all_exts(context, NULL,
750                                 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
751
752         /*
753          * inform all the protocols that they are done and will have no more
754          * callbacks.
755          *
756          * We can't free things until after the event loop shuts down.
757          */
758         if (context->protocol_init_done)
759                 vh = context->vhost_list;
760         while (vh) {
761                 wsi.vhost = vh;
762                 protocol = vh->protocols;
763                 if (protocol) {
764                         n = 0;
765                         while (n < vh->count_protocols) {
766                                 wsi.protocol = protocol;
767                                 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
768                                                    NULL, NULL, 0);
769                                 protocol++;
770                                 n++;
771                         }
772                 }
773
774                 vh = vh->vhost_next;
775         }
776
777         for (n = 0; n < context->count_threads; n++) {
778                 pt = &context->pt[n];
779
780                 lws_libev_destroyloop(context, n);
781                 lws_libuv_destroyloop(context, n);
782
783                 lws_free_set_NULL(context->pt[n].serv_buf);
784                 if (pt->ah_pool)
785                         lws_free(pt->ah_pool);
786                 if (pt->http_header_data)
787                         lws_free(pt->http_header_data);
788         }
789         lws_plat_context_early_destroy(context);
790         lws_ssl_context_destroy(context);
791
792         if (context->pt[0].fds)
793                 lws_free_set_NULL(context->pt[0].fds);
794
795         /* free all the vhost allocations */
796
797         vh = context->vhost_list;
798         while (vh) {
799                 protocol = vh->protocols;
800                 if (protocol) {
801                         n = 0;
802                         while (n < vh->count_protocols) {
803                                 if (vh->protocol_vh_privs &&
804                                     vh->protocol_vh_privs[n]) {
805                                         lws_free(vh->protocol_vh_privs[n]);
806                                         vh->protocol_vh_privs[n] = NULL;
807                                 }
808                                 protocol++;
809                                 n++;
810                         }
811                 }
812                 if (vh->protocol_vh_privs)
813                         lws_free(vh->protocol_vh_privs);
814                 lws_ssl_SSL_CTX_destroy(vh);
815                 lws_free(vh->same_vh_protocol_list);
816 #ifdef LWS_WITH_PLUGINS
817                 if (context->plugin_list)
818                         lws_free((void *)vh->protocols);
819 #ifndef LWS_NO_EXTENSIONS
820                 if (context->plugin_extension_count)
821                         lws_free((void *)vh->extensions);
822 #endif
823 #endif
824 #ifdef LWS_WITH_ACCESS_LOG
825                 if (vh->log_fd != LWS_INVALID_FILE)
826                         close(vh->log_fd);
827 #endif
828
829                 vh1 = vh->vhost_next;
830                 lws_free(vh);
831                 vh = vh1;
832         }
833
834         lws_plat_context_late_destroy(context);
835
836         lws_free(context);
837 }