extension permessage deflate
[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
38 LWS_VISIBLE const char *
39 lws_get_library_version(void)
40 {
41         return library_version;
42 }
43
44 /**
45  * lws_create_context() - Create the websocket handler
46  * @info:       pointer to struct with parameters
47  *
48  *      This function creates the listening socket (if serving) and takes care
49  *      of all initialization in one step.
50  *
51  *      After initialization, it returns a struct lws_context * that
52  *      represents this server.  After calling, user code needs to take care
53  *      of calling lws_service() with the context pointer to get the
54  *      server's sockets serviced.  This must be done in the same process
55  *      context as the initialization call.
56  *
57  *      The protocol callback functions are called for a handful of events
58  *      including http requests coming in, websocket connections becoming
59  *      established, and data arriving; it's also called periodically to allow
60  *      async transmission.
61  *
62  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
63  *      at that time websocket protocol has not been negotiated.  Other
64  *      protocols after the first one never see any HTTP callack activity.
65  *
66  *      The server created is a simple http server by default; part of the
67  *      websocket standard is upgrading this http connection to a websocket one.
68  *
69  *      This allows the same server to provide files like scripts and favicon /
70  *      images or whatever over http and dynamic data over websockets all in
71  *      one place; they're all handled in the user callback.
72  */
73
74 LWS_VISIBLE struct lws_context *
75 lws_create_context(struct lws_context_creation_info *info)
76 {
77         struct lws_context *context = NULL;
78         struct lws wsi;
79 #ifndef LWS_NO_DAEMONIZE
80         int pid_daemon = get_daemonize_pid();
81 #endif
82         char *p;
83         int n;
84
85         lwsl_notice("Initial logging level %d\n", log_level);
86
87         lwsl_notice("Libwebsockets version: %s\n", library_version);
88 #if LWS_POSIX
89 #ifdef LWS_USE_IPV6
90         if (!(info->options & LWS_SERVER_OPTION_DISABLE_IPV6))
91                 lwsl_notice("IPV6 compiled in and enabled\n");
92         else
93                 lwsl_notice("IPV6 compiled in but disabled\n");
94 #else
95         lwsl_notice("IPV6 not compiled in\n");
96 #endif
97         lws_feature_status_libev(info);
98 #endif
99         lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
100         lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
101
102         lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
103         lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
104         lwsl_info(" sizeof (*info): %u\n", sizeof(*info));
105 #if LWS_POSIX
106         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
107         lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
108 #endif
109         if (lws_plat_context_early_init())
110                 return NULL;
111
112         context = lws_zalloc(sizeof(struct lws_context));
113         if (!context) {
114                 lwsl_err("No memory for websocket context\n");
115                 return NULL;
116         }
117 #ifndef LWS_NO_DAEMONIZE
118         if (pid_daemon) {
119                 context->started_with_parent = pid_daemon;
120                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
121         }
122 #endif
123         context->lserv_seen = 0;
124         context->protocols = info->protocols;
125         context->token_limits = info->token_limits;
126         context->listen_port = info->port;
127         context->http_proxy_port = 0;
128         context->http_proxy_address[0] = '\0';
129         context->options = info->options;
130         context->iface = info->iface;
131         context->ka_time = info->ka_time;
132         context->ka_interval = info->ka_interval;
133         context->ka_probes = info->ka_probes;
134
135         memset(&wsi, 0, sizeof(wsi));
136         wsi.context = context;
137
138         if (!info->ka_interval && info->ka_time > 0) {
139                 lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
140                 return NULL;
141         }
142
143 #ifdef LWS_USE_LIBEV
144         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
145          * enable libev mediated SIGINT handling with a default handler of
146          * lws_sigint_cb. The handler can be overridden or disabled
147          * by invoking lws_sigint_cfg after creating the context, but
148          * before invoking lws_initloop:
149          */
150         context->use_ev_sigint = 1;
151         context->lws_ev_sigint_cb = &lws_sigint_cb;
152 #endif /* LWS_USE_LIBEV */
153
154         lwsl_info(" mem: context:         %5u bytes\n", sizeof(struct lws_context));
155
156         /*
157          * allocate and initialize the pool of
158          * allocated_header structs + data
159          */
160         if (info->max_http_header_data)
161                 context->max_http_header_data = info->max_http_header_data;
162         else
163                 context->max_http_header_data = LWS_MAX_HEADER_LEN;
164         if (info->max_http_header_pool)
165                 context->max_http_header_pool = info->max_http_header_pool;
166         else
167                 context->max_http_header_pool = LWS_MAX_HEADER_POOL;
168
169         context->http_header_data = lws_malloc(context->max_http_header_data *
170                                                context->max_http_header_pool);
171         if (!context->http_header_data)
172                 goto bail;
173         context->ah_pool = lws_zalloc(sizeof(struct allocated_headers) *
174                                       context->max_http_header_pool);
175         if (!context->ah_pool)
176                 goto bail;
177
178         for (n = 0; n < context->max_http_header_pool; n++)
179                 context->ah_pool[n].data = (char *)context->http_header_data +
180                         (n * context->max_http_header_data);
181
182         /* this is per context */
183         lwsl_info(" mem: http hdr rsvd:   %5u bytes ((%u + %u) x %u)\n",
184                     (context->max_http_header_data + sizeof(struct allocated_headers)) *
185                     context->max_http_header_pool,
186                     context->max_http_header_data, sizeof(struct allocated_headers),
187                     context->max_http_header_pool);
188
189         context->max_fds = getdtablesize();
190
191         context->fds = lws_zalloc(sizeof(struct lws_pollfd) * context->max_fds);
192         if (context->fds == NULL) {
193                 lwsl_err("OOM allocating %d fds\n", context->max_fds);
194                 goto bail;
195         }
196
197         lwsl_info(" mem: pollfd map:      %5u\n",
198                     sizeof(struct lws_pollfd) * context->max_fds);
199
200         if (lws_plat_init(context, info))
201                 goto bail;
202
203         lws_context_init_extensions(info, context);
204
205         context->user_space = info->user;
206
207         lwsl_notice(" mem: per-conn:        %5u bytes + protocol rx buf\n",
208                     sizeof(struct lws));
209
210         strcpy(context->canonical_hostname, "unknown");
211         lws_server_get_canonical_hostname(context, info);
212
213         /* either use proxy from info, or try get it from env var */
214
215         if (info->http_proxy_address) {
216                 /* override for backwards compatibility */
217                 if (info->http_proxy_port)
218                         context->http_proxy_port = info->http_proxy_port;
219                 lws_set_proxy(context, info->http_proxy_address);
220         } else {
221 #ifdef LWS_HAVE_GETENV
222                 p = getenv("http_proxy");
223                 if (p)
224                         lws_set_proxy(context, p);
225 #endif
226         }
227
228         if (lws_context_init_server_ssl(info, context))
229                 goto bail;
230
231         if (lws_context_init_client_ssl(info, context))
232                 goto bail;
233
234         if (lws_context_init_server(info, context))
235                 goto bail;
236
237         /*
238          * drop any root privs for this process
239          * to listen on port < 1023 we would have needed root, but now we are
240          * listening, we don't want the power for anything else
241          */
242         lws_plat_drop_app_privileges(info);
243
244         /* initialize supported protocols */
245
246         for (context->count_protocols = 0;
247              info->protocols[context->count_protocols].callback;
248              context->count_protocols++)
249                 /*
250                  * inform all the protocols that they are doing their one-time
251                  * initialization if they want to.
252                  *
253                  * NOTE the wsi is all zeros except for the context pointer
254                  * so lws_get_context(wsi) can work in the callback.
255                  */
256                 info->protocols[context->count_protocols].callback(&wsi,
257                                 LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
258
259         /*
260          * give all extensions a chance to create any per-context
261          * allocations they need
262          */
263         if (info->port != CONTEXT_PORT_NO_LISTEN) {
264                 if (lws_ext_cb_all_exts(context, NULL,
265                         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0)
266                         goto bail;
267         } else
268                 if (lws_ext_cb_all_exts(context, NULL,
269                         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0)
270                         goto bail;
271
272         return context;
273
274 bail:
275         lws_context_destroy(context);
276         return NULL;
277 }
278
279 /**
280  * lws_context_destroy() - Destroy the websocket context
281  * @context:    Websocket context
282  *
283  *      This function closes any active connections and then frees the
284  *      context.  After calling this, any further use of the context is
285  *      undefined.
286  */
287 LWS_VISIBLE void
288 lws_context_destroy(struct lws_context *context)
289 {
290         const struct lws_protocols *protocol = NULL;
291         struct lws wsi;
292         int n;
293
294         lwsl_notice("%s\n", __func__);
295
296         if (!context)
297                 return;
298
299         memset(&wsi, 0, sizeof(wsi));
300         wsi.context = context;
301
302 #ifdef LWS_LATENCY
303         if (context->worst_latency_info[0])
304                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
305 #endif
306
307         for (n = 0; n < context->fds_count; n++) {
308                 struct lws *wsi = wsi_from_fd(context, context->fds[n].fd);
309                 if (!wsi)
310                         continue;
311                 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
312                                 /* no protocol close */);
313                 n--;
314         }
315
316         /*
317          * give all extensions a chance to clean up any per-context
318          * allocations they might have made
319          */
320
321         n = lws_ext_cb_all_exts(context, NULL,
322                         LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0);
323
324         n = lws_ext_cb_all_exts(context, NULL,
325                         LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0);
326
327         /*
328          * inform all the protocols that they are done and will have no more
329          * callbacks
330          */
331         protocol = context->protocols;
332         if (protocol) {
333                 while (protocol->callback) {
334                         protocol->callback(&wsi,
335                                            LWS_CALLBACK_PROTOCOL_DESTROY,
336                                            NULL, NULL, 0);
337                         protocol++;
338                 }
339         }
340 #ifdef LWS_USE_LIBEV
341         ev_io_stop(context->io_loop, &context->w_accept.watcher);
342         if(context->use_ev_sigint)
343                 ev_signal_stop(context->io_loop, &context->w_sigint.watcher);
344 #endif /* LWS_USE_LIBEV */
345
346         lws_plat_context_early_destroy(context);
347         lws_ssl_context_destroy(context);
348         if (context->fds)
349                 lws_free(context->fds);
350         if (context->ah_pool)
351                 lws_free(context->ah_pool);
352         if (context->http_header_data)
353                 lws_free(context->http_header_data);
354
355         lws_plat_context_late_destroy(context);
356
357         lws_free(context);
358 }