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