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