lws_intptr_t
[platform/upstream/libwebsockets.git] / lib / context.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2015 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23
24 #ifndef LWS_BUILD_HASH
25 #define LWS_BUILD_HASH "unknown-build-hash"
26 #endif
27
28 static const char *library_version = LWS_LIBRARY_VERSION " " LWS_BUILD_HASH;
29
30 /**
31  * lws_get_library_version: get version and git hash library built from
32  *
33  *      returns a const char * to a string like "1.1 178d78c"
34  *      representing the library version followed by the git head hash it
35  *      was built from
36  */
37 LWS_VISIBLE const char *
38 lws_get_library_version(void)
39 {
40         return library_version;
41 }
42
43 static const char * const mount_protocols[] = {
44         "http://",
45         "https://",
46         "file://",
47         "cgi://",
48         ">http://",
49         ">https://",
50         "callback://"
51 };
52
53 LWS_VISIBLE void *
54 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
55                             int size)
56 {
57         int n = 0;
58
59         /* allocate the vh priv array only on demand */
60         if (!vhost->protocol_vh_privs) {
61                 vhost->protocol_vh_privs = (void **)lws_zalloc(
62                                 vhost->count_protocols * sizeof(void *));
63                 if (!vhost->protocol_vh_privs)
64                         return NULL;
65         }
66
67         while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
68                 n++;
69
70         if (n == vhost->count_protocols) {
71                 n = 0;
72                 while (n < vhost->count_protocols &&
73                        strcmp(vhost->protocols[n].name, prot->name))
74                         n++;
75
76                 if (n == vhost->count_protocols)
77                         return NULL;
78         }
79
80         vhost->protocol_vh_privs[n] = lws_zalloc(size);
81         return vhost->protocol_vh_privs[n];
82 }
83
84 LWS_VISIBLE void *
85 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot)
86 {
87         int n = 0;
88
89         if (!vhost->protocol_vh_privs)
90                 return NULL;
91
92         while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
93                 n++;
94
95         if (n == vhost->count_protocols) {
96                 n = 0;
97                 while (n < vhost->count_protocols &&
98                        strcmp(vhost->protocols[n].name, prot->name))
99                         n++;
100
101                 if (n == vhost->count_protocols) {
102                         lwsl_err("%s: unknown protocol %p\n", __func__, prot);
103                         return NULL;
104                 }
105         }
106
107         return vhost->protocol_vh_privs[n];
108 }
109
110 static const struct lws_protocol_vhost_options *
111 lws_vhost_protocol_options(struct lws_vhost *vh, const char *name)
112 {
113         const struct lws_protocol_vhost_options *pvo = vh->pvo;
114
115         while (pvo) {
116                 // lwsl_notice("%s: '%s' '%s'\n", __func__, pvo->name, name);
117                 if (!strcmp(pvo->name, name))
118                         return pvo;
119                 pvo = pvo->next;
120         }
121
122         return NULL;
123 }
124
125 /*
126  * inform every vhost that hasn't already done it, that
127  * his protocols are initializing
128  */
129 LWS_VISIBLE int
130 lws_protocol_init(struct lws_context *context)
131 {
132         struct lws_vhost *vh = context->vhost_list;
133         const struct lws_protocol_vhost_options *pvo, *pvo1;
134         struct lws wsi;
135         int n;
136
137         memset(&wsi, 0, sizeof(wsi));
138         wsi.context = context;
139
140         lwsl_info("%s\n", __func__);
141
142         while (vh) {
143                 wsi.vhost = vh;
144
145                 /* only do the protocol init once for a given vhost */
146                 if (vh->created_vhost_protocols)
147                         goto next;
148
149                 /* initialize supported protocols on this vhost */
150
151                 for (n = 0; n < vh->count_protocols; n++) {
152                         wsi.protocol = &vh->protocols[n];
153                         if (!vh->protocols[n].name)
154                                 continue;
155                         pvo = lws_vhost_protocol_options(vh,
156                                                          vh->protocols[n].name);
157                         if (pvo) {
158                                 /*
159                                  * linked list of options specific to
160                                  * vh + protocol
161                                  */
162                                 pvo1 = pvo;
163                                 pvo = pvo1->options;
164
165                                 while (pvo) {
166                                         lwsl_notice("    vh %s prot %s opt %s\n",
167                                                         vh->name,
168                                                         vh->protocols[n].name,
169                                                         pvo->name);
170
171                                         if (!strcmp(pvo->name, "default")) {
172                                                 lwsl_notice("Setting default "
173                                                    "protocol for vh %s to %s\n",
174                                                    vh->name,
175                                                    vh->protocols[n].name);
176                                                 vh->default_protocol_index = n;
177                                         }
178                                         if (!strcmp(pvo->name, "raw")) {
179                                                 lwsl_notice("Setting raw "
180                                                    "protocol for vh %s to %s\n",
181                                                    vh->name,
182                                                    vh->protocols[n].name);
183                                                 vh->raw_protocol_index = n;
184                                         }
185                                         pvo = pvo->next;
186                                 }
187
188                                 pvo = pvo1->options;
189                         }
190
191                         /*
192                          * inform all the protocols that they are doing their one-time
193                          * initialization if they want to.
194                          *
195                          * NOTE the wsi is all zeros except for the context, vh and
196                          * protocol ptrs so lws_get_context(wsi) etc can work
197                          */
198                         if (vh->protocols[n].callback(&wsi,
199                                 LWS_CALLBACK_PROTOCOL_INIT, NULL,
200                                 (void *)pvo, 0))
201                                 return 1;
202                 }
203
204                 vh->created_vhost_protocols = 1;
205 next:
206                 vh = vh->vhost_next;
207         }
208
209         if (!context->protocol_init_done)
210                 lws_finalize_startup(context);
211
212         context->protocol_init_done = 1;
213
214         return 0;
215 }
216
217 LWS_VISIBLE int
218 lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
219                     void *user, void *in, size_t len)
220 {
221 #ifdef LWS_WITH_CGI
222         struct lws_cgi_args *args;
223 #endif
224 #if defined(LWS_WITH_CGI) || defined(LWS_WITH_HTTP_PROXY)
225         char buf[512];
226         int n;
227 #endif
228
229
230         switch (reason) {
231         case LWS_CALLBACK_HTTP:
232 #ifndef LWS_NO_SERVER
233                 if (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL))
234                         return -1;
235
236                 if (lws_http_transaction_completed(wsi))
237 #endif
238                         return -1;
239                 break;
240
241         case LWS_CALLBACK_HTTP_WRITEABLE:
242 #ifdef LWS_WITH_CGI
243                 if (wsi->reason_bf & 1) {
244                         if (lws_cgi_write_split_stdout_headers(wsi) < 0)
245                                 return -1;
246
247                         if (wsi->reason_bf & 8)
248                                 wsi->reason_bf &= ~8;
249                         else
250                                 wsi->reason_bf &= ~1;
251                         break;
252                 }
253 #endif
254 #if defined(LWS_WITH_HTTP_PROXY)
255                 if (wsi->reason_bf & 2) {
256                         char *px = buf + LWS_PRE;
257                         int lenx = sizeof(buf) - LWS_PRE;
258                         /*
259                          * our sink is writeable and our source has something
260                          * to read.  So read a lump of source material of
261                          * suitable size to send or what's available, whichever
262                          * is the smaller.
263                          */
264
265
266                         wsi->reason_bf &= ~2;
267                         if (!lws_get_child(wsi))
268                                 break;
269                         if (lws_http_client_read(lws_get_child(wsi), &px, &lenx) < 0)
270                                 return -1;
271                         break;
272                 }
273 #endif
274                 break;
275
276 #if defined(LWS_WITH_HTTP_PROXY)
277         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
278                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
279                 assert(lws_get_parent(wsi));
280                 if (!lws_get_parent(wsi))
281                         break;
282                 lws_get_parent(wsi)->reason_bf |= 2;
283                 lws_callback_on_writable(lws_get_parent(wsi));
284                 break;
285
286         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
287                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", (int)len);
288                 assert(lws_get_parent(wsi));
289                 n = lws_write(lws_get_parent(wsi), (unsigned char *)in,
290                                 len, LWS_WRITE_HTTP);
291                 if (n < 0)
292                         return -1;
293                 break;
294
295         case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
296                 unsigned char *p, *end;
297                 char ctype[64], ctlen = 0;
298
299                 //lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
300         
301                 p = (unsigned char *)buf + LWS_PRE;
302                 end = p + sizeof(buf) - LWS_PRE;
303
304                 if (lws_add_http_header_status(lws_get_parent(wsi), HTTP_STATUS_OK, &p, end))
305                         return 1;
306                 if (lws_add_http_header_by_token(lws_get_parent(wsi),
307                                 WSI_TOKEN_HTTP_SERVER,
308                                 (unsigned char *)"libwebsockets",
309                                 13, &p, end))
310                         return 1;
311
312                 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
313                 if (ctlen > 0) {
314                         if (lws_add_http_header_by_token(lws_get_parent(wsi),
315                                 WSI_TOKEN_HTTP_CONTENT_TYPE,
316                                 (unsigned char *)ctype, ctlen, &p, end))
317                                 return 1;
318                 }
319 #if 0
320                 if (lws_add_http_header_content_length(lws_get_parent(wsi),
321                                                        file_len, &p, end))
322                         return 1;
323 #endif
324                 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
325                         return 1;
326
327                 *p = '\0';
328 //              lwsl_info("%s\n", buf + LWS_PRE);
329
330                 n = lws_write(lws_get_parent(wsi), (unsigned char *)buf + LWS_PRE,
331                               p - ((unsigned char *)buf + LWS_PRE),
332                               LWS_WRITE_HTTP_HEADERS);
333                 if (n < 0)
334                         return -1;
335
336                 break; }
337
338 #endif
339
340 #ifdef LWS_WITH_CGI
341         /* CGI IO events (POLLIN/OUT) appear here, our default policy is:
342          *
343          *  - POST data goes on subprocess stdin
344          *  - subprocess stdout goes on http via writeable callback
345          *  - subprocess stderr goes to the logs
346          */
347         case LWS_CALLBACK_CGI:
348                 args = (struct lws_cgi_args *)in;
349                 switch (args->ch) { /* which of stdin/out/err ? */
350                 case LWS_STDIN:
351                         /* TBD stdin rx flow control */
352                         break;
353                 case LWS_STDOUT:
354                         wsi->reason_bf |= 1;
355                         /* when writing to MASTER would not block */
356                         lws_callback_on_writable(wsi);
357                         break;
358                 case LWS_STDERR:
359                         n = read(lws_get_socket_fd(args->stdwsi[LWS_STDERR]),
360                                                    buf, sizeof(buf) - 2);
361                         if (n > 0) {
362                                 if (buf[n - 1] != '\n')
363                                         buf[n++] = '\n';
364                                 buf[n] = '\0';
365                                 lwsl_notice("CGI-stderr: %s\n", buf);
366                         }
367                         break;
368                 }
369                 break;
370
371         case LWS_CALLBACK_CGI_TERMINATED:
372                 return -1;
373
374         case LWS_CALLBACK_CGI_STDIN_DATA:  /* POST body for stdin */
375                 args = (struct lws_cgi_args *)in;
376                 args->data[args->len] = '\0';
377                 n = write(lws_get_socket_fd(args->stdwsi[LWS_STDIN]),
378                           args->data, args->len);
379                 if (n < args->len)
380                         lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: "
381                                     "sent %d only %d went", n, args->len);
382                 return n;
383 #endif
384
385         case LWS_CALLBACK_SSL_INFO:
386                 {
387                         struct lws_ssl_info *si = in;
388
389                         lwsl_notice("LWS_CALLBACK_SSL_INFO: where: 0x%x, ret: 0x%x\n",
390                                         si->where, si->ret);
391                 }
392                 break;
393
394         default:
395                 break;
396         }
397
398         return 0;
399 }
400
401 /* list of supported protocols and callbacks */
402
403 static const struct lws_protocols protocols_dummy[] = {
404         /* first protocol must always be HTTP handler */
405
406         {
407                 "http-only",            /* name */
408                 lws_callback_http_dummy,                /* callback */
409                 0,      /* per_session_data_size */
410                 0,                      /* max frame size / rx buffer */
411                 0, NULL, 0
412         },
413         /*
414          * the other protocols are provided by lws plugins
415          */
416         { NULL, NULL, 0, 0, 0, NULL, 0} /* terminator */
417 };
418
419 #ifdef LWS_PLAT_OPTEE
420 #undef LWS_HAVE_GETENV
421 #endif
422
423 LWS_VISIBLE struct lws_vhost *
424 lws_create_vhost(struct lws_context *context,
425                  struct lws_context_creation_info *info)
426 {
427         struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
428                          **vh1 = &context->vhost_list;
429         const struct lws_http_mount *mounts;
430         const struct lws_protocol_vhost_options *pvo;
431 #ifdef LWS_WITH_PLUGINS
432         struct lws_plugin *plugin = context->plugin_list;
433 #endif
434         struct lws_protocols *lwsp;
435         int m, f = !info->pvo;
436 #ifdef LWS_HAVE_GETENV
437         char *p;
438 #endif
439         int n;
440
441         if (!vh)
442                 return NULL;
443
444         if (!info->protocols)
445                 info->protocols = &protocols_dummy[0];
446
447         vh->context = context;
448         if (!info->vhost_name)
449                 vh->name = "default";
450         else
451                 vh->name = info->vhost_name;
452
453         vh->iface = info->iface;
454 #if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32) && !defined(OPTEE_TA) && !defined(WIN32)
455         vh->bind_iface = info->bind_iface;
456 #endif
457
458         for (vh->count_protocols = 0;
459              info->protocols[vh->count_protocols].callback;
460              vh->count_protocols++)
461                 ;
462
463         vh->options = info->options;
464         vh->pvo = info->pvo;
465         vh->headers = info->headers;
466         vh->ssl_info_event_mask = info->ssl_info_event_mask;
467         if (info->keepalive_timeout)
468                 vh->keepalive_timeout = info->keepalive_timeout;
469         else
470                 vh->keepalive_timeout = 5;
471
472         /*
473          * give the vhost a unified list of protocols including the
474          * ones that came from plugins
475          */
476         lwsp = lws_zalloc(sizeof(struct lws_protocols) *
477                                    (vh->count_protocols +
478                                    context->plugin_protocol_count + 1));
479         if (!lwsp) {
480                 lwsl_err("OOM\n");
481                 return NULL;
482         }
483
484         m = vh->count_protocols;
485         memcpy(lwsp, info->protocols, sizeof(struct lws_protocols) * m);
486
487         /* for compatibility, all protocols enabled on vhost if only
488          * the default vhost exists.  Otherwise only vhosts who ask
489          * for a protocol get it enabled.
490          */
491
492         if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
493                 f = 0;
494         (void)f;
495 #ifdef LWS_WITH_PLUGINS
496         if (plugin) {
497
498                 while (plugin) {
499                         for (n = 0; n < plugin->caps.count_protocols; n++) {
500                                 /*
501                                  * for compatibility's sake, no pvo implies
502                                  * allow all protocols
503                                  */
504                                 if (f || lws_vhost_protocol_options(vh,
505                                     plugin->caps.protocols[n].name)) {
506                                         memcpy(&lwsp[m],
507                                                &plugin->caps.protocols[n],
508                                                sizeof(struct lws_protocols));
509                                         m++;
510                                         vh->count_protocols++;
511                                 }
512                         }
513                         plugin = plugin->list;
514                 }
515         }
516 #endif
517
518         if (
519 #ifdef LWS_WITH_PLUGINS
520             (context->plugin_list) ||
521 #endif
522             info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
523                 vh->protocols = lwsp;
524         else {
525                 vh->protocols = info->protocols;
526                 free(lwsp);
527         }
528
529         vh->same_vh_protocol_list = (struct lws **)
530                         lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
531
532         vh->mount_list = info->mounts;
533
534 #ifdef LWS_USE_UNIX_SOCK
535         if (LWS_UNIX_SOCK_ENABLED(context)) {
536                 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
537                                 vh->name, info->iface, vh->count_protocols);
538         } else
539 #endif
540         lwsl_notice("Creating Vhost '%s' port %d, %d protocols, IPv6 %s\n",
541                         vh->name, info->port, vh->count_protocols, LWS_IPV6_ENABLED(vh) ? "on" : "off");
542
543         mounts = info->mounts;
544         while (mounts) {
545                 (void)mount_protocols[0];
546                 lwsl_notice("   mounting %s%s to %s\n",
547                                 mount_protocols[mounts->origin_protocol],
548                                 mounts->origin, mounts->mountpoint);
549
550                 /* convert interpreter protocol names to pointers */
551                 pvo = mounts->interpret;
552                 while (pvo) {
553                         for (n = 0; n < vh->count_protocols; n++)
554                                 if (!strcmp(pvo->value, vh->protocols[n].name)) {
555                                         ((struct lws_protocol_vhost_options *)pvo)->value =
556                                                         (const char *)(lws_intptr_t)n;
557                                         break;
558                                 }
559                         if (n == vh->count_protocols)
560                                 lwsl_err("ignoring unknown interpret protocol %s\n", pvo->value);
561                         pvo = pvo->next;
562                 }
563
564                 mounts = mounts->mount_next;
565         }
566
567 #ifndef LWS_NO_EXTENSIONS
568 #ifdef LWS_WITH_PLUGINS
569         if (context->plugin_extension_count) {
570
571                 m = 0;
572                 while (info->extensions && info->extensions[m].callback)
573                         m++;
574
575                 /*
576                  * give the vhost a unified list of extensions including the
577                  * ones that came from plugins
578                  */
579                 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
580                                            (m +
581                                            context->plugin_extension_count + 1));
582                 if (!vh->extensions)
583                         return NULL;
584
585                 memcpy((struct lws_extension *)vh->extensions, info->extensions,
586                        sizeof(struct lws_extension) * m);
587                 plugin = context->plugin_list;
588                 while (plugin) {
589                         memcpy((struct lws_extension *)&vh->extensions[m],
590                                 plugin->caps.extensions,
591                                sizeof(struct lws_extension) *
592                                plugin->caps.count_extensions);
593                         m += plugin->caps.count_extensions;
594                         plugin = plugin->list;
595                 }
596         } else
597 #endif
598                 vh->extensions = info->extensions;
599 #endif
600
601         vh->listen_port = info->port;
602 #if !defined(LWS_WITH_ESP8266)
603         vh->http_proxy_port = 0;
604         vh->http_proxy_address[0] = '\0';
605 #if defined(LWS_WITH_SOCKS5)
606         vh->socks_proxy_port = 0;
607         vh->socks_proxy_address[0] = '\0';
608 #endif
609
610         /* either use proxy from info, or try get it from env var */
611
612         /* http proxy */
613         if (info->http_proxy_address) {
614                 /* override for backwards compatibility */
615                 if (info->http_proxy_port)
616                         vh->http_proxy_port = info->http_proxy_port;
617                 lws_set_proxy(vh, info->http_proxy_address);
618         } else {
619 #ifdef LWS_HAVE_GETENV
620                 p = getenv("http_proxy");
621                 if (p)
622                         lws_set_proxy(vh, p);
623 #endif
624         }
625 #if defined(LWS_WITH_SOCKS5)
626         /* socks proxy */
627         if (info->socks_proxy_address) {
628                 /* override for backwards compatibility */
629                 if (info->socks_proxy_port)
630                         vh->socks_proxy_port = info->socks_proxy_port;
631                 lws_set_socks(vh, info->socks_proxy_address);
632         } else {
633 #ifdef LWS_HAVE_GETENV
634                 p = getenv("socks_proxy");
635                 if (p)
636                         lws_set_socks(vh, p);
637 #endif
638         }
639 #endif
640 #endif
641
642         vh->ka_time = info->ka_time;
643         vh->ka_interval = info->ka_interval;
644         vh->ka_probes = info->ka_probes;
645
646         if (vh->options & LWS_SERVER_OPTION_STS)
647                 lwsl_notice("   STS enabled\n");
648
649 #ifdef LWS_WITH_ACCESS_LOG
650         if (info->log_filepath) {
651                 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
652                 if (vh->log_fd == (int)LWS_INVALID_FILE) {
653                         lwsl_err("unable to open log filepath %s\n",
654                                  info->log_filepath);
655                         goto bail;
656                 }
657 #ifndef WIN32
658                 if (context->uid != -1)
659                         if (chown(info->log_filepath, context->uid,
660                                   context->gid) == -1)
661                                 lwsl_err("unable to chown log file %s\n",
662                                                 info->log_filepath);
663 #endif
664         } else
665                 vh->log_fd = (int)LWS_INVALID_FILE;
666 #endif
667         if (lws_context_init_server_ssl(info, vh))
668                 goto bail;
669         if (lws_context_init_client_ssl(info, vh))
670                 goto bail;
671         if (lws_context_init_server(info, vh)) {
672                 lwsl_err("init server failed\n");
673                 goto bail;
674         }
675
676         while (1) {
677                 if (!(*vh1)) {
678                         *vh1 = vh;
679                         break;
680                 }
681                 vh1 = &(*vh1)->vhost_next;
682         };
683         /* for the case we are adding a vhost much later, after server init */
684
685         if (context->protocol_init_done)
686                 lws_protocol_init(context);
687
688         return vh;
689
690 bail:
691         lws_free(vh);
692
693         return NULL;
694 }
695
696 LWS_VISIBLE int
697 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
698                           struct lws_vhost *vhost)
699 {
700         struct lws_context_creation_info i;
701
702         memcpy(&i, info, sizeof(i));
703         i.port = CONTEXT_PORT_NO_LISTEN;
704
705         return lws_context_init_client_ssl(&i, vhost);
706 }
707
708 LWS_VISIBLE struct lws_context *
709 lws_create_context(struct lws_context_creation_info *info)
710 {
711         struct lws_context *context = NULL;
712         struct lws_plat_file_ops *prev;
713 #ifndef LWS_NO_DAEMONIZE
714         int pid_daemon = get_daemonize_pid();
715 #endif
716         int n, m;
717 #if defined(__ANDROID__)
718         struct rlimit rt;
719 #endif
720
721         lwsl_notice("Initial logging level %d\n", log_level);
722         lwsl_notice("Libwebsockets version: %s\n", library_version);
723 #if defined(GCC_VER)
724         lwsl_notice("Compiled with  %s\n", GCC_VER);
725 #endif
726 #if LWS_POSIX
727 #ifdef LWS_USE_IPV6
728         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
729                 lwsl_notice("IPV6 compiled in and enabled\n");
730         else
731                 lwsl_notice("IPV6 compiled in but disabled\n");
732 #else
733         lwsl_notice("IPV6 not compiled in\n");
734 #endif
735 #if !defined(LWS_PLAT_OPTEE) && !defined(LWS_PLAT_ESP32)
736         lws_feature_status_libev(info);
737         lws_feature_status_libuv(info);
738 #endif
739 #endif
740         lwsl_info(" LWS_DEF_HEADER_LEN    : %u\n", LWS_DEF_HEADER_LEN);
741         lwsl_info(" LWS_MAX_PROTOCOLS     : %u\n", LWS_MAX_PROTOCOLS);
742         lwsl_info(" LWS_MAX_SMP           : %u\n", LWS_MAX_SMP);
743         lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
744         lwsl_info(" sizeof (*info)        : %ld\n", (long)sizeof(*info));
745 #if defined(LWS_WITH_STATS)
746         lwsl_notice(" LWS_WITH_STATS        : on\n");
747 #endif
748 #if LWS_POSIX
749         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
750 #endif
751         if (lws_plat_context_early_init())
752                 return NULL;
753
754         context = lws_zalloc(sizeof(struct lws_context));
755         if (!context) {
756                 lwsl_err("No memory for websocket context\n");
757                 return NULL;
758         }
759         if (info->pt_serv_buf_size)
760                 context->pt_serv_buf_size = info->pt_serv_buf_size;
761         else
762                 context->pt_serv_buf_size = 4096;
763
764         /* default to just the platform fops implementation */
765
766         context->fops_platform.LWS_FOP_OPEN     = _lws_plat_file_open;
767         context->fops_platform.LWS_FOP_CLOSE    = _lws_plat_file_close;
768         context->fops_platform.LWS_FOP_SEEK_CUR = _lws_plat_file_seek_cur;
769         context->fops_platform.LWS_FOP_READ     = _lws_plat_file_read;
770         context->fops_platform.LWS_FOP_WRITE    = _lws_plat_file_write;
771         context->fops_platform.fi[0].sig        = NULL;
772
773         /*
774          *  arrange a linear linked-list of fops starting from context->fops
775          *
776          * platform fops
777          * [ -> fops_zip (copied into context so .next settable) ]
778          * [ -> info->fops ]
779          */
780
781         context->fops = &context->fops_platform;
782         prev = (struct lws_plat_file_ops *)context->fops;
783
784 #if defined(LWS_WITH_ZIP_FOPS)
785         /* make a soft copy so we can set .next */
786         context->fops_zip = fops_zip;
787         prev->next = &context->fops_zip;
788         prev = (struct lws_plat_file_ops *)prev->next;
789 #endif
790
791         /* if user provided fops, tack them on the end of the list */
792         if (info->fops)
793                 prev->next = info->fops;
794
795         context->reject_service_keywords = info->reject_service_keywords;
796         if (info->external_baggage_free_on_destroy)
797                 context->external_baggage_free_on_destroy =
798                         info->external_baggage_free_on_destroy;
799
800         context->time_up = time(NULL);
801
802         context->simultaneous_ssl_restriction = info->simultaneous_ssl_restriction;
803
804 #ifndef LWS_NO_DAEMONIZE
805         if (pid_daemon) {
806                 context->started_with_parent = pid_daemon;
807                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
808         }
809 #endif
810 #if defined(__ANDROID__)
811                 n = getrlimit ( RLIMIT_NOFILE,&rt);
812                 if (-1 == n) {
813                         lwsl_err("Get RLIMIT_NOFILE failed!\n");
814                         return NULL;
815                 }
816                 context->max_fds = rt.rlim_cur;
817 #else
818                 context->max_fds = getdtablesize();
819 #endif
820
821         if (info->count_threads)
822                 context->count_threads = info->count_threads;
823         else
824                 context->count_threads = 1;
825
826         if (context->count_threads > LWS_MAX_SMP)
827                 context->count_threads = LWS_MAX_SMP;
828
829         context->token_limits = info->token_limits;
830
831         context->options = info->options;
832
833         if (info->timeout_secs)
834                 context->timeout_secs = info->timeout_secs;
835         else
836                 context->timeout_secs = AWAITING_TIMEOUT;
837
838         context->ws_ping_pong_interval = info->ws_ping_pong_interval;
839
840         lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
841
842         if (info->max_http_header_data)
843                 context->max_http_header_data = info->max_http_header_data;
844         else
845                 if (info->max_http_header_data2)
846                         context->max_http_header_data =
847                                         info->max_http_header_data2;
848                 else
849                         context->max_http_header_data = LWS_DEF_HEADER_LEN;
850         if (info->max_http_header_pool)
851                 context->max_http_header_pool = info->max_http_header_pool;
852         else
853                 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
854
855         /*
856          * Allocate the per-thread storage for scratchpad buffers,
857          * and header data pool
858          */
859         for (n = 0; n < context->count_threads; n++) {
860                 context->pt[n].serv_buf = lws_zalloc(context->pt_serv_buf_size);
861                 if (!context->pt[n].serv_buf) {
862                         lwsl_err("OOM\n");
863                         return NULL;
864                 }
865
866 #ifdef LWS_USE_LIBUV
867                 context->pt[n].context = context;
868 #endif
869                 context->pt[n].tid = n;
870                 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
871                                                        context->max_http_header_pool);
872                 if (!context->pt[n].http_header_data)
873                         goto bail;
874
875                 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
876                                               context->max_http_header_pool);
877                 for (m = 0; m < context->max_http_header_pool; m++)
878                         context->pt[n].ah_pool[m].data =
879                                 (char *)context->pt[n].http_header_data +
880                                 (m * context->max_http_header_data);
881                 if (!context->pt[n].ah_pool)
882                         goto bail;
883
884                 lws_pt_mutex_init(&context->pt[n]);
885         }
886
887         if (info->fd_limit_per_thread)
888                 context->fd_limit_per_thread = info->fd_limit_per_thread;
889         else
890                 context->fd_limit_per_thread = context->max_fds /
891                                                context->count_threads;
892
893         lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
894                     context->fd_limit_per_thread);
895
896         if (!info->ka_interval && info->ka_time > 0) {
897                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
898                 return NULL;
899         }
900
901 #ifdef LWS_USE_LIBEV
902         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
903          * enable libev mediated SIGINT handling with a default handler of
904          * lws_sigint_cb. The handler can be overridden or disabled
905          * by invoking lws_sigint_cfg after creating the context, but
906          * before invoking lws_initloop:
907          */
908         context->use_ev_sigint = 1;
909         context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
910 #endif /* LWS_USE_LIBEV */
911 #ifdef LWS_USE_LIBUV
912         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
913          * enable libev mediated SIGINT handling with a default handler of
914          * lws_sigint_cb. The handler can be overridden or disabled
915          * by invoking lws_sigint_cfg after creating the context, but
916          * before invoking lws_initloop:
917          */
918         context->use_ev_sigint = 1;
919         context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
920 #endif
921 #ifdef LWS_USE_LIBEVENT
922         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
923          * enable libev mediated SIGINT handling with a default handler of
924          * lws_sigint_cb. The handler can be overridden or disabled
925          * by invoking lws_sigint_cfg after creating the context, but
926          * before invoking lws_initloop:
927          */
928         context->use_ev_sigint = 1;
929         context->lws_event_sigint_cb = &lws_event_sigint_cb;
930 #endif /* LWS_USE_LIBEVENT */
931
932         lwsl_info(" mem: context:         %5lu bytes (%ld ctx + (%ld thr x %d))\n",
933                   (long)sizeof(struct lws_context) +
934                   (context->count_threads * context->pt_serv_buf_size),
935                   (long)sizeof(struct lws_context),
936                   (long)context->count_threads,
937                   context->pt_serv_buf_size);
938
939         lwsl_info(" mem: http hdr rsvd:   %5lu bytes (%u thr x (%u + %lu) x %u))\n",
940                     (long)(context->max_http_header_data +
941                      sizeof(struct allocated_headers)) *
942                     context->max_http_header_pool * context->count_threads,
943                     context->count_threads,
944                     context->max_http_header_data,
945                     (long)sizeof(struct allocated_headers),
946                     context->max_http_header_pool);
947         n = sizeof(struct lws_pollfd) * context->count_threads *
948             context->fd_limit_per_thread;
949         context->pt[0].fds = lws_zalloc(n);
950         if (context->pt[0].fds == NULL) {
951                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
952                 goto bail;
953         }
954         lwsl_info(" mem: pollfd map:      %5u\n", n);
955
956         if (info->server_string) {
957                 context->server_string = info->server_string;
958                 context->server_string_len = (short)
959                                 strlen(context->server_string);
960         }
961
962 #if LWS_MAX_SMP > 1
963         /* each thread serves his own chunk of fds */
964         for (n = 1; n < (int)info->count_threads; n++)
965                 context->pt[n].fds = context->pt[n - 1].fds +
966                                      context->fd_limit_per_thread;
967 #endif
968
969         if (lws_plat_init(context, info))
970                 goto bail;
971
972         lws_context_init_ssl_library(info);
973
974         context->user_space = info->user;
975
976         /*
977          * if he's not saying he'll make his own vhosts later then act
978          * compatibly and make a default vhost using the data in the info
979          */
980         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
981                 if (!lws_create_vhost(context, info)) {
982                         lwsl_err("Failed to create default vhost\n");
983                         return NULL;
984                 }
985
986         lws_context_init_extensions(info, context);
987
988         lwsl_notice(" mem: per-conn:        %5lu bytes + protocol rx buf\n",
989                     (unsigned long)sizeof(struct lws));
990
991         strcpy(context->canonical_hostname, "unknown");
992         lws_server_get_canonical_hostname(context, info);
993
994         context->uid = info->uid;
995         context->gid = info->gid;
996
997 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
998         memcpy(context->caps, info->caps, sizeof(context->caps));
999         context->count_caps = info->count_caps;
1000 #endif
1001
1002         /*
1003          * drop any root privs for this process
1004          * to listen on port < 1023 we would have needed root, but now we are
1005          * listening, we don't want the power for anything else
1006          */
1007         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
1008                 lws_plat_drop_app_privileges(info);
1009
1010         /*
1011          * give all extensions a chance to create any per-context
1012          * allocations they need
1013          */
1014         if (info->port != CONTEXT_PORT_NO_LISTEN) {
1015                 if (lws_ext_cb_all_exts(context, NULL,
1016                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
1017                         goto bail;
1018         } else
1019                 if (lws_ext_cb_all_exts(context, NULL,
1020                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
1021                         goto bail;
1022
1023         return context;
1024
1025 bail:
1026         lws_context_destroy(context);
1027         return NULL;
1028 }
1029
1030 LWS_VISIBLE LWS_EXTERN void
1031 lws_context_deprecate(struct lws_context *context, lws_reload_func cb)
1032 {
1033         struct lws_vhost *vh = context->vhost_list, *vh1;
1034         struct lws *wsi;
1035
1036         /*
1037          * "deprecation" means disable the context from accepting any new
1038          * connections and free up listen sockets to be used by a replacement
1039          * context.
1040          *
1041          * Otherwise the deprecated context remains operational, until its
1042          * number of connected sockets falls to zero, when it is deleted.
1043          */
1044
1045         /* for each vhost, close his listen socket */
1046
1047         while (vh) {
1048                 wsi = vh->lserv_wsi;
1049                 if (wsi) {
1050                         wsi->socket_is_permanently_unusable = 1;
1051                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1052                         wsi->context->deprecation_pending_listen_close_count++;
1053                         /*
1054                          * other vhosts can share the listen port, they
1055                          * point to the same wsi.  So zap those too.
1056                          */
1057                         vh1 = context->vhost_list;
1058                         while (vh1) {
1059                                 if (vh1->lserv_wsi == wsi)
1060                                         vh1->lserv_wsi = NULL;
1061                                 vh1 = vh1->vhost_next;
1062                         }
1063                 }
1064                 vh = vh->vhost_next;
1065         }
1066
1067         context->deprecated = 1;
1068         context->deprecation_cb = cb;
1069 }
1070
1071 LWS_VISIBLE LWS_EXTERN int
1072 lws_context_is_deprecated(struct lws_context *context)
1073 {
1074         return context->deprecated;
1075 }
1076
1077 LWS_VISIBLE void
1078 lws_context_destroy2(struct lws_context *context);
1079
1080 LWS_VISIBLE void
1081 lws_context_destroy(struct lws_context *context)
1082 {
1083         const struct lws_protocols *protocol = NULL;
1084         struct lws_context_per_thread *pt;
1085         struct lws_vhost *vh = NULL;
1086         struct lws wsi;
1087         int n, m;
1088
1089         if (!context) {
1090                 lwsl_notice("%s: ctx %p\n", __func__, context);
1091                 return;
1092         }
1093         if (context->being_destroyed1) {
1094                 lwsl_notice("%s: ctx %p: already being destroyed\n", __func__, context);
1095                 return;
1096         }
1097
1098         lwsl_notice("%s: ctx %p\n", __func__, context);
1099
1100         m = context->count_threads;
1101         context->being_destroyed = 1;
1102         context->being_destroyed1 = 1;
1103
1104         memset(&wsi, 0, sizeof(wsi));
1105         wsi.context = context;
1106
1107 #ifdef LWS_LATENCY
1108         if (context->worst_latency_info[0])
1109                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
1110 #endif
1111
1112         while (m--) {
1113                 pt = &context->pt[m];
1114
1115                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
1116                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
1117                         if (!wsi)
1118                                 continue;
1119
1120                         lws_close_free_wsi(wsi,
1121                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
1122                                 /* no protocol close */);
1123                         n--;
1124                 }
1125                 lws_pt_mutex_destroy(pt);
1126         }
1127
1128         /*
1129          * give all extensions a chance to clean up any per-context
1130          * allocations they might have made
1131          */
1132
1133         n = lws_ext_cb_all_exts(context, NULL,
1134                                 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
1135
1136         n = lws_ext_cb_all_exts(context, NULL,
1137                                 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
1138
1139         /*
1140          * inform all the protocols that they are done and will have no more
1141          * callbacks.
1142          *
1143          * We can't free things until after the event loop shuts down.
1144          */
1145         if (context->protocol_init_done)
1146                 vh = context->vhost_list;
1147         while (vh) {
1148                 wsi.vhost = vh;
1149                 protocol = vh->protocols;
1150                 if (protocol) {
1151                         n = 0;
1152                         while (n < vh->count_protocols) {
1153                                 wsi.protocol = protocol;
1154                                 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
1155                                                    NULL, NULL, 0);
1156                                 protocol++;
1157                                 n++;
1158                         }
1159                 }
1160
1161                 vh = vh->vhost_next;
1162         }
1163
1164         for (n = 0; n < context->count_threads; n++) {
1165                 pt = &context->pt[n];
1166
1167                 lws_libev_destroyloop(context, n);
1168                 lws_libuv_destroyloop(context, n);
1169                 lws_libevent_destroyloop(context, n);
1170
1171                 lws_free_set_NULL(context->pt[n].serv_buf);
1172                 if (pt->ah_pool)
1173                         lws_free(pt->ah_pool);
1174                 if (pt->http_header_data)
1175                         lws_free(pt->http_header_data);
1176         }
1177         lws_plat_context_early_destroy(context);
1178
1179         if (context->pt[0].fds)
1180                 lws_free_set_NULL(context->pt[0].fds);
1181
1182         if (!LWS_LIBUV_ENABLED(context))
1183                 lws_context_destroy2(context);
1184 }
1185
1186 /*
1187  * call the second one after the event loop has been shut down cleanly
1188  */
1189
1190 LWS_VISIBLE void
1191 lws_context_destroy2(struct lws_context *context)
1192 {
1193         const struct lws_protocols *protocol = NULL;
1194         struct lws_vhost *vh = NULL, *vh1;
1195         int n;
1196
1197         lwsl_notice("%s: ctx %p\n", __func__, context);
1198
1199         /*
1200          * free all the per-vhost allocations
1201          */
1202
1203         vh = context->vhost_list;
1204         while (vh) {
1205                 protocol = vh->protocols;
1206                 if (protocol) {
1207                         n = 0;
1208                         while (n < vh->count_protocols) {
1209                                 if (vh->protocol_vh_privs &&
1210                                     vh->protocol_vh_privs[n]) {
1211                                         // lwsl_notice("   %s: freeing per-vhost protocol data %p\n", __func__, vh->protocol_vh_privs[n]);
1212                                         lws_free(vh->protocol_vh_privs[n]);
1213                                         vh->protocol_vh_privs[n] = NULL;
1214                                 }
1215                                 protocol++;
1216                                 n++;
1217                         }
1218                 }
1219                 if (vh->protocol_vh_privs)
1220                         lws_free(vh->protocol_vh_privs);
1221                 lws_ssl_SSL_CTX_destroy(vh);
1222                 lws_free(vh->same_vh_protocol_list);
1223 #ifdef LWS_WITH_PLUGINS
1224                 if (context->plugin_list)
1225                         lws_free((void *)vh->protocols);
1226 #else
1227                 if (vh->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
1228                         lws_free((void *)vh->protocols);
1229 #endif
1230 #ifdef LWS_WITH_PLUGINS
1231 #ifndef LWS_NO_EXTENSIONS
1232                 if (context->plugin_extension_count)
1233                         lws_free((void *)vh->extensions);
1234 #endif
1235 #endif
1236 #ifdef LWS_WITH_ACCESS_LOG
1237                 if (vh->log_fd != (int)LWS_INVALID_FILE)
1238                         close(vh->log_fd);
1239 #endif
1240
1241                 vh1 = vh->vhost_next;
1242                 lws_free(vh);
1243                 vh = vh1;
1244         }
1245
1246         lws_stats_log_dump(context);
1247
1248         lws_ssl_context_destroy(context);
1249         lws_plat_context_late_destroy(context);
1250
1251         if (context->external_baggage_free_on_destroy)
1252                 free(context->external_baggage_free_on_destroy);
1253
1254         lws_free(context);
1255 }