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