WHOOPS! Stuck the sigint init int the wrong function.
[platform/upstream/libwebsockets.git] / lib / context.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2014 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  * libwebsocket_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 libwebsocket_context * that
52  *      represents this server.  After calling, user code needs to take care
53  *      of calling libwebsocket_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 libwebsocket_context *
75 libwebsocket_create_context(struct lws_context_creation_info *info)
76 {
77         struct libwebsocket_context *context = NULL;
78         char *p;
79 #ifdef _WIN32
80         int i;
81 #endif
82         int pid_daemon = get_daemonize_pid();
83
84         lwsl_notice("Initial logging level %d\n", log_level);
85         lwsl_notice("Library version: %s\n", library_version);
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         lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
96         lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
97
98         lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
99         lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
100         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
101         lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
102
103         if (lws_plat_context_early_init())
104                 return NULL;
105
106         context = lws_zalloc(sizeof(struct libwebsocket_context));
107         if (!context) {
108                 lwsl_err("No memory for websocket context\n");
109                 return NULL;
110         }
111
112         if (pid_daemon) {
113                 context->started_with_parent = pid_daemon;
114                 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
115         }
116
117         context->listen_service_extraseen = 0;
118         context->protocols = info->protocols;
119         context->token_limits = info->token_limits;
120         context->listen_port = info->port;
121         context->http_proxy_port = 0;
122         context->http_proxy_address[0] = '\0';
123         context->options = info->options;
124         context->iface = info->iface;
125         context->ka_time = info->ka_time;
126         context->ka_interval = info->ka_interval;
127         context->ka_probes = info->ka_probes;
128
129 #ifdef LWS_USE_LIBEV
130         /* (Issue #264) In order to *avoid breaking backwards compatibility*, we
131          * enable libev mediated SIGINT handling with a default handler of
132          * libwebsocket_sigint_cb. The handler can be overridden or disabled
133          * by invoking libwebsocket_sigint_cfg after creating the context, but
134          * before invoking libwebsocket_initloop:
135          */
136         context->use_ev_sigint = 1;
137         context->lws_ev_sigint_cb = &libwebsocket_sigint_cb;
138 #endif /* LWS_USE_LIBEV */
139
140
141         /* to reduce this allocation, */
142         context->max_fds = getdtablesize();
143         lwsl_notice(" static allocation: %u + (%u x %u fds) = %u bytes\n",
144                 sizeof(struct libwebsocket_context),
145                 sizeof(struct libwebsocket_pollfd) +
146                                         sizeof(struct libwebsocket *),
147                 context->max_fds,
148                 sizeof(struct libwebsocket_context) +
149                 ((sizeof(struct libwebsocket_pollfd) +
150                                         sizeof(struct libwebsocket *)) *
151                                                              context->max_fds));
152
153         context->fds = lws_zalloc(sizeof(struct libwebsocket_pollfd) *
154                                   context->max_fds);
155         if (context->fds == NULL) {
156                 lwsl_err("Unable to allocate fds array for %d connections\n",
157                                                               context->max_fds);
158                 goto bail;
159         }
160
161         if (lws_plat_init_lookup(context)) {
162                 goto bail;
163         }
164
165         if (lws_plat_init_fd_tables(context)) {
166                 goto bail;
167         }
168
169         lws_context_init_extensions(info, context);
170
171         context->user_space = info->user;
172
173         strcpy(context->canonical_hostname, "unknown");
174
175         lws_server_get_canonical_hostname(context, info);
176
177         /* split the proxy ads:port if given */
178
179         if (info->http_proxy_address) {
180                 strncpy(context->http_proxy_address, info->http_proxy_address,
181                                       sizeof(context->http_proxy_address) - 1);
182                 context->http_proxy_address[
183                                 sizeof(context->http_proxy_address) - 1] = '\0';
184                 context->http_proxy_port = info->http_proxy_port;
185         } else {
186 #ifdef LWS_HAVE_GETENV
187                 p = getenv("http_proxy");
188                 if (p) {
189                         strncpy(context->http_proxy_address, p,
190                                        sizeof(context->http_proxy_address) - 1);
191                         context->http_proxy_address[
192                                 sizeof(context->http_proxy_address) - 1] = '\0';
193
194                         p = strchr(context->http_proxy_address, ':');
195                         if (p == NULL) {
196                                 lwsl_err("http_proxy needs to be ads:port\n");
197                                 goto bail;
198                         }
199                         *p = '\0';
200                         context->http_proxy_port = atoi(p + 1);
201                 }
202 #endif
203         }
204
205         if (context->http_proxy_address[0])
206                 lwsl_notice(" Proxy %s:%u\n",
207                                 context->http_proxy_address,
208                                                       context->http_proxy_port);
209
210         lwsl_notice(
211                 " per-conn mem: %u + %u headers + protocol rx buf\n",
212                                 sizeof(struct libwebsocket),
213                                               sizeof(struct allocated_headers));
214
215         if (lws_context_init_server_ssl(info, context))
216                 goto bail;
217
218         if (lws_context_init_client_ssl(info, context))
219                 goto bail;
220
221         if (lws_context_init_server(info, context))
222                 goto bail;
223
224         /*
225          * drop any root privs for this process
226          * to listen on port < 1023 we would have needed root, but now we are
227          * listening, we don't want the power for anything else
228          */
229         lws_plat_drop_app_privileges(info);
230
231         /* initialize supported protocols */
232
233         for (context->count_protocols = 0;
234                 info->protocols[context->count_protocols].callback;
235                                                    context->count_protocols++) {
236
237                 lwsl_parser("  Protocol: %s\n",
238                                 info->protocols[context->count_protocols].name);
239
240                 info->protocols[context->count_protocols].owning_server =
241                                                                         context;
242                 info->protocols[context->count_protocols].protocol_index =
243                                                        context->count_protocols;
244
245                 /*
246                  * inform all the protocols that they are doing their one-time
247                  * initialization if they want to
248                  */
249                 info->protocols[context->count_protocols].callback(context,
250                                NULL, LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
251         }
252
253         /*
254          * give all extensions a chance to create any per-context
255          * allocations they need
256          */
257
258         if (info->port != CONTEXT_PORT_NO_LISTEN) {
259                 if (lws_ext_callback_for_each_extension_type(context, NULL,
260                                 LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT,
261                                                                    NULL, 0) < 0)
262                         goto bail;
263         } else
264                 if (lws_ext_callback_for_each_extension_type(context, NULL,
265                                 LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT,
266                                                                    NULL, 0) < 0)
267                         goto bail;
268
269         return context;
270
271 bail:
272         libwebsocket_context_destroy(context);
273         return NULL;
274 }
275
276 /**
277  * libwebsocket_context_destroy() - Destroy the websocket context
278  * @context:    Websocket context
279  *
280  *      This function closes any active connections and then frees the
281  *      context.  After calling this, any further use of the context is
282  *      undefined.
283  */
284 LWS_VISIBLE void
285 libwebsocket_context_destroy(struct libwebsocket_context *context)
286 {
287         /* Note that this is used for freeing partially allocated structs as well
288          * so make sure you don't try to free something uninitialized */
289         int n;
290         struct libwebsocket_protocols *protocol = NULL;
291
292         lwsl_notice("%s\n", __func__);
293
294         if (!context)
295                 return;
296
297 #ifdef LWS_LATENCY
298         if (context->worst_latency_info[0])
299                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
300 #endif
301
302         for (n = 0; n < context->fds_count; n++) {
303                 struct libwebsocket *wsi =
304                                         wsi_from_fd(context, context->fds[n].fd);
305                 if (!wsi)
306                         continue;
307                 libwebsocket_close_and_free_session(context,
308                         wsi, LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY /* no protocol close */);
309                 n--;
310         }
311
312         /*
313          * give all extensions a chance to clean up any per-context
314          * allocations they might have made
315          */
316         // TODO: I am not sure, but are we never supposed to be able to run a server
317         //       and client at the same time for a given context?
318         //       Otherwise both of these callbacks should always be called!
319         if (context->listen_port != CONTEXT_PORT_NO_LISTEN) {
320                 if (lws_ext_callback_for_each_extension_type(context, NULL,
321                                 LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT, NULL, 0) < 0) {
322                         lwsl_err("Got error from server extension callback on cleanup");
323                 }
324         } else {
325                 if (lws_ext_callback_for_each_extension_type(context, NULL,
326                                 LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT, NULL, 0) < 0) {
327                         lwsl_err("Got error from client extension callback on cleanup");
328                 }
329         }
330
331         /*
332          * inform all the protocols that they are done and will have no more
333          * callbacks
334          */
335         protocol = context->protocols;
336         if (protocol) {
337                 while (protocol->callback) {
338                         protocol->callback(context, NULL, LWS_CALLBACK_PROTOCOL_DESTROY,
339                                         NULL, NULL, 0);
340                         protocol++;
341                 }
342         }
343
344         lws_plat_context_early_destroy(context);
345
346         lws_ssl_context_destroy(context);
347
348         if (context->fds)
349                 lws_free(context->fds);
350
351         lws_plat_context_late_destroy(context);
352
353         lws_free(context);
354 }