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