win fix warnings from appveyor
[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                 return NULL;
72
73         vhost->protocol_vh_privs[n] = lws_zalloc(size);
74         return vhost->protocol_vh_privs[n];
75 }
76
77 LWS_VISIBLE void *
78 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot)
79 {
80         int n = 0;
81
82         if (!vhost->protocol_vh_privs)
83                 return NULL;
84
85         while (n < vhost->count_protocols && &vhost->protocols[n] != prot)
86                 n++;
87
88         if (n == vhost->count_protocols) {
89                 lwsl_err("%s: unknown protocol %p\n", __func__, prot);
90                 return NULL;
91         }
92
93         return vhost->protocol_vh_privs[n];
94 }
95
96 static const struct lws_protocol_vhost_options *
97 lws_vhost_protocol_options(struct lws_vhost *vh, const char *name)
98 {
99         const struct lws_protocol_vhost_options *pvo = vh->pvo;
100
101         while (pvo) {
102                 // lwsl_notice("%s: '%s' '%s'\n", __func__, pvo->name, name);
103                 if (!strcmp(pvo->name, name))
104                         return pvo;
105                 pvo = pvo->next;
106         }
107
108         return NULL;
109 }
110
111 int
112 lws_protocol_init(struct lws_context *context)
113 {
114         struct lws_vhost *vh = context->vhost_list;
115         const struct lws_protocol_vhost_options *pvo, *pvo1;
116         struct lws wsi;
117         int n;
118
119         memset(&wsi, 0, sizeof(wsi));
120         wsi.context = context;
121
122         lwsl_notice("%s\n", __func__);
123
124         while (vh) {
125                 wsi.vhost = vh;
126
127                 /* initialize supported protocols on this vhost */
128
129                 for (n = 0; n < vh->count_protocols; n++) {
130                         wsi.protocol = &vh->protocols[n];
131
132                         pvo = lws_vhost_protocol_options(vh,
133                                                          vh->protocols[n].name);
134                         if (pvo) {
135                                 /*
136                                  * linked list of options specific to
137                                  * vh + protocol
138                                  */
139                                 pvo1 = pvo;
140                                 pvo = pvo1->options;
141
142                                 while (pvo) {
143                                         lwsl_notice("    vh %s prot %s opt %s\n",
144                                                         vh->name,
145                                                         vh->protocols[n].name,
146                                                         pvo->name);
147
148                                         if (!strcmp(pvo->name, "default")) {
149                                                 lwsl_notice("Setting default "
150                                                    "protocol for vh %s to %s\n",
151                                                    vh->name,
152                                                    vh->protocols[n].name);
153                                                 vh->default_protocol_index = n;
154                                         }
155                                         pvo = pvo->next;
156                                 }
157
158                                 pvo = pvo1->options;
159                         }
160
161                         /*
162                          * inform all the protocols that they are doing their one-time
163                          * initialization if they want to.
164                          *
165                          * NOTE the wsi is all zeros except for the context, vh and
166                          * protocol ptrs so lws_get_context(wsi) etc can work
167                          */
168                         vh->protocols[n].callback(&wsi,
169                                 LWS_CALLBACK_PROTOCOL_INIT, NULL,
170                                 (void *)pvo, 0);
171                 }
172
173                 vh = vh->vhost_next;
174         }
175
176         context->protocol_init_done = 1;
177
178         return 0;
179 }
180
181 static int
182 callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
183                     void *user, void *in, size_t len)
184 {
185 #ifdef LWS_WITH_CGI
186         struct lws_cgi_args *args;
187         char buf[128];
188         int n;
189 #endif
190
191         switch (reason) {
192         case LWS_CALLBACK_HTTP:
193 #ifndef LWS_NO_SERVER
194                 if (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL))
195                         return -1;
196
197                 if (lws_http_transaction_completed(wsi))
198 #endif
199                         return -1;
200                 break;
201
202         case LWS_CALLBACK_HTTP_WRITEABLE:
203 #ifdef LWS_WITH_CGI
204                 if (wsi->reason_bf & 1) {
205                         if (lws_cgi_write_split_stdout_headers(wsi) < 0)
206                                 return -1;
207
208                         wsi->reason_bf &= ~1;
209                         break;
210                 }
211 #endif
212
213                 break;
214
215 #ifdef LWS_WITH_CGI
216         /* CGI IO events (POLLIN/OUT) appear here, our default policy is:
217          *
218          *  - POST data goes on subprocess stdin
219          *  - subprocess stdout goes on http via writeable callback
220          *  - subprocess stderr goes to the logs
221          */
222         case LWS_CALLBACK_CGI:
223                 args = (struct lws_cgi_args *)in;
224                 switch (args->ch) { /* which of stdin/out/err ? */
225                 case LWS_STDIN:
226                         /* TBD stdin rx flow control */
227                         break;
228                 case LWS_STDOUT:
229                         wsi->reason_bf |= 1;
230                         /* when writing to MASTER would not block */
231                         lws_callback_on_writable(wsi);
232                         break;
233                 case LWS_STDERR:
234                         n = read(lws_get_socket_fd(args->stdwsi[LWS_STDERR]),
235                                                    buf, sizeof(buf) - 1);
236                         if (n > 0) {
237                                 if (buf[n - 1] != '\n')
238                                         buf[n++] = '\n';
239                                 buf[n] = '\0';
240                                 lwsl_notice("CGI-stderr: %s\n", buf);
241                         }
242                         break;
243                 }
244                 break;
245
246         case LWS_CALLBACK_CGI_TERMINATED:
247                 return -1;
248
249         case LWS_CALLBACK_CGI_STDIN_DATA:  /* POST body for stdin */
250                 args = (struct lws_cgi_args *)in;
251                 args->data[args->len] = '\0';
252                 n = write(lws_get_socket_fd(args->stdwsi[LWS_STDIN]),
253                           args->data, args->len);
254                 if (n < args->len)
255                         lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: "
256                                     "sent %d only %d went", n, args->len);
257                 return n;
258 #endif
259         default:
260                 break;
261         }
262
263         return 0;
264 }
265
266 /* list of supported protocols and callbacks */
267
268 static const struct lws_protocols protocols_dummy[] = {
269         /* first protocol must always be HTTP handler */
270
271         {
272                 "http-only",            /* name */
273                 callback_http_dummy,            /* callback */
274                 0,      /* per_session_data_size */
275                 4096,                   /* max frame size / rx buffer */
276         },
277         /*
278          * the other protocols are provided by lws plugins
279          */
280         { NULL, NULL, 0, 0 } /* terminator */
281 };
282
283 LWS_VISIBLE struct lws_vhost *
284 lws_create_vhost(struct lws_context *context,
285                  struct lws_context_creation_info *info)
286 {
287         struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
288                          **vh1 = &context->vhost_list;
289         const struct lws_http_mount *mounts;
290 #ifdef LWS_WITH_PLUGINS
291         struct lws_plugin *plugin = context->plugin_list;
292         struct lws_protocols *lwsp;
293         int m, n, f = !info->pvo;
294 #endif
295         char *p;
296
297         if (!vh)
298                 return NULL;
299
300         if (!info->protocols)
301                 info->protocols = &protocols_dummy[0];
302
303         vh->context = context;
304         if (!info->vhost_name)
305                 vh->name = "default";
306         else
307                 vh->name = info->vhost_name;
308
309         vh->iface = info->iface;
310         for (vh->count_protocols = 0;
311              info->protocols[vh->count_protocols].callback;
312              vh->count_protocols++)
313                 ;
314
315         vh->options = info->options;
316         vh->pvo = info->pvo;
317         vh->keepalive_timeout = info->keepalive_timeout;
318
319 #ifdef LWS_WITH_PLUGINS
320         if (plugin) {
321                 /*
322                  * give the vhost a unified list of protocols including the
323                  * ones that came from plugins
324                  */
325                 lwsp = lws_zalloc(sizeof(struct lws_protocols) *
326                                            (vh->count_protocols +
327                                            context->plugin_protocol_count + 1));
328                 if (!lwsp)
329                         return NULL;
330
331                 m = vh->count_protocols;
332                 memcpy(lwsp, info->protocols,
333                        sizeof(struct lws_protocols) * m);
334
335                 /* for compatibility, all protocols enabled on vhost if only
336                  * the default vhost exists.  Otherwise only vhosts who ask
337                  * for a protocol get it enabled.
338                  */
339
340                 if (info->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)
341                         f = 0;
342
343                 while (plugin) {
344                         for (n = 0; n < plugin->caps.count_protocols; n++) {
345                                 /*
346                                  * for compatibility's sake, no pvo implies
347                                  * allow all protocols
348                                  */
349                                 if (f || lws_vhost_protocol_options(vh,
350                                     plugin->caps.protocols[n].name)) {
351                                         memcpy(&lwsp[m],
352                                                &plugin->caps.protocols[n],
353                                                sizeof(struct lws_protocols));
354                                         m++;
355                                         vh->count_protocols++;
356                                 }
357                         }
358                         plugin = plugin->list;
359                 }
360                 vh->protocols = lwsp;
361         } else
362 #endif
363                 vh->protocols = info->protocols;
364
365         vh->same_vh_protocol_list = (struct lws **)
366                         lws_zalloc(sizeof(struct lws *) * vh->count_protocols);
367
368         vh->mount_list = info->mounts;
369
370 #ifdef LWS_USE_UNIX_SOCK
371         if (LWS_UNIX_SOCK_ENABLED(context)) {
372                 lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n",
373                                 vh->name, info->iface, vh->count_protocols);
374         } else
375 #endif
376         lwsl_notice("Creating Vhost '%s' port %d, %d protocols\n",
377                         vh->name, info->port, vh->count_protocols);
378
379         mounts = info->mounts;
380         while (mounts) {
381                 lwsl_notice("   mounting %s%s to %s\n",
382                                 mount_protocols[mounts->origin_protocol],
383                                 mounts->origin, mounts->mountpoint);
384                 mounts = mounts->mount_next;
385         }
386
387 #ifndef LWS_NO_EXTENSIONS
388 #ifdef LWS_WITH_PLUGINS
389         if (context->plugin_extension_count) {
390
391                 m = 0;
392                 while (info->extensions && info->extensions[m].callback)
393                         m++;
394
395                 /*
396                  * give the vhost a unified list of extensions including the
397                  * ones that came from plugins
398                  */
399                 vh->extensions = lws_zalloc(sizeof(struct lws_extension) *
400                                            (m +
401                                            context->plugin_extension_count + 1));
402                 if (!vh->extensions)
403                         return NULL;
404
405                 memcpy((struct lws_extension *)vh->extensions, info->extensions,
406                        sizeof(struct lws_extension) * m);
407                 plugin = context->plugin_list;
408                 while (plugin) {
409                         memcpy((struct lws_extension *)&vh->extensions[m],
410                                 plugin->caps.extensions,
411                                sizeof(struct lws_extension) *
412                                plugin->caps.count_extensions);
413                         m += plugin->caps.count_extensions;
414                         plugin = plugin->list;
415                 }
416         } else
417 #endif
418                 vh->extensions = info->extensions;
419 #endif
420
421         vh->listen_port = info->port;
422         vh->http_proxy_port = 0;
423         vh->http_proxy_address[0] = '\0';
424
425         /* either use proxy from info, or try get it from env var */
426
427         if (info->http_proxy_address) {
428                 /* override for backwards compatibility */
429                 if (info->http_proxy_port)
430                         vh->http_proxy_port = info->http_proxy_port;
431                 lws_set_proxy(vh, info->http_proxy_address);
432         } else {
433 #ifdef LWS_HAVE_GETENV
434                 p = getenv("http_proxy");
435                 if (p)
436                         lws_set_proxy(vh, p);
437 #endif
438         }
439
440         vh->ka_time = info->ka_time;
441         vh->ka_interval = info->ka_interval;
442         vh->ka_probes = info->ka_probes;
443
444         if (vh->options & LWS_SERVER_OPTION_STS)
445                 lwsl_notice("   STS enabled\n");
446
447 #ifdef LWS_WITH_ACCESS_LOG
448         if (info->log_filepath) {
449                 vh->log_fd = open(info->log_filepath, O_CREAT | O_APPEND | O_RDWR, 0600);
450                 if (vh->log_fd == (int)LWS_INVALID_FILE) {
451                         lwsl_err("unable to open log filepath %s\n",
452                                  info->log_filepath);
453                         goto bail;
454                 }
455 #ifndef WIN32
456                 if (context->uid != -1)
457                         if (chown(info->log_filepath, context->uid,
458                                   context->gid) == -1)
459                                 lwsl_err("unable to chown log file %s\n",
460                                                 info->log_filepath);
461 #endif
462         } else
463                 vh->log_fd = (int)LWS_INVALID_FILE;
464 #endif
465
466         if (lws_context_init_server_ssl(info, vh))
467                 goto bail;
468
469         if (lws_context_init_client_ssl(info, vh))
470                 goto bail;
471
472         if (lws_context_init_server(info, vh))
473                 goto bail;
474
475         while (1) {
476                 if (!(*vh1)) {
477                         *vh1 = vh;
478                         break;
479                 }
480                 vh1 = &(*vh1)->vhost_next;
481         };
482
483         return vh;
484
485 bail:
486         lws_free(vh);
487
488         return NULL;
489 }
490
491 /**
492  * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost
493  *
494  * @info: client ssl related info
495  * @vhost: which vhost to initialize client ssl operations on
496  *
497  * You only need to call this if you plan on using SSL client connections on
498  * the vhost.  For non-SSL client connections, it's not necessary to call this.
499  *
500  * The following members of @info are used during the call
501  *
502  *       - @options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,
503  *           otherwise the call does nothing
504  *       - @provided_client_ssl_ctx must be NULL to get a generated client
505  *           ssl context, otherwise you can pass a prepared one in by setting it
506  *       - @ssl_cipher_list may be NULL or set to the client valid cipher list
507  *       - @ssl_ca_filepath may be NULL or client cert filepath
508  *       - @ssl_cert_filepath may be NULL or client cert filepath
509  *       - @ssl_private_key_filepath may be NULL or client cert private key
510  *
511  * You must create your vhost explicitly if you want to use this, so you have
512  * a pointer to the vhost.  Create the context first with the option flag
513  * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with
514  * the same info struct.
515  */
516 LWS_VISIBLE int
517 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
518                           struct lws_vhost *vhost)
519 {
520         struct lws_context_creation_info i;
521
522         memcpy(&i, info, sizeof(i));
523         i.port = CONTEXT_PORT_NO_LISTEN;
524
525         return lws_context_init_client_ssl(&i, vhost);
526 }
527
528 /**
529  * lws_create_context() - Create the websocket handler
530  * @info:       pointer to struct with parameters
531  *
532  *      This function creates the listening socket (if serving) and takes care
533  *      of all initialization in one step.
534  *
535  *      After initialization, it returns a struct lws_context * that
536  *      represents this server.  After calling, user code needs to take care
537  *      of calling lws_service() with the context pointer to get the
538  *      server's sockets serviced.  This must be done in the same process
539  *      context as the initialization call.
540  *
541  *      The protocol callback functions are called for a handful of events
542  *      including http requests coming in, websocket connections becoming
543  *      established, and data arriving; it's also called periodically to allow
544  *      async transmission.
545  *
546  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
547  *      at that time websocket protocol has not been negotiated.  Other
548  *      protocols after the first one never see any HTTP callack activity.
549  *
550  *      The server created is a simple http server by default; part of the
551  *      websocket standard is upgrading this http connection to a websocket one.
552  *
553  *      This allows the same server to provide files like scripts and favicon /
554  *      images or whatever over http and dynamic data over websockets all in
555  *      one place; they're all handled in the user callback.
556  */
557 LWS_VISIBLE struct lws_context *
558 lws_create_context(struct lws_context_creation_info *info)
559 {
560         struct lws_context *context = NULL;
561         struct lws wsi;
562 #ifndef LWS_NO_DAEMONIZE
563         int pid_daemon = get_daemonize_pid();
564 #endif
565         int n, m;
566 #if defined(__ANDROID__)
567         struct rlimit rt;
568 #endif
569
570         lwsl_notice("Initial logging level %d\n", log_level);
571         lwsl_notice("Libwebsockets version: %s\n", library_version);
572 #if LWS_POSIX
573 #ifdef LWS_USE_IPV6
574         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
575                 lwsl_notice("IPV6 compiled in and enabled\n");
576         else
577                 lwsl_notice("IPV6 compiled in but disabled\n");
578 #else
579         lwsl_notice("IPV6 not compiled in\n");
580 #endif
581         lws_feature_status_libev(info);
582         lws_feature_status_libuv(info);
583 #endif
584         lwsl_info(" LWS_DEF_HEADER_LEN    : %u\n", LWS_DEF_HEADER_LEN);
585         lwsl_info(" LWS_MAX_PROTOCOLS     : %u\n", LWS_MAX_PROTOCOLS);
586         lwsl_info(" LWS_MAX_SMP           : %u\n", LWS_MAX_SMP);
587         lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
588         lwsl_info(" sizeof (*info)        : %u\n", sizeof(*info));
589 #if LWS_POSIX
590         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
591 #endif
592         if (lws_plat_context_early_init())
593                 return NULL;
594
595         context = lws_zalloc(sizeof(struct lws_context));
596         if (!context) {
597                 lwsl_err("No memory for websocket context\n");
598                 return NULL;
599         }
600
601         context->time_up = time(NULL);
602 #ifndef LWS_NO_DAEMONIZE
603         if (pid_daemon) {
604                 context->started_with_parent = pid_daemon;
605                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
606         }
607 #endif
608 #if defined(__ANDROID__)
609                 n = getrlimit ( RLIMIT_NOFILE,&rt);
610                 if (-1 == n) {
611                         lwsl_err("Get RLIMIT_NOFILE failed!\n");
612                         return NULL;
613                 }
614                 context->max_fds = rt.rlim_cur;
615 #else
616                 context->max_fds = getdtablesize();
617 #endif
618
619         if (info->count_threads)
620                 context->count_threads = info->count_threads;
621         else
622                 context->count_threads = 1;
623
624         if (context->count_threads > LWS_MAX_SMP)
625                 context->count_threads = LWS_MAX_SMP;
626
627         context->token_limits = info->token_limits;
628
629         context->options = info->options;
630
631         if (info->timeout_secs)
632                 context->timeout_secs = info->timeout_secs;
633         else
634                 context->timeout_secs = AWAITING_TIMEOUT;
635
636         lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
637
638         if (info->max_http_header_data)
639                 context->max_http_header_data = info->max_http_header_data;
640         else
641                 context->max_http_header_data = LWS_DEF_HEADER_LEN;
642         if (info->max_http_header_pool)
643                 context->max_http_header_pool = info->max_http_header_pool;
644         else
645                 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
646
647         /*
648          * Allocate the per-thread storage for scratchpad buffers,
649          * and header data pool
650          */
651         for (n = 0; n < context->count_threads; n++) {
652                 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
653                 if (!context->pt[n].serv_buf) {
654                         lwsl_err("OOM\n");
655                         return NULL;
656                 }
657
658                 context->pt[n].context = context;
659                 context->pt[n].tid = n;
660                 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
661                                                        context->max_http_header_pool);
662                 if (!context->pt[n].http_header_data)
663                         goto bail;
664
665                 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
666                                               context->max_http_header_pool);
667                 for (m = 0; m < context->max_http_header_pool; m++)
668                         context->pt[n].ah_pool[m].data =
669                                 (char *)context->pt[n].http_header_data +
670                                 (m * context->max_http_header_data);
671                 if (!context->pt[n].ah_pool)
672                         goto bail;
673
674                 lws_pt_mutex_init(&context->pt[n]);
675         }
676
677         if (info->fd_limit_per_thread)
678                 context->fd_limit_per_thread = info->fd_limit_per_thread;
679         else
680                 context->fd_limit_per_thread = context->max_fds /
681                                                context->count_threads;
682
683         lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
684                     context->fd_limit_per_thread);
685
686         memset(&wsi, 0, sizeof(wsi));
687         wsi.context = context;
688
689         if (!info->ka_interval && info->ka_time > 0) {
690                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
691                 return NULL;
692         }
693
694 #ifdef LWS_USE_LIBEV
695         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
696          * enable libev mediated SIGINT handling with a default handler of
697          * lws_sigint_cb. The handler can be overridden or disabled
698          * by invoking lws_sigint_cfg after creating the context, but
699          * before invoking lws_initloop:
700          */
701         context->use_ev_sigint = 1;
702         context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
703 #endif /* LWS_USE_LIBEV */
704 #ifdef LWS_USE_LIBUV
705         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
706          * enable libev mediated SIGINT handling with a default handler of
707          * lws_sigint_cb. The handler can be overridden or disabled
708          * by invoking lws_sigint_cfg after creating the context, but
709          * before invoking lws_initloop:
710          */
711         context->use_ev_sigint = 1;
712         context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
713 #endif
714
715         lwsl_info(" mem: context:         %5u bytes (%d ctx + (%d thr x %d))\n",
716                   sizeof(struct lws_context) +
717                   (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
718                   sizeof(struct lws_context),
719                   context->count_threads,
720                   LWS_MAX_SOCKET_IO_BUF);
721
722         lwsl_info(" mem: http hdr rsvd:   %5u bytes (%u thr x (%u + %u) x %u))\n",
723                     (context->max_http_header_data +
724                      sizeof(struct allocated_headers)) *
725                     context->max_http_header_pool * context->count_threads,
726                     context->count_threads,
727                     context->max_http_header_data,
728                     sizeof(struct allocated_headers),
729                     context->max_http_header_pool);
730         n = sizeof(struct lws_pollfd) * context->count_threads *
731             context->fd_limit_per_thread;
732         context->pt[0].fds = lws_zalloc(n);
733         if (context->pt[0].fds == NULL) {
734                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
735                 goto bail;
736         }
737         lwsl_info(" mem: pollfd map:      %5u\n", n);
738
739         if (info->server_string) {
740                 context->server_string = info->server_string;
741                 context->server_string_len = (short)
742                                 strlen(context->server_string);
743         } else {
744                 context->server_string = "libwebsockets";
745                 context->server_string_len = 13;
746         }
747
748 #if LWS_MAX_SMP > 1
749         /* each thread serves his own chunk of fds */
750         for (n = 1; n < (int)info->count_threads; n++)
751                 context->pt[n].fds = context->pt[n - 1].fds +
752                                      context->fd_limit_per_thread;
753 #endif
754
755         if (lws_plat_init(context, info))
756                 goto bail;
757
758         lws_context_init_ssl_library(info);
759
760         context->user_space = info->user;
761
762         /*
763          * if he's not saying he'll make his own vhosts later then act
764          * compatibly and make a default vhost using the data in the info
765          */
766         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
767                 if (!lws_create_vhost(context, info)) {
768                         lwsl_err("Failed to create default vhost\n");
769                         return NULL;
770                 }
771
772         lws_context_init_extensions(info, context);
773
774         lwsl_notice(" mem: per-conn:        %5u bytes + protocol rx buf\n",
775                     sizeof(struct lws));
776
777         strcpy(context->canonical_hostname, "unknown");
778         lws_server_get_canonical_hostname(context, info);
779
780         context->uid = info->uid;
781         context->gid = info->gid;
782
783         /*
784          * drop any root privs for this process
785          * to listen on port < 1023 we would have needed root, but now we are
786          * listening, we don't want the power for anything else
787          */
788         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
789                 lws_plat_drop_app_privileges(info);
790
791         /*
792          * give all extensions a chance to create any per-context
793          * allocations they need
794          */
795         if (info->port != CONTEXT_PORT_NO_LISTEN) {
796                 if (lws_ext_cb_all_exts(context, NULL,
797                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
798                         goto bail;
799         } else
800                 if (lws_ext_cb_all_exts(context, NULL,
801                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
802                         goto bail;
803
804         return context;
805
806 bail:
807         lws_context_destroy(context);
808         return NULL;
809 }
810
811 /**
812  * lws_context_destroy() - Destroy the websocket context
813  * @context:    Websocket context
814  *
815  *      This function closes any active connections and then frees the
816  *      context.  After calling this, any further use of the context is
817  *      undefined.
818  */
819 LWS_VISIBLE void
820 lws_context_destroy(struct lws_context *context)
821 {
822         const struct lws_protocols *protocol = NULL;
823         struct lws_context_per_thread *pt;
824         struct lws_vhost *vh = NULL, *vh1;
825         struct lws wsi;
826         int n, m;
827
828         lwsl_notice("%s\n", __func__);
829
830         if (!context)
831                 return;
832
833         m = context->count_threads;
834         context->being_destroyed = 1;
835
836         memset(&wsi, 0, sizeof(wsi));
837         wsi.context = context;
838
839 #ifdef LWS_LATENCY
840         if (context->worst_latency_info[0])
841                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
842 #endif
843
844         while (m--) {
845                 pt = &context->pt[m];
846
847                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
848                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
849                         if (!wsi)
850                                 continue;
851
852                         lws_close_free_wsi(wsi,
853                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
854                                 /* no protocol close */);
855                         n--;
856                 }
857                 lws_pt_mutex_destroy(pt);
858         }
859         /*
860          * give all extensions a chance to clean up any per-context
861          * allocations they might have made
862          */
863
864         n = lws_ext_cb_all_exts(context, NULL,
865                                 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
866
867         n = lws_ext_cb_all_exts(context, NULL,
868                                 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
869
870         /*
871          * inform all the protocols that they are done and will have no more
872          * callbacks.
873          *
874          * We can't free things until after the event loop shuts down.
875          */
876         if (context->protocol_init_done)
877                 vh = context->vhost_list;
878         while (vh) {
879                 wsi.vhost = vh;
880                 protocol = vh->protocols;
881                 if (protocol) {
882                         n = 0;
883                         while (n < vh->count_protocols) {
884                                 wsi.protocol = protocol;
885                                 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
886                                                    NULL, NULL, 0);
887                                 protocol++;
888                                 n++;
889                         }
890                 }
891
892                 vh = vh->vhost_next;
893         }
894
895         for (n = 0; n < context->count_threads; n++) {
896                 pt = &context->pt[n];
897
898                 lws_libev_destroyloop(context, n);
899                 lws_libuv_destroyloop(context, n);
900
901                 lws_free_set_NULL(context->pt[n].serv_buf);
902                 if (pt->ah_pool)
903                         lws_free(pt->ah_pool);
904                 if (pt->http_header_data)
905                         lws_free(pt->http_header_data);
906         }
907         lws_plat_context_early_destroy(context);
908         lws_ssl_context_destroy(context);
909
910         if (context->pt[0].fds)
911                 lws_free_set_NULL(context->pt[0].fds);
912
913         /* free all the vhost allocations */
914
915         vh = context->vhost_list;
916         while (vh) {
917                 protocol = vh->protocols;
918                 if (protocol) {
919                         n = 0;
920                         while (n < vh->count_protocols) {
921                                 if (vh->protocol_vh_privs &&
922                                     vh->protocol_vh_privs[n]) {
923                                         lws_free(vh->protocol_vh_privs[n]);
924                                         vh->protocol_vh_privs[n] = NULL;
925                                 }
926                                 protocol++;
927                                 n++;
928                         }
929                 }
930                 if (vh->protocol_vh_privs)
931                         lws_free(vh->protocol_vh_privs);
932                 lws_ssl_SSL_CTX_destroy(vh);
933                 lws_free(vh->same_vh_protocol_list);
934 #ifdef LWS_WITH_PLUGINS
935                 if (context->plugin_list)
936                         lws_free((void *)vh->protocols);
937 #ifndef LWS_NO_EXTENSIONS
938                 if (context->plugin_extension_count)
939                         lws_free((void *)vh->extensions);
940 #endif
941 #endif
942 #ifdef LWS_WITH_ACCESS_LOG
943                 if (vh->log_fd != (int)LWS_INVALID_FILE)
944                         close(vh->log_fd);
945 #endif
946
947                 vh1 = vh->vhost_next;
948                 lws_free(vh);
949                 vh = vh1;
950         }
951
952         lws_plat_context_late_destroy(context);
953
954         lws_free(context);
955 }