Subject: [PATCH 1/2] fix win32 context memory leak
[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         /* to reduce this allocation, */
130         context->max_fds = getdtablesize();
131         lwsl_notice(" static allocation: %u + (%u x %u fds) = %u bytes\n",
132                 sizeof(struct libwebsocket_context),
133                 sizeof(struct libwebsocket_pollfd) +
134                                         sizeof(struct libwebsocket *),
135                 context->max_fds,
136                 sizeof(struct libwebsocket_context) +
137                 ((sizeof(struct libwebsocket_pollfd) +
138                                         sizeof(struct libwebsocket *)) *
139                                                              context->max_fds));
140
141         context->fds = lws_zalloc(sizeof(struct libwebsocket_pollfd) *
142                                   context->max_fds);
143         if (context->fds == NULL) {
144                 lwsl_err("Unable to allocate fds array for %d connections\n",
145                                                               context->max_fds);
146                 lws_free(context);
147                 return NULL;
148         }
149
150 #ifdef _WIN32
151         for (i = 0; i < FD_HASHTABLE_MODULUS; i++) {
152                 context->fd_hashtable[i].wsi = lws_zalloc(sizeof(struct libwebsocket*) * context->max_fds);
153         }
154 #else
155         context->lws_lookup = lws_zalloc(sizeof(struct libwebsocket *) * context->max_fds);
156         if (context->lws_lookup == NULL) {
157                 lwsl_err(
158                   "Unable to allocate lws_lookup array for %d connections\n",
159                                                               context->max_fds);
160                 lws_free(context->fds);
161                 lws_free(context);
162                 return NULL;
163         }
164 #endif
165
166         if (lws_plat_init_fd_tables(context)) {
167 #ifdef _WIN32
168                 for (i = 0; i < FD_HASHTABLE_MODULUS; i++) {
169                         lws_free(context->fd_hashtable[i].wsi);
170                 }
171 #else
172                 lws_free(context->lws_lookup);
173 #endif
174                 lws_free(context->fds);
175                 lws_free(context);
176                 return NULL;
177         }
178
179         lws_context_init_extensions(info, context);
180
181         context->user_space = info->user;
182
183         strcpy(context->canonical_hostname, "unknown");
184
185         lws_server_get_canonical_hostname(context, info);
186
187         /* split the proxy ads:port if given */
188
189         if (info->http_proxy_address) {
190                 strncpy(context->http_proxy_address, info->http_proxy_address,
191                                       sizeof(context->http_proxy_address) - 1);
192                 context->http_proxy_address[
193                                 sizeof(context->http_proxy_address) - 1] = '\0';
194                 context->http_proxy_port = info->http_proxy_port;
195         } else {
196 #ifdef HAVE_GETENV
197                 p = getenv("http_proxy");
198                 if (p) {
199                         strncpy(context->http_proxy_address, p,
200                                        sizeof(context->http_proxy_address) - 1);
201                         context->http_proxy_address[
202                                 sizeof(context->http_proxy_address) - 1] = '\0';
203
204                         p = strchr(context->http_proxy_address, ':');
205                         if (p == NULL) {
206                                 lwsl_err("http_proxy needs to be ads:port\n");
207                                 goto bail;
208                         }
209                         *p = '\0';
210                         context->http_proxy_port = atoi(p + 1);
211                 }
212 #endif
213         }
214
215         if (context->http_proxy_address[0])
216                 lwsl_notice(" Proxy %s:%u\n",
217                                 context->http_proxy_address,
218                                                       context->http_proxy_port);
219
220         lwsl_notice(
221                 " per-conn mem: %u + %u headers + protocol rx buf\n",
222                                 sizeof(struct libwebsocket),
223                                               sizeof(struct allocated_headers));
224
225         if (lws_context_init_server_ssl(info, context))
226                 goto bail;
227
228         if (lws_context_init_client_ssl(info, context))
229                 goto bail;
230
231         if (lws_context_init_server(info, context))
232                 goto bail;
233
234         /*
235          * drop any root privs for this process
236          * to listen on port < 1023 we would have needed root, but now we are
237          * listening, we don't want the power for anything else
238          */
239         lws_plat_drop_app_privileges(info);
240
241         /* initialize supported protocols */
242
243         for (context->count_protocols = 0;
244                 info->protocols[context->count_protocols].callback;
245                                                    context->count_protocols++) {
246
247                 lwsl_parser("  Protocol: %s\n",
248                                 info->protocols[context->count_protocols].name);
249
250                 info->protocols[context->count_protocols].owning_server =
251                                                                         context;
252                 info->protocols[context->count_protocols].protocol_index =
253                                                        context->count_protocols;
254
255                 /*
256                  * inform all the protocols that they are doing their one-time
257                  * initialization if they want to
258                  */
259                 info->protocols[context->count_protocols].callback(context,
260                                NULL, LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
261         }
262
263         /*
264          * give all extensions a chance to create any per-context
265          * allocations they need
266          */
267
268         if (info->port != CONTEXT_PORT_NO_LISTEN) {
269                 if (lws_ext_callback_for_each_extension_type(context, NULL,
270                                 LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT,
271                                                                    NULL, 0) < 0)
272                         goto bail;
273         } else
274                 if (lws_ext_callback_for_each_extension_type(context, NULL,
275                                 LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT,
276                                                                    NULL, 0) < 0)
277                         goto bail;
278
279         return context;
280
281 bail:
282         libwebsocket_context_destroy(context);
283         return NULL;
284 }
285
286 /**
287  * libwebsocket_context_destroy() - Destroy the websocket context
288  * @context:    Websocket context
289  *
290  *      This function closes any active connections and then frees the
291  *      context.  After calling this, any further use of the context is
292  *      undefined.
293  */
294 LWS_VISIBLE void
295 libwebsocket_context_destroy(struct libwebsocket_context *context)
296 {
297         int n;
298         struct libwebsocket_protocols *protocol = context->protocols;
299
300         lwsl_notice("%s\n", __func__);
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 libwebsocket *wsi =
309                                         wsi_from_fd(context, context->fds[n].fd);
310                 if (!wsi)
311                         continue;
312                 libwebsocket_close_and_free_session(context,
313                         wsi, LWS_CLOSE_STATUS_NOSTATUS /* no protocol close */);
314                 n--;
315         }
316
317         /*
318          * give all extensions a chance to clean up any per-context
319          * allocations they might have made
320          */
321         if (context->listen_port != CONTEXT_PORT_NO_LISTEN) {
322                 if (lws_ext_callback_for_each_extension_type(context, NULL,
323                          LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT, NULL, 0) < 0)
324                         return;
325         } else
326                 if (lws_ext_callback_for_each_extension_type(context, NULL,
327                          LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT, NULL, 0) < 0)
328                         return;
329
330         /*
331          * inform all the protocols that they are done and will have no more
332          * callbacks
333          */
334
335         while (protocol->callback) {
336                 protocol->callback(context, NULL, LWS_CALLBACK_PROTOCOL_DESTROY,
337                                 NULL, NULL, 0);
338                 protocol++;
339         }
340
341         lws_plat_context_early_destroy(context);
342
343         lws_ssl_context_destroy(context);
344
345         lws_free(context->fds);
346 #ifdef _WIN32
347         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
348                 lws_free(context->fd_hashtable[n].wsi);
349         }
350 #else
351         lws_free(context->lws_lookup);
352 #endif
353         lws_plat_context_late_destroy(context);
354
355         lws_free(context);
356 }