f791ca6afa75e8e2754e3dde0ffdf229ed77d9ba
[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         char buf[128];
224         int n;
225 #endif
226
227         switch (reason) {
228         case LWS_CALLBACK_HTTP:
229 #ifndef LWS_NO_SERVER
230                 if (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL))
231                         return -1;
232
233                 if (lws_http_transaction_completed(wsi))
234 #endif
235                         return -1;
236                 break;
237
238         case LWS_CALLBACK_HTTP_WRITEABLE:
239 #ifdef LWS_WITH_CGI
240                 if (wsi->reason_bf & 1) {
241                         if (lws_cgi_write_split_stdout_headers(wsi) < 0)
242                                 return -1;
243
244                         wsi->reason_bf &= ~1;
245                         break;
246                 }
247 #endif
248
249                 break;
250
251 #ifdef LWS_WITH_CGI
252         /* CGI IO events (POLLIN/OUT) appear here, our default policy is:
253          *
254          *  - POST data goes on subprocess stdin
255          *  - subprocess stdout goes on http via writeable callback
256          *  - subprocess stderr goes to the logs
257          */
258         case LWS_CALLBACK_CGI:
259                 args = (struct lws_cgi_args *)in;
260                 switch (args->ch) { /* which of stdin/out/err ? */
261                 case LWS_STDIN:
262                         /* TBD stdin rx flow control */
263                         break;
264                 case LWS_STDOUT:
265                         wsi->reason_bf |= 1;
266                         /* when writing to MASTER would not block */
267                         lws_callback_on_writable(wsi);
268                         break;
269                 case LWS_STDERR:
270                         n = read(lws_get_socket_fd(args->stdwsi[LWS_STDERR]),
271                                                    buf, sizeof(buf) - 2);
272                         if (n > 0) {
273                                 if (buf[n - 1] != '\n')
274                                         buf[n++] = '\n';
275                                 buf[n] = '\0';
276                                 lwsl_notice("CGI-stderr: %s\n", buf);
277                         }
278                         break;
279                 }
280                 break;
281
282         case LWS_CALLBACK_CGI_TERMINATED:
283                 return -1;
284
285         case LWS_CALLBACK_CGI_STDIN_DATA:  /* POST body for stdin */
286                 args = (struct lws_cgi_args *)in;
287                 args->data[args->len] = '\0';
288                 n = write(lws_get_socket_fd(args->stdwsi[LWS_STDIN]),
289                           args->data, args->len);
290                 if (n < args->len)
291                         lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: "
292                                     "sent %d only %d went", n, args->len);
293                 return n;
294 #endif
295         default:
296                 break;
297         }
298
299         return 0;
300 }
301
302 /* list of supported protocols and callbacks */
303
304 static const struct lws_protocols protocols_dummy[] = {
305         /* first protocol must always be HTTP handler */
306
307         {
308                 "http-only",            /* name */
309                 lws_callback_http_dummy,                /* callback */
310                 0,      /* per_session_data_size */
311                 0,                      /* max frame size / rx buffer */
312                 0, NULL, 0
313         },
314         /*
315          * the other protocols are provided by lws plugins
316          */
317         { NULL, NULL, 0, 0, 0, NULL, 0} /* terminator */
318 };
319
320 #ifdef LWS_PLAT_OPTEE
321 #undef LWS_HAVE_GETENV
322 #endif
323
324 LWS_VISIBLE struct lws_vhost *
325 lws_create_vhost(struct lws_context *context,
326                  struct lws_context_creation_info *info)
327 {
328         struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
329                          **vh1 = &context->vhost_list;
330         const struct lws_http_mount *mounts;
331         const struct lws_protocol_vhost_options *pvo;
332 #ifdef LWS_WITH_PLUGINS
333         struct lws_plugin *plugin = context->plugin_list;
334 #endif
335         struct lws_protocols *lwsp;
336         int m, f = !info->pvo;
337 #ifdef LWS_HAVE_GETENV
338         char *p;
339 #endif
340         int n;
341
342         if (!vh)
343                 return NULL;
344
345         if (!info->protocols)
346                 info->protocols = &protocols_dummy[0];
347
348         vh->context = context;
349         if (!info->vhost_name)
350                 vh->name = "default";
351         else
352                 vh->name = info->vhost_name;
353
354         vh->iface = info->iface;
355         for (vh->count_protocols = 0;
356              info->protocols[vh->count_protocols].callback;
357              vh->count_protocols++)
358                 ;
359
360         vh->options = info->options;
361         vh->pvo = info->pvo;
362         vh->headers = info->headers;
363         if (info->keepalive_timeout)
364                 vh->keepalive_timeout = info->keepalive_timeout;
365         else
366                 vh->keepalive_timeout = 5;
367
368         /*
369          * give the vhost a unified list of protocols including the
370          * ones that came from plugins
371          */
372         lwsp = lws_zalloc(sizeof(struct lws_protocols) *
373                                    (vh->count_protocols +
374                                    context->plugin_protocol_count + 1));
375         if (!lwsp) {
376                 lwsl_err("OOM\n");
377                 return NULL;
378         }
379
380         m = vh->count_protocols;
381         memcpy(lwsp, info->protocols, sizeof(struct lws_protocols) * m);
382
383         /* for compatibility, all protocols enabled on vhost if only
384          * the default vhost exists.  Otherwise only vhosts who ask
385          * for a protocol get it enabled.
386          */
387
388         if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
389                 f = 0;
390         (void)f;
391 #ifdef LWS_WITH_PLUGINS
392         if (plugin) {
393
394                 while (plugin) {
395                         for (n = 0; n < plugin->caps.count_protocols; n++) {
396                                 /*
397                                  * for compatibility's sake, no pvo implies
398                                  * allow all protocols
399                                  */
400                                 if (f || lws_vhost_protocol_options(vh,
401                                     plugin->caps.protocols[n].name)) {
402                                         memcpy(&lwsp[m],
403                                                &plugin->caps.protocols[n],
404                                                sizeof(struct lws_protocols));
405                                         m++;
406                                         vh->count_protocols++;
407                                 }
408                         }
409                         plugin = plugin->list;
410                 }
411         }
412 #endif
413
414         if (
415 #ifdef LWS_WITH_PLUGINS
416             (context->plugin_list) ||
417 #endif
418             info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
419                 vh->protocols = lwsp;
420         else {
421                 vh->protocols = info->protocols;
422                 free(lwsp);
423         }
424
425         vh->same_vh_protocol_list = (struct lws **)
426                         lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
427
428         vh->mount_list = info->mounts;
429
430 #ifdef LWS_USE_UNIX_SOCK
431         if (LWS_UNIX_SOCK_ENABLED(context)) {
432                 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
433                                 vh->name, info->iface, vh->count_protocols);
434         } else
435 #endif
436         lwsl_notice("Creating Vhost '%s' port %d, %d protocols, IPv6 %s\n",
437                         vh->name, info->port, vh->count_protocols, LWS_IPV6_ENABLED(vh) ? "on" : "off");
438
439         mounts = info->mounts;
440         while (mounts) {
441                 lwsl_notice("   mounting %s%s to %s\n",
442                                 mount_protocols[mounts->origin_protocol],
443                                 mounts->origin, mounts->mountpoint);
444
445                 /* convert interpreter protocol names to pointers */
446                 pvo = mounts->interpret;
447                 while (pvo) {
448                         for (n = 0; n < vh->count_protocols; n++)
449                                 if (!strcmp(pvo->value, vh->protocols[n].name)) {
450                                         ((struct lws_protocol_vhost_options *)pvo)->value =
451                                                         (const char *)(long)n;
452                                         break;
453                                 }
454                         if (n == vh->count_protocols)
455                                 lwsl_err("ignoring unknown interpret protocol %s\n", pvo->value);
456                         pvo = pvo->next;
457                 }
458
459                 mounts = mounts->mount_next;
460         }
461
462 #ifndef LWS_NO_EXTENSIONS
463 #ifdef LWS_WITH_PLUGINS
464         if (context->plugin_extension_count) {
465
466                 m = 0;
467                 while (info->extensions && info->extensions[m].callback)
468                         m++;
469
470                 /*
471                  * give the vhost a unified list of extensions including the
472                  * ones that came from plugins
473                  */
474                 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
475                                            (m +
476                                            context->plugin_extension_count + 1));
477                 if (!vh->extensions)
478                         return NULL;
479
480                 memcpy((struct lws_extension *)vh->extensions, info->extensions,
481                        sizeof(struct lws_extension) * m);
482                 plugin = context->plugin_list;
483                 while (plugin) {
484                         memcpy((struct lws_extension *)&vh->extensions[m],
485                                 plugin->caps.extensions,
486                                sizeof(struct lws_extension) *
487                                plugin->caps.count_extensions);
488                         m += plugin->caps.count_extensions;
489                         plugin = plugin->list;
490                 }
491         } else
492 #endif
493                 vh->extensions = info->extensions;
494 #endif
495
496         vh->listen_port = info->port;
497 #if !defined(LWS_WITH_ESP8266)
498         vh->http_proxy_port = 0;
499         vh->http_proxy_address[0] = '\0';
500
501         /* either use proxy from info, or try get it from env var */
502
503         if (info->http_proxy_address) {
504                 /* override for backwards compatibility */
505                 if (info->http_proxy_port)
506                         vh->http_proxy_port = info->http_proxy_port;
507                 lws_set_proxy(vh, info->http_proxy_address);
508         } else {
509 #ifdef LWS_HAVE_GETENV
510                 p = getenv("http_proxy");
511                 if (p)
512                         lws_set_proxy(vh, p);
513 #endif
514         }
515 #endif
516         vh->ka_time = info->ka_time;
517         vh->ka_interval = info->ka_interval;
518         vh->ka_probes = info->ka_probes;
519
520         if (vh->options & LWS_SERVER_OPTION_STS)
521                 lwsl_notice("   STS enabled\n");
522
523 #ifdef LWS_WITH_ACCESS_LOG
524         if (info->log_filepath) {
525                 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
526                 if (vh->log_fd == (int)LWS_INVALID_FILE) {
527                         lwsl_err("unable to open log filepath %s\n",
528                                  info->log_filepath);
529                         goto bail;
530                 }
531 #ifndef WIN32
532                 if (context->uid != -1)
533                         if (chown(info->log_filepath, context->uid,
534                                   context->gid) == -1)
535                                 lwsl_err("unable to chown log file %s\n",
536                                                 info->log_filepath);
537 #endif
538         } else
539                 vh->log_fd = (int)LWS_INVALID_FILE;
540 #endif
541         if (lws_context_init_server_ssl(info, vh))
542                 goto bail;
543         if (lws_context_init_client_ssl(info, vh))
544                 goto bail;
545         if (lws_context_init_server(info, vh)) {
546                 lwsl_err("init server failed\n");
547                 goto bail;
548         }
549
550         while (1) {
551                 if (!(*vh1)) {
552                         *vh1 = vh;
553                         break;
554                 }
555                 vh1 = &(*vh1)->vhost_next;
556         };
557         /* for the case we are adding a vhost much later, after server init */
558
559         if (context->protocol_init_done)
560                 lws_protocol_init(context);
561
562         return vh;
563
564 bail:
565         lws_free(vh);
566
567         return NULL;
568 }
569
570 LWS_VISIBLE int
571 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
572                           struct lws_vhost *vhost)
573 {
574         struct lws_context_creation_info i;
575
576         memcpy(&i, info, sizeof(i));
577         i.port = CONTEXT_PORT_NO_LISTEN;
578
579         return lws_context_init_client_ssl(&i, vhost);
580 }
581
582 LWS_VISIBLE struct lws_context *
583 lws_create_context(struct lws_context_creation_info *info)
584 {
585         struct lws_context *context = NULL;
586         struct lws_plat_file_ops *prev;
587 #ifndef LWS_NO_DAEMONIZE
588         int pid_daemon = get_daemonize_pid();
589 #endif
590         int n, m;
591 #if defined(__ANDROID__)
592         struct rlimit rt;
593 #endif
594
595         lwsl_notice("Initial logging level %d\n", log_level);
596         lwsl_notice("Libwebsockets version: %s\n", library_version);
597 #if defined(GCC_VER)
598         lwsl_notice("Compiled with  %s\n", GCC_VER);
599 #endif
600 #if LWS_POSIX
601 #ifdef LWS_USE_IPV6
602         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
603                 lwsl_notice("IPV6 compiled in and enabled\n");
604         else
605                 lwsl_notice("IPV6 compiled in but disabled\n");
606 #else
607         lwsl_notice("IPV6 not compiled in\n");
608 #endif
609 #if !defined(LWS_PLAT_OPTEE) && !defined(LWS_PLAT_ESP32)
610         lws_feature_status_libev(info);
611         lws_feature_status_libuv(info);
612 #endif
613 #endif
614         lwsl_info(" LWS_DEF_HEADER_LEN    : %u\n", LWS_DEF_HEADER_LEN);
615         lwsl_info(" LWS_MAX_PROTOCOLS     : %u\n", LWS_MAX_PROTOCOLS);
616         lwsl_info(" LWS_MAX_SMP           : %u\n", LWS_MAX_SMP);
617         lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
618         lwsl_info(" sizeof (*info)        : %ld\n", (long)sizeof(*info));
619 #if defined(LWS_WITH_STATS)
620         lwsl_notice(" LWS_WITH_STATS        : on\n");
621 #endif
622 #if LWS_POSIX
623         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
624 #endif
625         if (lws_plat_context_early_init())
626                 return NULL;
627
628         context = lws_zalloc(sizeof(struct lws_context));
629         if (!context) {
630                 lwsl_err("No memory for websocket context\n");
631                 return NULL;
632         }
633         if (info->pt_serv_buf_size)
634                 context->pt_serv_buf_size = info->pt_serv_buf_size;
635         else
636                 context->pt_serv_buf_size = 4096;
637
638         /* default to just the platform fops implementation */
639
640         context->fops_platform.LWS_FOP_OPEN     = _lws_plat_file_open;
641         context->fops_platform.LWS_FOP_CLOSE    = _lws_plat_file_close;
642         context->fops_platform.LWS_FOP_SEEK_CUR = _lws_plat_file_seek_cur;
643         context->fops_platform.LWS_FOP_READ     = _lws_plat_file_read;
644         context->fops_platform.LWS_FOP_WRITE    = _lws_plat_file_write;
645         context->fops_platform.fi[0].sig        = NULL;
646
647         /*
648          *  arrange a linear linked-list of fops starting from context->fops
649          *
650          * platform fops
651          * [ -> fops_zip (copied into context so .next settable) ]
652          * [ -> info->fops ]
653          */
654
655         context->fops = &context->fops_platform;
656         prev = (struct lws_plat_file_ops *)context->fops;
657
658 #if defined(LWS_WITH_ZIP_FOPS)
659         /* make a soft copy so we can set .next */
660         context->fops_zip = fops_zip;
661         prev->next = &context->fops_zip;
662         prev = (struct lws_plat_file_ops *)prev->next;
663 #endif
664
665         /* if user provided fops, tack them on the end of the list */
666         if (info->fops)
667                 prev->next = info->fops;
668
669         context->reject_service_keywords = info->reject_service_keywords;
670         if (info->external_baggage_free_on_destroy)
671                 context->external_baggage_free_on_destroy =
672                         info->external_baggage_free_on_destroy;
673
674         context->time_up = time(NULL);
675
676         context->simultaneous_ssl_restriction = info->simultaneous_ssl_restriction;
677
678 #ifndef LWS_NO_DAEMONIZE
679         if (pid_daemon) {
680                 context->started_with_parent = pid_daemon;
681                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
682         }
683 #endif
684 #if defined(__ANDROID__)
685                 n = getrlimit ( RLIMIT_NOFILE,&rt);
686                 if (-1 == n) {
687                         lwsl_err("Get RLIMIT_NOFILE failed!\n");
688                         return NULL;
689                 }
690                 context->max_fds = rt.rlim_cur;
691 #else
692                 context->max_fds = getdtablesize();
693 #endif
694
695         if (info->count_threads)
696                 context->count_threads = info->count_threads;
697         else
698                 context->count_threads = 1;
699
700         if (context->count_threads > LWS_MAX_SMP)
701                 context->count_threads = LWS_MAX_SMP;
702
703         context->token_limits = info->token_limits;
704
705         context->options = info->options;
706
707         if (info->timeout_secs)
708                 context->timeout_secs = info->timeout_secs;
709         else
710                 context->timeout_secs = AWAITING_TIMEOUT;
711
712         context->ws_ping_pong_interval = info->ws_ping_pong_interval;
713
714         lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
715
716         if (info->max_http_header_data)
717                 context->max_http_header_data = info->max_http_header_data;
718         else
719                 if (info->max_http_header_data2)
720                         context->max_http_header_data =
721                                         info->max_http_header_data2;
722                 else
723                         context->max_http_header_data = LWS_DEF_HEADER_LEN;
724         if (info->max_http_header_pool)
725                 context->max_http_header_pool = info->max_http_header_pool;
726         else
727                 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
728
729         /*
730          * Allocate the per-thread storage for scratchpad buffers,
731          * and header data pool
732          */
733         for (n = 0; n < context->count_threads; n++) {
734                 context->pt[n].serv_buf = lws_zalloc(context->pt_serv_buf_size);
735                 if (!context->pt[n].serv_buf) {
736                         lwsl_err("OOM\n");
737                         return NULL;
738                 }
739
740 #ifdef LWS_USE_LIBUV
741                 context->pt[n].context = context;
742 #endif
743                 context->pt[n].tid = n;
744                 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
745                                                        context->max_http_header_pool);
746                 if (!context->pt[n].http_header_data)
747                         goto bail;
748
749                 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
750                                               context->max_http_header_pool);
751                 for (m = 0; m < context->max_http_header_pool; m++)
752                         context->pt[n].ah_pool[m].data =
753                                 (char *)context->pt[n].http_header_data +
754                                 (m * context->max_http_header_data);
755                 if (!context->pt[n].ah_pool)
756                         goto bail;
757
758                 lws_pt_mutex_init(&context->pt[n]);
759         }
760
761         if (info->fd_limit_per_thread)
762                 context->fd_limit_per_thread = info->fd_limit_per_thread;
763         else
764                 context->fd_limit_per_thread = context->max_fds /
765                                                context->count_threads;
766
767         lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
768                     context->fd_limit_per_thread);
769
770         if (!info->ka_interval && info->ka_time > 0) {
771                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
772                 return NULL;
773         }
774
775 #ifdef LWS_USE_LIBEV
776         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
777          * enable libev mediated SIGINT handling with a default handler of
778          * lws_sigint_cb. The handler can be overridden or disabled
779          * by invoking lws_sigint_cfg after creating the context, but
780          * before invoking lws_initloop:
781          */
782         context->use_ev_sigint = 1;
783         context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
784 #endif /* LWS_USE_LIBEV */
785 #ifdef LWS_USE_LIBUV
786         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
787          * enable libev mediated SIGINT handling with a default handler of
788          * lws_sigint_cb. The handler can be overridden or disabled
789          * by invoking lws_sigint_cfg after creating the context, but
790          * before invoking lws_initloop:
791          */
792         context->use_ev_sigint = 1;
793         context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
794 #endif
795 #ifdef LWS_USE_LIBEVENT
796         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
797          * enable libev mediated SIGINT handling with a default handler of
798          * lws_sigint_cb. The handler can be overridden or disabled
799          * by invoking lws_sigint_cfg after creating the context, but
800          * before invoking lws_initloop:
801          */
802         context->use_ev_sigint = 1;
803         context->lws_event_sigint_cb = &lws_event_sigint_cb;
804 #endif /* LWS_USE_LIBEVENT */
805
806         lwsl_info(" mem: context:         %5lu bytes (%ld ctx + (%ld thr x %d))\n",
807                   (long)sizeof(struct lws_context) +
808                   (context->count_threads * context->pt_serv_buf_size),
809                   (long)sizeof(struct lws_context),
810                   (long)context->count_threads,
811                   context->pt_serv_buf_size);
812
813         lwsl_info(" mem: http hdr rsvd:   %5lu bytes (%u thr x (%u + %lu) x %u))\n",
814                     (long)(context->max_http_header_data +
815                      sizeof(struct allocated_headers)) *
816                     context->max_http_header_pool * context->count_threads,
817                     context->count_threads,
818                     context->max_http_header_data,
819                     (long)sizeof(struct allocated_headers),
820                     context->max_http_header_pool);
821         n = sizeof(struct lws_pollfd) * context->count_threads *
822             context->fd_limit_per_thread;
823         context->pt[0].fds = lws_zalloc(n);
824         if (context->pt[0].fds == NULL) {
825                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
826                 goto bail;
827         }
828         lwsl_info(" mem: pollfd map:      %5u\n", n);
829
830         if (info->server_string) {
831                 context->server_string = info->server_string;
832                 context->server_string_len = (short)
833                                 strlen(context->server_string);
834         }
835
836 #if LWS_MAX_SMP > 1
837         /* each thread serves his own chunk of fds */
838         for (n = 1; n < (int)info->count_threads; n++)
839                 context->pt[n].fds = context->pt[n - 1].fds +
840                                      context->fd_limit_per_thread;
841 #endif
842
843         if (lws_plat_init(context, info))
844                 goto bail;
845
846         lws_context_init_ssl_library(info);
847
848         context->user_space = info->user;
849
850         /*
851          * if he's not saying he'll make his own vhosts later then act
852          * compatibly and make a default vhost using the data in the info
853          */
854         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
855                 if (!lws_create_vhost(context, info)) {
856                         lwsl_err("Failed to create default vhost\n");
857                         return NULL;
858                 }
859
860         lws_context_init_extensions(info, context);
861
862         lwsl_notice(" mem: per-conn:        %5lu bytes + protocol rx buf\n",
863                     (unsigned long)sizeof(struct lws));
864
865         strcpy(context->canonical_hostname, "unknown");
866         lws_server_get_canonical_hostname(context, info);
867
868         context->uid = info->uid;
869         context->gid = info->gid;
870
871         /*
872          * drop any root privs for this process
873          * to listen on port < 1023 we would have needed root, but now we are
874          * listening, we don't want the power for anything else
875          */
876         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
877                 lws_plat_drop_app_privileges(info);
878
879         /*
880          * give all extensions a chance to create any per-context
881          * allocations they need
882          */
883         if (info->port != CONTEXT_PORT_NO_LISTEN) {
884                 if (lws_ext_cb_all_exts(context, NULL,
885                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
886                         goto bail;
887         } else
888                 if (lws_ext_cb_all_exts(context, NULL,
889                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
890                         goto bail;
891
892         return context;
893
894 bail:
895         lws_context_destroy(context);
896         return NULL;
897 }
898
899 LWS_VISIBLE LWS_EXTERN void
900 lws_context_deprecate(struct lws_context *context, lws_reload_func cb)
901 {
902         struct lws_vhost *vh = context->vhost_list, *vh1;
903         struct lws *wsi;
904
905         /*
906          * "deprecation" means disable the context from accepting any new
907          * connections and free up listen sockets to be used by a replacement
908          * context.
909          *
910          * Otherwise the deprecated context remains operational, until its
911          * number of connected sockets falls to zero, when it is deleted.
912          */
913
914         /* for each vhost, close his listen socket */
915
916         while (vh) {
917                 wsi = vh->lserv_wsi;
918                 if (wsi) {
919                         wsi->socket_is_permanently_unusable = 1;
920                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
921                         wsi->context->deprecation_pending_listen_close_count++;
922                         /*
923                          * other vhosts can share the listen port, they
924                          * point to the same wsi.  So zap those too.
925                          */
926                         vh1 = context->vhost_list;
927                         while (vh1) {
928                                 if (vh1->lserv_wsi == wsi)
929                                         vh1->lserv_wsi = NULL;
930                                 vh1 = vh1->vhost_next;
931                         }
932                 }
933                 vh = vh->vhost_next;
934         }
935
936         context->deprecated = 1;
937         context->deprecation_cb = cb;
938 }
939
940 LWS_VISIBLE LWS_EXTERN int
941 lws_context_is_deprecated(struct lws_context *context)
942 {
943         return context->deprecated;
944 }
945
946 LWS_VISIBLE void
947 lws_context_destroy2(struct lws_context *context);
948
949 LWS_VISIBLE void
950 lws_context_destroy(struct lws_context *context)
951 {
952         const struct lws_protocols *protocol = NULL;
953         struct lws_context_per_thread *pt;
954         struct lws_vhost *vh = NULL;
955         struct lws wsi;
956         int n, m;
957
958         if (!context) {
959                 lwsl_notice("%s: ctx %p\n", __func__, context);
960                 return;
961         }
962         if (context->being_destroyed1) {
963                 lwsl_notice("%s: ctx %p: already being destroyed\n", __func__, context);
964                 return;
965         }
966
967         lwsl_notice("%s: ctx %p\n", __func__, context);
968
969         m = context->count_threads;
970         context->being_destroyed = 1;
971         context->being_destroyed1 = 1;
972
973         memset(&wsi, 0, sizeof(wsi));
974         wsi.context = context;
975
976 #ifdef LWS_LATENCY
977         if (context->worst_latency_info[0])
978                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
979 #endif
980
981         while (m--) {
982                 pt = &context->pt[m];
983
984                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
985                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
986                         if (!wsi)
987                                 continue;
988
989                         lws_close_free_wsi(wsi,
990                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
991                                 /* no protocol close */);
992                         n--;
993                 }
994                 lws_pt_mutex_destroy(pt);
995         }
996
997         /*
998          * give all extensions a chance to clean up any per-context
999          * allocations they might have made
1000          */
1001
1002         n = lws_ext_cb_all_exts(context, NULL,
1003                                 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
1004
1005         n = lws_ext_cb_all_exts(context, NULL,
1006                                 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
1007
1008         /*
1009          * inform all the protocols that they are done and will have no more
1010          * callbacks.
1011          *
1012          * We can't free things until after the event loop shuts down.
1013          */
1014         if (context->protocol_init_done)
1015                 vh = context->vhost_list;
1016         while (vh) {
1017                 wsi.vhost = vh;
1018                 protocol = vh->protocols;
1019                 if (protocol) {
1020                         n = 0;
1021                         while (n < vh->count_protocols) {
1022                                 wsi.protocol = protocol;
1023                                 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
1024                                                    NULL, NULL, 0);
1025                                 protocol++;
1026                                 n++;
1027                         }
1028                 }
1029
1030                 vh = vh->vhost_next;
1031         }
1032
1033         for (n = 0; n < context->count_threads; n++) {
1034                 pt = &context->pt[n];
1035
1036                 lws_libev_destroyloop(context, n);
1037                 lws_libuv_destroyloop(context, n);
1038                 lws_libevent_destroyloop(context, n);
1039
1040                 lws_free_set_NULL(context->pt[n].serv_buf);
1041                 if (pt->ah_pool)
1042                         lws_free(pt->ah_pool);
1043                 if (pt->http_header_data)
1044                         lws_free(pt->http_header_data);
1045         }
1046         lws_plat_context_early_destroy(context);
1047
1048         if (context->pt[0].fds)
1049                 lws_free_set_NULL(context->pt[0].fds);
1050
1051         if (!LWS_LIBUV_ENABLED(context))
1052                 lws_context_destroy2(context);
1053 }
1054
1055 /*
1056  * call the second one after the event loop has been shut down cleanly
1057  */
1058
1059 LWS_VISIBLE void
1060 lws_context_destroy2(struct lws_context *context)
1061 {
1062         const struct lws_protocols *protocol = NULL;
1063         struct lws_vhost *vh = NULL, *vh1;
1064         int n;
1065
1066         lwsl_notice("%s: ctx %p\n", __func__, context);
1067
1068         /*
1069          * free all the per-vhost allocations
1070          */
1071
1072         vh = context->vhost_list;
1073         while (vh) {
1074                 protocol = vh->protocols;
1075                 if (protocol) {
1076                         n = 0;
1077                         while (n < vh->count_protocols) {
1078                                 if (vh->protocol_vh_privs &&
1079                                     vh->protocol_vh_privs[n]) {
1080                                         // lwsl_notice("   %s: freeing per-vhost protocol data %p\n", __func__, vh->protocol_vh_privs[n]);
1081                                         lws_free(vh->protocol_vh_privs[n]);
1082                                         vh->protocol_vh_privs[n] = NULL;
1083                                 }
1084                                 protocol++;
1085                                 n++;
1086                         }
1087                 }
1088                 if (vh->protocol_vh_privs)
1089                         lws_free(vh->protocol_vh_privs);
1090                 lws_ssl_SSL_CTX_destroy(vh);
1091                 lws_free(vh->same_vh_protocol_list);
1092 #ifdef LWS_WITH_PLUGINS
1093                 if (context->plugin_list)
1094                         lws_free((void *)vh->protocols);
1095 #else
1096                 if (vh->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
1097                         lws_free((void *)vh->protocols);
1098 #endif
1099 #ifdef LWS_WITH_PLUGINS
1100 #ifndef LWS_NO_EXTENSIONS
1101                 if (context->plugin_extension_count)
1102                         lws_free((void *)vh->extensions);
1103 #endif
1104 #endif
1105 #ifdef LWS_WITH_ACCESS_LOG
1106                 if (vh->log_fd != (int)LWS_INVALID_FILE)
1107                         close(vh->log_fd);
1108 #endif
1109
1110                 vh1 = vh->vhost_next;
1111                 lws_free(vh);
1112                 vh = vh1;
1113         }
1114
1115         lws_stats_log_dump(context);
1116
1117         lws_ssl_context_destroy(context);
1118         lws_plat_context_late_destroy(context);
1119
1120         if (context->external_baggage_free_on_destroy)
1121                 free(context->external_baggage_free_on_destroy);
1122
1123         lws_free(context);
1124 }