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