introduce vhosts
[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 };
49
50 LWS_VISIBLE LWS_EXTERN int
51 lws_write_http_mount(struct lws_http_mount *next, struct lws_http_mount **res,
52                      void *store, const char *mountpoint, const char *origin,
53                      const char *def)
54 {
55         struct lws_http_mount *m;
56         void *orig = store;
57         unsigned long l = (unsigned long)store;
58         int n;
59
60         if (l & 15)
61                 l += 16 - (l & 15);
62
63         store = (void *)l;
64         m = (struct lws_http_mount *)store;
65         *res = m;
66
67         m->def = def;
68         m->mountpoint = mountpoint;
69         m->mountpoint_len = (unsigned char)strlen(mountpoint);
70         m->mount_next = NULL;
71         if (next)
72                 next->mount_next = m;
73         for (n = 0; n < ARRAY_SIZE(mount_protocols); n++)
74                 if (!strncmp(origin, mount_protocols[n],
75                      strlen(mount_protocols[n]))) {
76                         m->origin_protocol = n;
77                         m->origin = origin + strlen(mount_protocols[n]);
78                         break;
79                 }
80
81         if (n == ARRAY_SIZE(mount_protocols)) {
82                 lwsl_err("unsupported protocol://\n");
83                 return 0; /* ie, fail */
84         }
85
86         return ((char *)store + sizeof(*m)) - (char *)orig;
87 }
88
89 LWS_VISIBLE struct lws_vhost *
90 lws_create_vhost(struct lws_context *context,
91                  struct lws_context_creation_info *info,
92                  struct lws_http_mount *mounts)
93 {
94         struct lws_vhost *vh = lws_zalloc(sizeof(*vh)),
95                          **vh1 = &context->vhost_list;
96         struct lws wsi;
97         char *p;
98         int n;
99
100         if (!vh)
101                 return NULL;
102
103         vh->context = context;
104         if (!info->vhost_name)
105                 vh->name = "default";
106         else
107                 vh->name = info->vhost_name;
108
109         vh->iface = info->iface;
110         vh->protocols = info->protocols;
111         for (vh->count_protocols = 0;
112              info->protocols[vh->count_protocols].callback;
113              vh->count_protocols++)
114                 ;
115
116         vh->mount_list = mounts;
117
118         lwsl_notice("Creating Vhost '%s' port %d, %d protocols\n",
119                         vh->name, info->port, vh->count_protocols);
120
121         while (mounts) {
122                 lwsl_notice("   mounting %s%s to %s\n",
123                                 mount_protocols[mounts->origin_protocol],
124                                 mounts->origin, mounts->mountpoint);
125                 mounts = mounts->mount_next;
126         }
127
128 #ifndef LWS_NO_EXTENSIONS
129         vh->extensions = info->extensions;
130 #endif
131
132         vh->listen_port = info->port;
133         vh->http_proxy_port = 0;
134         vh->http_proxy_address[0] = '\0';
135
136         /* either use proxy from info, or try get it from env var */
137
138         if (info->http_proxy_address) {
139                 /* override for backwards compatibility */
140                 if (info->http_proxy_port)
141                         vh->http_proxy_port = info->http_proxy_port;
142                 lws_set_proxy(vh, info->http_proxy_address);
143         } else {
144 #ifdef LWS_HAVE_GETENV
145                 p = getenv("http_proxy");
146                 if (p)
147                         lws_set_proxy(vh, p);
148 #endif
149         }
150
151         memset(&wsi, 0, sizeof(wsi));
152         wsi.context = context;
153         wsi.vhost = vh;
154
155         /* initialize supported protocols */
156
157         for (n = 0; n < vh->count_protocols; n++)
158                 /*
159                  * inform all the protocols that they are doing their one-time
160                  * initialization if they want to.
161                  *
162                  * NOTE the wsi is all zeros except for the context & vh ptrs
163                  * so lws_get_context(wsi) can work in the callback.
164                  */
165                 info->protocols[n].callback(&wsi,
166                                 LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
167
168         vh->ka_time = info->ka_time;
169         vh->ka_interval = info->ka_interval;
170         vh->ka_probes = info->ka_probes;
171
172         if (lws_context_init_server_ssl(info, vh))
173                 goto bail;
174
175         if (lws_context_init_client_ssl(info, vh))
176                 goto bail;
177
178         if (lws_context_init_server(info, vh))
179                 goto bail;
180
181         while (1) {
182                 if (!(*vh1)) {
183                         *vh1 = vh;
184                         break;
185                 }
186                 vh1 = &(*vh1)->vhost_next;
187         };
188
189         return vh;
190
191 bail:
192         lws_free(vh);
193
194         return NULL;
195 }
196
197 /**
198  * lws_create_context() - Create the websocket handler
199  * @info:       pointer to struct with parameters
200  *
201  *      This function creates the listening socket (if serving) and takes care
202  *      of all initialization in one step.
203  *
204  *      After initialization, it returns a struct lws_context * that
205  *      represents this server.  After calling, user code needs to take care
206  *      of calling lws_service() with the context pointer to get the
207  *      server's sockets serviced.  This must be done in the same process
208  *      context as the initialization call.
209  *
210  *      The protocol callback functions are called for a handful of events
211  *      including http requests coming in, websocket connections becoming
212  *      established, and data arriving; it's also called periodically to allow
213  *      async transmission.
214  *
215  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
216  *      at that time websocket protocol has not been negotiated.  Other
217  *      protocols after the first one never see any HTTP callack activity.
218  *
219  *      The server created is a simple http server by default; part of the
220  *      websocket standard is upgrading this http connection to a websocket one.
221  *
222  *      This allows the same server to provide files like scripts and favicon /
223  *      images or whatever over http and dynamic data over websockets all in
224  *      one place; they're all handled in the user callback.
225  */
226 LWS_VISIBLE struct lws_context *
227 lws_create_context(struct lws_context_creation_info *info)
228 {
229         struct lws_context *context = NULL;
230         struct lws wsi;
231 #ifndef LWS_NO_DAEMONIZE
232         int pid_daemon = get_daemonize_pid();
233 #endif
234         int n, m;
235
236         lwsl_notice("Initial logging level %d\n", log_level);
237         lwsl_notice("Libwebsockets version: %s\n", library_version);
238 #if LWS_POSIX
239 #ifdef LWS_USE_IPV6
240         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
241                 lwsl_notice("IPV6 compiled in and enabled\n");
242         else
243                 lwsl_notice("IPV6 compiled in but disabled\n");
244 #else
245         lwsl_notice("IPV6 not compiled in\n");
246 #endif
247         lws_feature_status_libev(info);
248         lws_feature_status_libuv(info);
249 #endif
250         lwsl_info(" LWS_DEF_HEADER_LEN    : %u\n", LWS_DEF_HEADER_LEN);
251         lwsl_info(" LWS_MAX_PROTOCOLS     : %u\n", LWS_MAX_PROTOCOLS);
252         lwsl_info(" LWS_MAX_SMP           : %u\n", LWS_MAX_SMP);
253         lwsl_info(" SPEC_LATEST_SUPPORTED : %u\n", SPEC_LATEST_SUPPORTED);
254         lwsl_info(" sizeof (*info)        : %u\n", sizeof(*info));
255 #if LWS_POSIX
256         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
257 #endif
258         if (lws_plat_context_early_init())
259                 return NULL;
260
261         context = lws_zalloc(sizeof(struct lws_context));
262         if (!context) {
263                 lwsl_err("No memory for websocket context\n");
264                 return NULL;
265         }
266 #ifndef LWS_NO_DAEMONIZE
267         if (pid_daemon) {
268                 context->started_with_parent = pid_daemon;
269                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
270         }
271 #endif
272         context->max_fds = getdtablesize();
273
274         if (info->count_threads)
275                 context->count_threads = info->count_threads;
276         else
277                 context->count_threads = 1;
278
279         if (context->count_threads > LWS_MAX_SMP)
280                 context->count_threads = LWS_MAX_SMP;
281
282         context->token_limits = info->token_limits;
283
284         context->options = info->options;
285
286         if (info->timeout_secs)
287                 context->timeout_secs = info->timeout_secs;
288         else
289                 context->timeout_secs = AWAITING_TIMEOUT;
290
291         lwsl_info(" default timeout (secs): %u\n", context->timeout_secs);
292
293         if (info->max_http_header_data)
294                 context->max_http_header_data = info->max_http_header_data;
295         else
296                 context->max_http_header_data = LWS_DEF_HEADER_LEN;
297         if (info->max_http_header_pool)
298                 context->max_http_header_pool = info->max_http_header_pool;
299         else
300                 context->max_http_header_pool = LWS_DEF_HEADER_POOL;
301
302         /*
303          * Allocate the per-thread storage for scratchpad buffers,
304          * and header data pool
305          */
306         for (n = 0; n < context->count_threads; n++) {
307                 context->pt[n].serv_buf = lws_zalloc(LWS_MAX_SOCKET_IO_BUF);
308                 if (!context->pt[n].serv_buf) {
309                         lwsl_err("OOM\n");
310                         return NULL;
311                 }
312
313                 context->pt[n].context = context;
314                 context->pt[n].tid = n;
315                 context->pt[n].http_header_data = lws_malloc(context->max_http_header_data *
316                                                        context->max_http_header_pool);
317                 if (!context->pt[n].http_header_data)
318                         goto bail;
319
320                 context->pt[n].ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
321                                               context->max_http_header_pool);
322                 for (m = 0; m < context->max_http_header_pool; m++)
323                         context->pt[n].ah_pool[m].data =
324                                 (char *)context->pt[n].http_header_data +
325                                 (m * context->max_http_header_data);
326                 if (!context->pt[n].ah_pool)
327                         goto bail;
328
329                 lws_pt_mutex_init(&context->pt[n]);
330         }
331
332         if (info->fd_limit_per_thread)
333                 context->fd_limit_per_thread = info->fd_limit_per_thread;
334         else
335                 context->fd_limit_per_thread = context->max_fds /
336                                                context->count_threads;
337
338         lwsl_notice(" Threads: %d each %d fds\n", context->count_threads,
339                     context->fd_limit_per_thread);
340
341         memset(&wsi, 0, sizeof(wsi));
342         wsi.context = context;
343
344         if (!info->ka_interval && info->ka_time > 0) {
345                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
346                 return NULL;
347         }
348
349 #ifdef LWS_USE_LIBEV
350         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
351          * enable libev mediated SIGINT handling with a default handler of
352          * lws_sigint_cb. The handler can be overridden or disabled
353          * by invoking lws_sigint_cfg after creating the context, but
354          * before invoking lws_initloop:
355          */
356         context->use_ev_sigint = 1;
357         context->lws_ev_sigint_cb = &lws_ev_sigint_cb;
358 #endif /* LWS_USE_LIBEV */
359 #ifdef LWS_USE_LIBUV
360         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
361          * enable libev mediated SIGINT handling with a default handler of
362          * lws_sigint_cb. The handler can be overridden or disabled
363          * by invoking lws_sigint_cfg after creating the context, but
364          * before invoking lws_initloop:
365          */
366         context->use_ev_sigint = 1;
367         context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
368 #endif
369
370         lwsl_info(" mem: context:         %5u bytes (%d ctx + (%d thr x %d))\n",
371                   sizeof(struct lws_context) +
372                   (context->count_threads * LWS_MAX_SOCKET_IO_BUF),
373                   sizeof(struct lws_context),
374                   context->count_threads,
375                   LWS_MAX_SOCKET_IO_BUF);
376
377         lwsl_info(" mem: http hdr rsvd:   %5u bytes (%u thr x (%u + %u) x %u))\n",
378                     (context->max_http_header_data +
379                      sizeof(struct allocated_headers)) *
380                     context->max_http_header_pool * context->count_threads,
381                     context->count_threads,
382                     context->max_http_header_data,
383                     sizeof(struct allocated_headers),
384                     context->max_http_header_pool);
385         n = sizeof(struct lws_pollfd) * context->count_threads *
386             context->fd_limit_per_thread;
387         context->pt[0].fds = lws_zalloc(n);
388         if (context->pt[0].fds == NULL) {
389                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
390                 goto bail;
391         }
392         lwsl_info(" mem: pollfd map:      %5u\n", n);
393
394 #if LWS_MAX_SMP > 1
395         /* each thread serves his own chunk of fds */
396         for (n = 1; n < (int)info->count_threads; n++)
397                 context->pt[n].fds = context->pt[n - 1].fds +
398                                      context->fd_limit_per_thread;
399 #endif
400
401         if (lws_plat_init(context, info))
402                 goto bail;
403
404         lws_context_init_ssl_library(info);
405
406         /*
407          * if he's not saying he'll make his own vhosts later then act
408          * compatibly and make a default vhost using the data in the info
409          */
410         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
411                 if (!lws_create_vhost(context, info, NULL)) {
412                         lwsl_err("Failed to create default vhost\n");
413                         return NULL;
414                 }
415
416         lws_context_init_extensions(info, context);
417
418         context->user_space = info->user;
419
420         lwsl_notice(" mem: per-conn:        %5u bytes + protocol rx buf\n",
421                     sizeof(struct lws));
422
423         strcpy(context->canonical_hostname, "unknown");
424         lws_server_get_canonical_hostname(context, info);
425
426         context->uid = info->uid;
427         context->gid = info->gid;
428
429         /*
430          * drop any root privs for this process
431          * to listen on port < 1023 we would have needed root, but now we are
432          * listening, we don't want the power for anything else
433          */
434         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
435                 lws_plat_drop_app_privileges(info);
436
437         /*
438          * give all extensions a chance to create any per-context
439          * allocations they need
440          */
441         if (info->port != CONTEXT_PORT_NO_LISTEN) {
442                 if (lws_ext_cb_all_exts(context, NULL,
443                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
444                         goto bail;
445         } else
446                 if (lws_ext_cb_all_exts(context, NULL,
447                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
448                         goto bail;
449
450         return context;
451
452 bail:
453         lws_context_destroy(context);
454         return NULL;
455 }
456
457 /**
458  * lws_context_destroy() - Destroy the websocket context
459  * @context:    Websocket context
460  *
461  *      This function closes any active connections and then frees the
462  *      context.  After calling this, any further use of the context is
463  *      undefined.
464  */
465 LWS_VISIBLE void
466 lws_context_destroy(struct lws_context *context)
467 {
468         const struct lws_protocols *protocol = NULL;
469         struct lws_context_per_thread *pt;
470         struct lws_vhost *vh;
471         struct lws wsi;
472         int n, m;
473
474         lwsl_notice("%s\n", __func__);
475
476         if (!context)
477                 return;
478
479         m = context->count_threads;
480         context->being_destroyed = 1;
481
482         memset(&wsi, 0, sizeof(wsi));
483         wsi.context = context;
484
485 #ifdef LWS_LATENCY
486         if (context->worst_latency_info[0])
487                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
488 #endif
489
490         while (m--) {
491                 pt = &context->pt[m];
492
493                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
494                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
495                         if (!wsi)
496                                 continue;
497
498                         lws_close_free_wsi(wsi,
499                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
500                                 /* no protocol close */);
501                         n--;
502                 }
503         }
504         /*
505          * give all extensions a chance to clean up any per-context
506          * allocations they might have made
507          */
508
509         n = lws_ext_cb_all_exts(context, NULL,
510                                 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
511
512         n = lws_ext_cb_all_exts(context, NULL,
513                                 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
514
515         /*
516          * inform all the protocols that they are done and will have no more
517          * callbacks
518          */
519         vh = context->vhost_list;
520         while (vh) {
521                 protocol = vh->protocols;
522                 if (protocol)
523                         while (protocol->callback) {
524                                 protocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,
525                                                    NULL, NULL, 0);
526                                 protocol++;
527                         }
528                 lws_ssl_SSL_CTX_destroy(vh);
529                 vh = vh->vhost_next;
530         }
531
532         for (n = 0; n < context->count_threads; n++) {
533                 pt = &context->pt[n];
534
535                 lws_libev_destroyloop(context, n);
536                 lws_libuv_destroyloop(context, n);
537
538                 lws_free_set_NULL(context->pt[n].serv_buf);
539                 if (pt->ah_pool)
540                         lws_free(pt->ah_pool);
541                 if (pt->http_header_data)
542                         lws_free(pt->http_header_data);
543         }
544         lws_plat_context_early_destroy(context);
545         lws_ssl_context_destroy(context);
546
547         if (context->pt[0].fds)
548                 lws_free_set_NULL(context->pt[0].fds);
549
550         lws_plat_context_late_destroy(context);
551
552         lws_free(context);
553 }