Subject: LWS_UNUSED
[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         default:
385                 break;
386         }
387
388         return 0;
389 }
390
391 /* list of supported protocols and callbacks */
392
393 static const struct lws_protocols protocols_dummy[] = {
394         /* first protocol must always be HTTP handler */
395
396         {
397                 "http-only",            /* name */
398                 lws_callback_http_dummy,                /* callback */
399                 0,      /* per_session_data_size */
400                 0,                      /* max frame size / rx buffer */
401                 0, NULL, 0
402         },
403         /*
404          * the other protocols are provided by lws plugins
405          */
406         { NULL, NULL, 0, 0, 0, NULL, 0} /* terminator */
407 };
408
409 #ifdef LWS_PLAT_OPTEE
410 #undef LWS_HAVE_GETENV
411 #endif
412
413 LWS_VISIBLE struct lws_vhost *
414 lws_create_vhost(struct lws_context *context,
415                  struct lws_context_creation_info *info)
416 {
417         struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
418                          **vh1 = &context->vhost_list;
419         const struct lws_http_mount *mounts;
420         const struct lws_protocol_vhost_options *pvo;
421 #ifdef LWS_WITH_PLUGINS
422         struct lws_plugin *plugin = context->plugin_list;
423 #endif
424         struct lws_protocols *lwsp;
425         int m, f = !info->pvo;
426 #ifdef LWS_HAVE_GETENV
427         char *p;
428 #endif
429         int n;
430
431         if (!vh)
432                 return NULL;
433
434         if (!info->protocols)
435                 info->protocols = &protocols_dummy[0];
436
437         vh->context = context;
438         if (!info->vhost_name)
439                 vh->name = "default";
440         else
441                 vh->name = info->vhost_name;
442
443         vh->iface = info->iface;
444 #if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32) && !defined(OPTEE_TA) && !defined(WIN32)
445         vh->bind_iface = info->bind_iface;
446 #endif
447
448         for (vh->count_protocols = 0;
449              info->protocols[vh->count_protocols].callback;
450              vh->count_protocols++)
451                 ;
452
453         vh->options = info->options;
454         vh->pvo = info->pvo;
455         vh->headers = info->headers;
456         if (info->keepalive_timeout)
457                 vh->keepalive_timeout = info->keepalive_timeout;
458         else
459                 vh->keepalive_timeout = 5;
460
461         /*
462          * give the vhost a unified list of protocols including the
463          * ones that came from plugins
464          */
465         lwsp = lws_zalloc(sizeof(struct lws_protocols) *
466                                    (vh->count_protocols +
467                                    context->plugin_protocol_count + 1));
468         if (!lwsp) {
469                 lwsl_err("OOM\n");
470                 return NULL;
471         }
472
473         m = vh->count_protocols;
474         memcpy(lwsp, info->protocols, sizeof(struct lws_protocols) * m);
475
476         /* for compatibility, all protocols enabled on vhost if only
477          * the default vhost exists.  Otherwise only vhosts who ask
478          * for a protocol get it enabled.
479          */
480
481         if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
482                 f = 0;
483         (void)f;
484 #ifdef LWS_WITH_PLUGINS
485         if (plugin) {
486
487                 while (plugin) {
488                         for (n = 0; n < plugin->caps.count_protocols; n++) {
489                                 /*
490                                  * for compatibility's sake, no pvo implies
491                                  * allow all protocols
492                                  */
493                                 if (f || lws_vhost_protocol_options(vh,
494                                     plugin->caps.protocols[n].name)) {
495                                         memcpy(&lwsp[m],
496                                                &plugin->caps.protocols[n],
497                                                sizeof(struct lws_protocols));
498                                         m++;
499                                         vh->count_protocols++;
500                                 }
501                         }
502                         plugin = plugin->list;
503                 }
504         }
505 #endif
506
507         if (
508 #ifdef LWS_WITH_PLUGINS
509             (context->plugin_list) ||
510 #endif
511             info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
512                 vh->protocols = lwsp;
513         else {
514                 vh->protocols = info->protocols;
515                 free(lwsp);
516         }
517
518         vh->same_vh_protocol_list = (struct lws **)
519                         lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
520
521         vh->mount_list = info->mounts;
522
523 #ifdef LWS_USE_UNIX_SOCK
524         if (LWS_UNIX_SOCK_ENABLED(context)) {
525                 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
526                                 vh->name, info->iface, vh->count_protocols);
527         } else
528 #endif
529         lwsl_notice("Creating Vhost '%s' port %d, %d protocols, IPv6 %s\n",
530                         vh->name, info->port, vh->count_protocols, LWS_IPV6_ENABLED(vh) ? "on" : "off");
531
532         mounts = info->mounts;
533         while (mounts) {
534                 (void)mount_protocols[0];
535                 lwsl_notice("   mounting %s%s to %s\n",
536                                 mount_protocols[mounts->origin_protocol],
537                                 mounts->origin, mounts->mountpoint);
538
539                 /* convert interpreter protocol names to pointers */
540                 pvo = mounts->interpret;
541                 while (pvo) {
542                         for (n = 0; n < vh->count_protocols; n++)
543                                 if (!strcmp(pvo->value, vh->protocols[n].name)) {
544                                         ((struct lws_protocol_vhost_options *)pvo)->value =
545                                                         (const char *)(long)n;
546                                         break;
547                                 }
548                         if (n == vh->count_protocols)
549                                 lwsl_err("ignoring unknown interpret protocol %s\n", pvo->value);
550                         pvo = pvo->next;
551                 }
552
553                 mounts = mounts->mount_next;
554         }
555
556 #ifndef LWS_NO_EXTENSIONS
557 #ifdef LWS_WITH_PLUGINS
558         if (context->plugin_extension_count) {
559
560                 m = 0;
561                 while (info->extensions && info->extensions[m].callback)
562                         m++;
563
564                 /*
565                  * give the vhost a unified list of extensions including the
566                  * ones that came from plugins
567                  */
568                 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
569                                            (m +
570                                            context->plugin_extension_count + 1));
571                 if (!vh->extensions)
572                         return NULL;
573
574                 memcpy((struct lws_extension *)vh->extensions, info->extensions,
575                        sizeof(struct lws_extension) * m);
576                 plugin = context->plugin_list;
577                 while (plugin) {
578                         memcpy((struct lws_extension *)&vh->extensions[m],
579                                 plugin->caps.extensions,
580                                sizeof(struct lws_extension) *
581                                plugin->caps.count_extensions);
582                         m += plugin->caps.count_extensions;
583                         plugin = plugin->list;
584                 }
585         } else
586 #endif
587                 vh->extensions = info->extensions;
588 #endif
589
590         vh->listen_port = info->port;
591 #if !defined(LWS_WITH_ESP8266)
592         vh->http_proxy_port = 0;
593         vh->http_proxy_address[0] = '\0';
594 #if defined(LWS_WITH_SOCKS5)
595         vh->socks_proxy_port = 0;
596         vh->socks_proxy_address[0] = '\0';
597 #endif
598
599         /* either use proxy from info, or try get it from env var */
600
601         /* http proxy */
602         if (info->http_proxy_address) {
603                 /* override for backwards compatibility */
604                 if (info->http_proxy_port)
605                         vh->http_proxy_port = info->http_proxy_port;
606                 lws_set_proxy(vh, info->http_proxy_address);
607         } else {
608 #ifdef LWS_HAVE_GETENV
609                 p = getenv("http_proxy");
610                 if (p)
611                         lws_set_proxy(vh, p);
612 #endif
613         }
614 #if defined(LWS_WITH_SOCKS5)
615         /* socks proxy */
616         if (info->socks_proxy_address) {
617                 /* override for backwards compatibility */
618                 if (info->socks_proxy_port)
619                         vh->socks_proxy_port = info->socks_proxy_port;
620                 lws_set_socks(vh, info->socks_proxy_address);
621         } else {
622 #ifdef LWS_HAVE_GETENV
623                 p = getenv("socks_proxy");
624                 if (p)
625                         lws_set_socks(vh, p);
626 #endif
627         }
628 #endif
629 #endif
630
631         vh->ka_time = info->ka_time;
632         vh->ka_interval = info->ka_interval;
633         vh->ka_probes = info->ka_probes;
634
635         if (vh->options & LWS_SERVER_OPTION_STS)
636                 lwsl_notice("   STS enabled\n");
637
638 #ifdef LWS_WITH_ACCESS_LOG
639         if (info->log_filepath) {
640                 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
641                 if (vh->log_fd == (int)LWS_INVALID_FILE) {
642                         lwsl_err("unable to open log filepath %s\n",
643                                  info->log_filepath);
644                         goto bail;
645                 }
646 #ifndef WIN32
647                 if (context->uid != -1)
648                         if (chown(info->log_filepath, context->uid,
649                                   context->gid) == -1)
650                                 lwsl_err("unable to chown log file %s\n",
651                                                 info->log_filepath);
652 #endif
653         } else
654                 vh->log_fd = (int)LWS_INVALID_FILE;
655 #endif
656         if (lws_context_init_server_ssl(info, vh))
657                 goto bail;
658         if (lws_context_init_client_ssl(info, vh))
659                 goto bail;
660         if (lws_context_init_server(info, vh)) {
661                 lwsl_err("init server failed\n");
662                 goto bail;
663         }
664
665         while (1) {
666                 if (!(*vh1)) {
667                         *vh1 = vh;
668                         break;
669                 }
670                 vh1 = &(*vh1)->vhost_next;
671         };
672         /* for the case we are adding a vhost much later, after server init */
673
674         if (context->protocol_init_done)
675                 lws_protocol_init(context);
676
677         return vh;
678
679 bail:
680         lws_free(vh);
681
682         return NULL;
683 }
684
685 LWS_VISIBLE int
686 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
687                           struct lws_vhost *vhost)
688 {
689         struct lws_context_creation_info i;
690
691         memcpy(&i, info, sizeof(i));
692         i.port = CONTEXT_PORT_NO_LISTEN;
693
694         return lws_context_init_client_ssl(&i, vhost);
695 }
696
697 LWS_VISIBLE struct lws_context *
698 lws_create_context(struct lws_context_creation_info *info)
699 {
700         struct lws_context *context = NULL;
701         struct lws_plat_file_ops *prev;
702 #ifndef LWS_NO_DAEMONIZE
703         int pid_daemon = get_daemonize_pid();
704 #endif
705         int n, m;
706 #if defined(__ANDROID__)
707         struct rlimit rt;
708 #endif
709
710         lwsl_notice("Initial logging level %d\n", log_level);
711         lwsl_notice("Libwebsockets version: %s\n", library_version);
712 #if defined(GCC_VER)
713         lwsl_notice("Compiled with  %s\n", GCC_VER);
714 #endif
715 #if LWS_POSIX
716 #ifdef LWS_USE_IPV6
717         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
718                 lwsl_notice("IPV6 compiled in and enabled\n");
719         else
720                 lwsl_notice("IPV6 compiled in but disabled\n");
721 #else
722         lwsl_notice("IPV6 not compiled in\n");
723 #endif
724 #if !defined(LWS_PLAT_OPTEE) && !defined(LWS_PLAT_ESP32)
725         lws_feature_status_libev(info);
726         lws_feature_status_libuv(info);
727 #endif
728 #endif
729         lwsl_info(" LWS_DEF_HEADER_LEN    : %u\n", LWS_DEF_HEADER_LEN);
730         lwsl_info(" LWS_MAX_PROTOCOLS     : %u\n", LWS_MAX_PROTOCOLS);
731         lwsl_info(" LWS_MAX_SMP           : %u\n", LWS_MAX_SMP);
732         lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
733         lwsl_info(" sizeof (*info)        : %ld\n", (long)sizeof(*info));
734 #if defined(LWS_WITH_STATS)
735         lwsl_notice(" LWS_WITH_STATS        : on\n");
736 #endif
737 #if LWS_POSIX
738         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
739 #endif
740         if (lws_plat_context_early_init())
741                 return NULL;
742
743         context = lws_zalloc(sizeof(struct lws_context));
744         if (!context) {
745                 lwsl_err("No memory for websocket context\n");
746                 return NULL;
747         }
748         if (info->pt_serv_buf_size)
749                 context->pt_serv_buf_size = info->pt_serv_buf_size;
750         else
751                 context->pt_serv_buf_size = 4096;
752
753         /* default to just the platform fops implementation */
754
755         context->fops_platform.LWS_FOP_OPEN     = _lws_plat_file_open;
756         context->fops_platform.LWS_FOP_CLOSE    = _lws_plat_file_close;
757         context->fops_platform.LWS_FOP_SEEK_CUR = _lws_plat_file_seek_cur;
758         context->fops_platform.LWS_FOP_READ     = _lws_plat_file_read;
759         context->fops_platform.LWS_FOP_WRITE    = _lws_plat_file_write;
760         context->fops_platform.fi[0].sig        = NULL;
761
762         /*
763          *  arrange a linear linked-list of fops starting from context->fops
764          *
765          * platform fops
766          * [ -> fops_zip (copied into context so .next settable) ]
767          * [ -> info->fops ]
768          */
769
770         context->fops = &context->fops_platform;
771         prev = (struct lws_plat_file_ops *)context->fops;
772
773 #if defined(LWS_WITH_ZIP_FOPS)
774         /* make a soft copy so we can set .next */
775         context->fops_zip = fops_zip;
776         prev->next = &context->fops_zip;
777         prev = (struct lws_plat_file_ops *)prev->next;
778 #endif
779
780         /* if user provided fops, tack them on the end of the list */
781         if (info->fops)
782                 prev->next = info->fops;
783
784         context->reject_service_keywords = info->reject_service_keywords;
785         if (info->external_baggage_free_on_destroy)
786                 context->external_baggage_free_on_destroy =
787                         info->external_baggage_free_on_destroy;
788
789         context->time_up = time(NULL);
790
791         context->simultaneous_ssl_restriction = info->simultaneous_ssl_restriction;
792
793 #ifndef LWS_NO_DAEMONIZE
794         if (pid_daemon) {
795                 context->started_with_parent = pid_daemon;
796                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
797         }
798 #endif
799 #if defined(__ANDROID__)
800                 n = getrlimit ( RLIMIT_NOFILE,&rt);
801                 if (-1 == n) {
802                         lwsl_err("Get RLIMIT_NOFILE failed!\n");
803                         return NULL;
804                 }
805                 context->max_fds = rt.rlim_cur;
806 #else
807                 context->max_fds = getdtablesize();
808 #endif
809
810         if (info->count_threads)
811                 context->count_threads = info->count_threads;
812         else
813                 context->count_threads = 1;
814
815         if (context->count_threads > LWS_MAX_SMP)
816                 context->count_threads = LWS_MAX_SMP;
817
818         context->token_limits = info->token_limits;
819
820         context->options = info->options;
821
822         if (info->timeout_secs)
823                 context->timeout_secs = info->timeout_secs;
824         else
825                 context->timeout_secs = AWAITING_TIMEOUT;
826
827         context->ws_ping_pong_interval = info->ws_ping_pong_interval;
828
829         lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
830
831         if (info->max_http_header_data)
832                 context->max_http_header_data = info->max_http_header_data;
833         else
834                 if (info->max_http_header_data2)
835                         context->max_http_header_data =
836                                         info->max_http_header_data2;
837                 else
838                         context->max_http_header_data = LWS_DEF_HEADER_LEN;
839         if (info->max_http_header_pool)
840                 context->max_http_header_pool = info->max_http_header_pool;
841         else
842                 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
843
844         /*
845          * Allocate the per-thread storage for scratchpad buffers,
846          * and header data pool
847          */
848         for (n = 0; n < context->count_threads; n++) {
849                 context->pt[n].serv_buf = lws_zalloc(context->pt_serv_buf_size);
850                 if (!context->pt[n].serv_buf) {
851                         lwsl_err("OOM\n");
852                         return NULL;
853                 }
854
855 #ifdef LWS_USE_LIBUV
856                 context->pt[n].context = context;
857 #endif
858                 context->pt[n].tid = n;
859                 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
860                                                        context->max_http_header_pool);
861                 if (!context->pt[n].http_header_data)
862                         goto bail;
863
864                 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
865                                               context->max_http_header_pool);
866                 for (m = 0; m < context->max_http_header_pool; m++)
867                         context->pt[n].ah_pool[m].data =
868                                 (char *)context->pt[n].http_header_data +
869                                 (m * context->max_http_header_data);
870                 if (!context->pt[n].ah_pool)
871                         goto bail;
872
873                 lws_pt_mutex_init(&context->pt[n]);
874         }
875
876         if (info->fd_limit_per_thread)
877                 context->fd_limit_per_thread = info->fd_limit_per_thread;
878         else
879                 context->fd_limit_per_thread = context->max_fds /
880                                                context->count_threads;
881
882         lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
883                     context->fd_limit_per_thread);
884
885         if (!info->ka_interval && info->ka_time > 0) {
886                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
887                 return NULL;
888         }
889
890 #ifdef LWS_USE_LIBEV
891         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
892          * enable libev mediated SIGINT handling with a default handler of
893          * lws_sigint_cb. The handler can be overridden or disabled
894          * by invoking lws_sigint_cfg after creating the context, but
895          * before invoking lws_initloop:
896          */
897         context->use_ev_sigint = 1;
898         context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
899 #endif /* LWS_USE_LIBEV */
900 #ifdef LWS_USE_LIBUV
901         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
902          * enable libev mediated SIGINT handling with a default handler of
903          * lws_sigint_cb. The handler can be overridden or disabled
904          * by invoking lws_sigint_cfg after creating the context, but
905          * before invoking lws_initloop:
906          */
907         context->use_ev_sigint = 1;
908         context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
909 #endif
910 #ifdef LWS_USE_LIBEVENT
911         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
912          * enable libev mediated SIGINT handling with a default handler of
913          * lws_sigint_cb. The handler can be overridden or disabled
914          * by invoking lws_sigint_cfg after creating the context, but
915          * before invoking lws_initloop:
916          */
917         context->use_ev_sigint = 1;
918         context->lws_event_sigint_cb = &lws_event_sigint_cb;
919 #endif /* LWS_USE_LIBEVENT */
920
921         lwsl_info(" mem: context:         %5lu bytes (%ld ctx + (%ld thr x %d))\n",
922                   (long)sizeof(struct lws_context) +
923                   (context->count_threads * context->pt_serv_buf_size),
924                   (long)sizeof(struct lws_context),
925                   (long)context->count_threads,
926                   context->pt_serv_buf_size);
927
928         lwsl_info(" mem: http hdr rsvd:   %5lu bytes (%u thr x (%u + %lu) x %u))\n",
929                     (long)(context->max_http_header_data +
930                      sizeof(struct allocated_headers)) *
931                     context->max_http_header_pool * context->count_threads,
932                     context->count_threads,
933                     context->max_http_header_data,
934                     (long)sizeof(struct allocated_headers),
935                     context->max_http_header_pool);
936         n = sizeof(struct lws_pollfd) * context->count_threads *
937             context->fd_limit_per_thread;
938         context->pt[0].fds = lws_zalloc(n);
939         if (context->pt[0].fds == NULL) {
940                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
941                 goto bail;
942         }
943         lwsl_info(" mem: pollfd map:      %5u\n", n);
944
945         if (info->server_string) {
946                 context->server_string = info->server_string;
947                 context->server_string_len = (short)
948                                 strlen(context->server_string);
949         }
950
951 #if LWS_MAX_SMP > 1
952         /* each thread serves his own chunk of fds */
953         for (n = 1; n < (int)info->count_threads; n++)
954                 context->pt[n].fds = context->pt[n - 1].fds +
955                                      context->fd_limit_per_thread;
956 #endif
957
958         if (lws_plat_init(context, info))
959                 goto bail;
960
961         lws_context_init_ssl_library(info);
962
963         context->user_space = info->user;
964
965         /*
966          * if he's not saying he'll make his own vhosts later then act
967          * compatibly and make a default vhost using the data in the info
968          */
969         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
970                 if (!lws_create_vhost(context, info)) {
971                         lwsl_err("Failed to create default vhost\n");
972                         return NULL;
973                 }
974
975         lws_context_init_extensions(info, context);
976
977         lwsl_notice(" mem: per-conn:        %5lu bytes + protocol rx buf\n",
978                     (unsigned long)sizeof(struct lws));
979
980         strcpy(context->canonical_hostname, "unknown");
981         lws_server_get_canonical_hostname(context, info);
982
983         context->uid = info->uid;
984         context->gid = info->gid;
985
986 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
987         memcpy(context->caps, info->caps, sizeof(context->caps));
988         context->count_caps = info->count_caps;
989 #endif
990
991         /*
992          * drop any root privs for this process
993          * to listen on port < 1023 we would have needed root, but now we are
994          * listening, we don't want the power for anything else
995          */
996         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
997                 lws_plat_drop_app_privileges(info);
998
999         /*
1000          * give all extensions a chance to create any per-context
1001          * allocations they need
1002          */
1003         if (info->port != CONTEXT_PORT_NO_LISTEN) {
1004                 if (lws_ext_cb_all_exts(context, NULL,
1005                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
1006                         goto bail;
1007         } else
1008                 if (lws_ext_cb_all_exts(context, NULL,
1009                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
1010                         goto bail;
1011
1012         return context;
1013
1014 bail:
1015         lws_context_destroy(context);
1016         return NULL;
1017 }
1018
1019 LWS_VISIBLE LWS_EXTERN void
1020 lws_context_deprecate(struct lws_context *context, lws_reload_func cb)
1021 {
1022         struct lws_vhost *vh = context->vhost_list, *vh1;
1023         struct lws *wsi;
1024
1025         /*
1026          * "deprecation" means disable the context from accepting any new
1027          * connections and free up listen sockets to be used by a replacement
1028          * context.
1029          *
1030          * Otherwise the deprecated context remains operational, until its
1031          * number of connected sockets falls to zero, when it is deleted.
1032          */
1033
1034         /* for each vhost, close his listen socket */
1035
1036         while (vh) {
1037                 wsi = vh->lserv_wsi;
1038                 if (wsi) {
1039                         wsi->socket_is_permanently_unusable = 1;
1040                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1041                         wsi->context->deprecation_pending_listen_close_count++;
1042                         /*
1043                          * other vhosts can share the listen port, they
1044                          * point to the same wsi.  So zap those too.
1045                          */
1046                         vh1 = context->vhost_list;
1047                         while (vh1) {
1048                                 if (vh1->lserv_wsi == wsi)
1049                                         vh1->lserv_wsi = NULL;
1050                                 vh1 = vh1->vhost_next;
1051                         }
1052                 }
1053                 vh = vh->vhost_next;
1054         }
1055
1056         context->deprecated = 1;
1057         context->deprecation_cb = cb;
1058 }
1059
1060 LWS_VISIBLE LWS_EXTERN int
1061 lws_context_is_deprecated(struct lws_context *context)
1062 {
1063         return context->deprecated;
1064 }
1065
1066 LWS_VISIBLE void
1067 lws_context_destroy2(struct lws_context *context);
1068
1069 LWS_VISIBLE void
1070 lws_context_destroy(struct lws_context *context)
1071 {
1072         const struct lws_protocols *protocol = NULL;
1073         struct lws_context_per_thread *pt;
1074         struct lws_vhost *vh = NULL;
1075         struct lws wsi;
1076         int n, m;
1077
1078         if (!context) {
1079                 lwsl_notice("%s: ctx %p\n", __func__, context);
1080                 return;
1081         }
1082         if (context->being_destroyed1) {
1083                 lwsl_notice("%s: ctx %p: already being destroyed\n", __func__, context);
1084                 return;
1085         }
1086
1087         lwsl_notice("%s: ctx %p\n", __func__, context);
1088
1089         m = context->count_threads;
1090         context->being_destroyed = 1;
1091         context->being_destroyed1 = 1;
1092
1093         memset(&wsi, 0, sizeof(wsi));
1094         wsi.context = context;
1095
1096 #ifdef LWS_LATENCY
1097         if (context->worst_latency_info[0])
1098                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
1099 #endif
1100
1101         while (m--) {
1102                 pt = &context->pt[m];
1103
1104                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
1105                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
1106                         if (!wsi)
1107                                 continue;
1108
1109                         lws_close_free_wsi(wsi,
1110                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
1111                                 /* no protocol close */);
1112                         n--;
1113                 }
1114                 lws_pt_mutex_destroy(pt);
1115         }
1116
1117         /*
1118          * give all extensions a chance to clean up any per-context
1119          * allocations they might have made
1120          */
1121
1122         n = lws_ext_cb_all_exts(context, NULL,
1123                                 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
1124
1125         n = lws_ext_cb_all_exts(context, NULL,
1126                                 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
1127
1128         /*
1129          * inform all the protocols that they are done and will have no more
1130          * callbacks.
1131          *
1132          * We can't free things until after the event loop shuts down.
1133          */
1134         if (context->protocol_init_done)
1135                 vh = context->vhost_list;
1136         while (vh) {
1137                 wsi.vhost = vh;
1138                 protocol = vh->protocols;
1139                 if (protocol) {
1140                         n = 0;
1141                         while (n < vh->count_protocols) {
1142                                 wsi.protocol = protocol;
1143                                 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
1144                                                    NULL, NULL, 0);
1145                                 protocol++;
1146                                 n++;
1147                         }
1148                 }
1149
1150                 vh = vh->vhost_next;
1151         }
1152
1153         for (n = 0; n < context->count_threads; n++) {
1154                 pt = &context->pt[n];
1155
1156                 lws_libev_destroyloop(context, n);
1157                 lws_libuv_destroyloop(context, n);
1158                 lws_libevent_destroyloop(context, n);
1159
1160                 lws_free_set_NULL(context->pt[n].serv_buf);
1161                 if (pt->ah_pool)
1162                         lws_free(pt->ah_pool);
1163                 if (pt->http_header_data)
1164                         lws_free(pt->http_header_data);
1165         }
1166         lws_plat_context_early_destroy(context);
1167
1168         if (context->pt[0].fds)
1169                 lws_free_set_NULL(context->pt[0].fds);
1170
1171         if (!LWS_LIBUV_ENABLED(context))
1172                 lws_context_destroy2(context);
1173 }
1174
1175 /*
1176  * call the second one after the event loop has been shut down cleanly
1177  */
1178
1179 LWS_VISIBLE void
1180 lws_context_destroy2(struct lws_context *context)
1181 {
1182         const struct lws_protocols *protocol = NULL;
1183         struct lws_vhost *vh = NULL, *vh1;
1184         int n;
1185
1186         lwsl_notice("%s: ctx %p\n", __func__, context);
1187
1188         /*
1189          * free all the per-vhost allocations
1190          */
1191
1192         vh = context->vhost_list;
1193         while (vh) {
1194                 protocol = vh->protocols;
1195                 if (protocol) {
1196                         n = 0;
1197                         while (n < vh->count_protocols) {
1198                                 if (vh->protocol_vh_privs &&
1199                                     vh->protocol_vh_privs[n]) {
1200                                         // lwsl_notice("   %s: freeing per-vhost protocol data %p\n", __func__, vh->protocol_vh_privs[n]);
1201                                         lws_free(vh->protocol_vh_privs[n]);
1202                                         vh->protocol_vh_privs[n] = NULL;
1203                                 }
1204                                 protocol++;
1205                                 n++;
1206                         }
1207                 }
1208                 if (vh->protocol_vh_privs)
1209                         lws_free(vh->protocol_vh_privs);
1210                 lws_ssl_SSL_CTX_destroy(vh);
1211                 lws_free(vh->same_vh_protocol_list);
1212 #ifdef LWS_WITH_PLUGINS
1213                 if (context->plugin_list)
1214                         lws_free((void *)vh->protocols);
1215 #else
1216                 if (vh->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
1217                         lws_free((void *)vh->protocols);
1218 #endif
1219 #ifdef LWS_WITH_PLUGINS
1220 #ifndef LWS_NO_EXTENSIONS
1221                 if (context->plugin_extension_count)
1222                         lws_free((void *)vh->extensions);
1223 #endif
1224 #endif
1225 #ifdef LWS_WITH_ACCESS_LOG
1226                 if (vh->log_fd != (int)LWS_INVALID_FILE)
1227                         close(vh->log_fd);
1228 #endif
1229
1230                 vh1 = vh->vhost_next;
1231                 lws_free(vh);
1232                 vh = vh1;
1233         }
1234
1235         lws_stats_log_dump(context);
1236
1237         lws_ssl_context_destroy(context);
1238         lws_plat_context_late_destroy(context);
1239
1240         if (context->external_baggage_free_on_destroy)
1241                 free(context->external_baggage_free_on_destroy);
1242
1243         lws_free(context);
1244 }