blob: 63d286a831e572b57bfad0b9d2c61bff8366cf33 [file] [log] [blame]
Andy Green58eaa742011-03-07 17:54:06 +00001/*
Andy Greena0da8a82010-11-08 17:12:19 +00002 * libwebsockets - small server side websockets and web server implementation
Andy Green8f037e42010-12-19 22:13:26 +00003 *
Andy Greena0da8a82010-11-08 17:12:19 +00004 * Copyright (C) 2010 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
Andy Green05a0a7b2010-10-31 17:51:39 +000020 */
21
Andy Green7c212cc2010-11-08 20:20:42 +000022#include "private-libwebsockets.h"
Andy Greenff95d7a2010-10-28 22:36:01 +010023
Peter Hinz56885f32011-03-02 22:03:47 +000024#ifdef WIN32
David Galeanocb193682013-01-09 15:29:00 +080025#include <tchar.h>
26#include <io.h>
Peter Hinz56885f32011-03-02 22:03:47 +000027#else
Davidc4ef7b12013-01-12 20:39:47 +080028#ifdef LWS_BUILTIN_GETIFADDRS
29#include <getifaddrs.h>
30#else
Peter Hinz56885f32011-03-02 22:03:47 +000031#include <ifaddrs.h>
Davidc4ef7b12013-01-12 20:39:47 +080032#endif
Andy Green7627af52011-03-09 15:13:52 +000033#include <sys/un.h>
Andy Greena69f0512012-05-03 12:32:38 +080034#include <sys/socket.h>
35#include <netdb.h>
Peter Hinz56885f32011-03-02 22:03:47 +000036#endif
Andy Green2e24da02011-03-05 16:12:04 +000037
38#ifdef LWS_OPENSSL_SUPPORT
39int openssl_websocket_private_data_index;
40#endif
41
Andy Greenaa6fc442012-04-12 13:26:49 +080042#ifdef __MINGW32__
43#include "../win32port/win32helpers/websock-w32.c"
44#else
45#ifdef __MINGW64__
46#include "../win32port/win32helpers/websock-w32.c"
47#endif
48#endif
49
Andy Green43db0452013-01-10 19:50:35 +080050static int log_level = LLL_ERR | LLL_WARN;
Andy Greende8f27a2013-01-12 09:17:42 +080051static void lwsl_emit_stderr(const char *line);
52static void (*lwsl_emit)(const char *line) = lwsl_emit_stderr;
Andy Green43db0452013-01-10 19:50:35 +080053static const char *log_level_names[] = {
54 "ERR",
55 "WARN",
56 "INFO",
57 "DEBUG",
58 "PARSER",
59 "HEADER",
60 "EXTENSION",
61 "CLIENT",
62};
63
Andy Green0d338332011-02-12 11:57:43 +000064/* file descriptor hash management */
65
66struct libwebsocket *
Peter Hinz56885f32011-03-02 22:03:47 +000067wsi_from_fd(struct libwebsocket_context *context, int fd)
Andy Green0d338332011-02-12 11:57:43 +000068{
69 int h = LWS_FD_HASH(fd);
70 int n = 0;
71
Peter Hinz56885f32011-03-02 22:03:47 +000072 for (n = 0; n < context->fd_hashtable[h].length; n++)
73 if (context->fd_hashtable[h].wsi[n]->sock == fd)
74 return context->fd_hashtable[h].wsi[n];
Andy Green0d338332011-02-12 11:57:43 +000075
76 return NULL;
77}
78
79int
Peter Hinz56885f32011-03-02 22:03:47 +000080insert_wsi(struct libwebsocket_context *context, struct libwebsocket *wsi)
Andy Green0d338332011-02-12 11:57:43 +000081{
82 int h = LWS_FD_HASH(wsi->sock);
83
Peter Hinz56885f32011-03-02 22:03:47 +000084 if (context->fd_hashtable[h].length == MAX_CLIENTS - 1) {
Andy Green43db0452013-01-10 19:50:35 +080085 lwsl_err("hash table overflow\n");
Andy Green0d338332011-02-12 11:57:43 +000086 return 1;
87 }
88
Peter Hinz56885f32011-03-02 22:03:47 +000089 context->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;
Andy Green0d338332011-02-12 11:57:43 +000090
91 return 0;
92}
93
94int
Peter Hinz56885f32011-03-02 22:03:47 +000095delete_from_fd(struct libwebsocket_context *context, int fd)
Andy Green0d338332011-02-12 11:57:43 +000096{
97 int h = LWS_FD_HASH(fd);
98 int n = 0;
99
Peter Hinz56885f32011-03-02 22:03:47 +0000100 for (n = 0; n < context->fd_hashtable[h].length; n++)
101 if (context->fd_hashtable[h].wsi[n]->sock == fd) {
102 while (n < context->fd_hashtable[h].length) {
103 context->fd_hashtable[h].wsi[n] =
104 context->fd_hashtable[h].wsi[n + 1];
Andy Green0d338332011-02-12 11:57:43 +0000105 n++;
106 }
Peter Hinz56885f32011-03-02 22:03:47 +0000107 context->fd_hashtable[h].length--;
Andy Green0d338332011-02-12 11:57:43 +0000108
109 return 0;
110 }
111
Andy Green43db0452013-01-10 19:50:35 +0800112 lwsl_err("Failed to find fd %d requested for "
Andy Green0d338332011-02-12 11:57:43 +0000113 "delete in hashtable\n", fd);
114 return 1;
115}
116
Andy Green1f9bf522011-02-14 21:14:37 +0000117#ifdef LWS_OPENSSL_SUPPORT
118static void
119libwebsockets_decode_ssl_error(void)
120{
121 char buf[256];
122 u_long err;
123
124 while ((err = ERR_get_error()) != 0) {
125 ERR_error_string_n(err, buf, sizeof(buf));
Andy Green43db0452013-01-10 19:50:35 +0800126 lwsl_err("*** %s\n", buf);
Andy Green1f9bf522011-02-14 21:14:37 +0000127 }
128}
129#endif
Andy Green0d338332011-02-12 11:57:43 +0000130
Andy Green32375b72011-02-19 08:32:53 +0000131
132static int
Andy Green6ee372f2012-04-09 15:09:01 +0800133interface_to_sa(const char *ifname, struct sockaddr_in *addr, size_t addrlen)
Andy Green32375b72011-02-19 08:32:53 +0000134{
135 int rc = -1;
Peter Hinz56885f32011-03-02 22:03:47 +0000136#ifdef WIN32
Andy Green6ee372f2012-04-09 15:09:01 +0800137 /* TODO */
Peter Hinz56885f32011-03-02 22:03:47 +0000138#else
Andy Green32375b72011-02-19 08:32:53 +0000139 struct ifaddrs *ifr;
140 struct ifaddrs *ifc;
141 struct sockaddr_in *sin;
142
143 getifaddrs(&ifr);
144 for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
145 if (strcmp(ifc->ifa_name, ifname))
146 continue;
147 if (ifc->ifa_addr == NULL)
148 continue;
149 sin = (struct sockaddr_in *)ifc->ifa_addr;
150 if (sin->sin_family != AF_INET)
151 continue;
152 memcpy(addr, sin, addrlen);
Andy Green6ee372f2012-04-09 15:09:01 +0800153 rc = 0;
Andy Green32375b72011-02-19 08:32:53 +0000154 }
155
156 freeifaddrs(ifr);
Peter Hinz56885f32011-03-02 22:03:47 +0000157#endif
Andy Green32375b72011-02-19 08:32:53 +0000158 return rc;
159}
160
Andy Green8f037e42010-12-19 22:13:26 +0000161void
Peter Hinz56885f32011-03-02 22:03:47 +0000162libwebsocket_close_and_free_session(struct libwebsocket_context *context,
Andy Green687b0182011-02-26 11:04:01 +0000163 struct libwebsocket *wsi, enum lws_close_status reason)
Andy Green251f6fa2010-11-03 11:13:06 +0000164{
Andy Greenb45993c2010-12-18 15:13:50 +0000165 int n;
Andy Green62c54d22011-02-14 09:14:25 +0000166 int old_state;
Andy Green5e1fa172011-02-10 09:07:05 +0000167 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
168 LWS_SEND_BUFFER_POST_PADDING];
Andy Greenc44159f2011-03-07 07:08:18 +0000169 int ret;
170 int m;
171 struct lws_tokens eff_buf;
Andy Greena41314f2011-05-23 10:00:03 +0100172 struct libwebsocket_extension *ext;
Andy Greenb45993c2010-12-18 15:13:50 +0000173
Andy Green4b6fbe12011-02-14 08:03:48 +0000174 if (!wsi)
Andy Greenb45993c2010-12-18 15:13:50 +0000175 return;
176
Andy Green62c54d22011-02-14 09:14:25 +0000177 old_state = wsi->state;
Andy Green251f6fa2010-11-03 11:13:06 +0000178
Andy Green62c54d22011-02-14 09:14:25 +0000179 if (old_state == WSI_STATE_DEAD_SOCKET)
Andy Green5e1fa172011-02-10 09:07:05 +0000180 return;
181
Andy Greenda527df2011-03-07 07:08:12 +0000182 wsi->close_reason = reason;
183
184 /*
Andy Green68b45042011-05-25 21:41:57 +0100185 * are his extensions okay with him closing? Eg he might be a mux
186 * parent and just his ch1 aspect is closing?
187 */
188
189
190 for (n = 0; n < wsi->count_active_extensions; n++) {
191 if (!wsi->active_extensions[n]->callback)
192 continue;
193
194 m = wsi->active_extensions[n]->callback(context,
195 wsi->active_extensions[n], wsi,
196 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
197 wsi->active_extensions_user[n], NULL, 0);
198
199 /*
200 * if somebody vetoed actually closing him at this time....
201 * up to the extension to track the attempted close, let's
202 * just bail
203 */
204
205 if (m) {
Andy Green43db0452013-01-10 19:50:35 +0800206 lwsl_ext("extension vetoed close\n");
Andy Green68b45042011-05-25 21:41:57 +0100207 return;
208 }
209 }
210
211
212
213 /*
Andy Greenc44159f2011-03-07 07:08:18 +0000214 * flush any tx pending from extensions, since we may send close packet
215 * if there are problems with send, just nuke the connection
216 */
217
218 ret = 1;
219 while (ret == 1) {
220
221 /* default to nobody has more to spill */
222
223 ret = 0;
224 eff_buf.token = NULL;
225 eff_buf.token_len = 0;
226
227 /* show every extension the new incoming data */
228
229 for (n = 0; n < wsi->count_active_extensions; n++) {
230 m = wsi->active_extensions[n]->callback(
Andy Green46c2ea02011-03-22 09:04:01 +0000231 wsi->protocol->owning_server,
232 wsi->active_extensions[n], wsi,
Andy Greenc44159f2011-03-07 07:08:18 +0000233 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
234 wsi->active_extensions_user[n], &eff_buf, 0);
235 if (m < 0) {
Andy Green43db0452013-01-10 19:50:35 +0800236 lwsl_ext("Extension reports fatal error\n");
Andy Greenc44159f2011-03-07 07:08:18 +0000237 goto just_kill_connection;
238 }
239 if (m)
240 /*
241 * at least one extension told us he has more
242 * to spill, so we will go around again after
243 */
244 ret = 1;
245 }
246
247 /* assuming they left us something to send, send it */
248
249 if (eff_buf.token_len)
250 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
251 eff_buf.token_len))
252 goto just_kill_connection;
253 }
254
255 /*
Andy Greenda527df2011-03-07 07:08:12 +0000256 * signal we are closing, libsocket_write will
257 * add any necessary version-specific stuff. If the write fails,
258 * no worries we are closing anyway. If we didn't initiate this
259 * close, then our state has been changed to
260 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
261 *
262 * Likewise if it's a second call to close this connection after we
263 * sent the close indication to the peer already, we are in state
264 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
265 */
266
267 if (old_state == WSI_STATE_ESTABLISHED &&
268 reason != LWS_CLOSE_STATUS_NOSTATUS) {
Andy Green66a16f32011-05-24 22:07:45 +0100269
Andy Green43db0452013-01-10 19:50:35 +0800270 lwsl_debug("sending close indication...\n");
Andy Green66a16f32011-05-24 22:07:45 +0100271
Andy Greenda527df2011-03-07 07:08:12 +0000272 n = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
273 0, LWS_WRITE_CLOSE);
274 if (!n) {
275 /*
276 * we have sent a nice protocol level indication we
277 * now wish to close, we should not send anything more
278 */
279
280 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
281
282 /* and we should wait for a reply for a bit */
283
284 libwebsocket_set_timeout(wsi,
David Galeanoc9f1ff82013-01-09 18:01:23 +0800285 PENDING_TIMEOUT_CLOSE_ACK, AWAITING_TIMEOUT);
Andy Greenda527df2011-03-07 07:08:12 +0000286
Andy Green43db0452013-01-10 19:50:35 +0800287 lwsl_debug("sent close indication, awaiting ack\n");
Andy Greenda527df2011-03-07 07:08:12 +0000288
289 return;
290 }
291
292 /* else, the send failed and we should just hang up */
293 }
294
Andy Greenc44159f2011-03-07 07:08:18 +0000295just_kill_connection:
Andy Green66a16f32011-05-24 22:07:45 +0100296
Andy Green43db0452013-01-10 19:50:35 +0800297 lwsl_debug("libwebsocket_close_and_free_session: just_kill_connection\n");
Andy Green66a16f32011-05-24 22:07:45 +0100298
Andy Greenda527df2011-03-07 07:08:12 +0000299 /*
300 * we won't be servicing or receiving anything further from this guy
301 * remove this fd from wsi mapping hashtable
302 */
Andy Green4b6fbe12011-02-14 08:03:48 +0000303
Andy Greena41314f2011-05-23 10:00:03 +0100304 if (wsi->sock)
305 delete_from_fd(context, wsi->sock);
Andy Green4b6fbe12011-02-14 08:03:48 +0000306
307 /* delete it from the internal poll list if still present */
308
Peter Hinz56885f32011-03-02 22:03:47 +0000309 for (n = 0; n < context->fds_count; n++) {
310 if (context->fds[n].fd != wsi->sock)
Andy Green4b6fbe12011-02-14 08:03:48 +0000311 continue;
Peter Hinz56885f32011-03-02 22:03:47 +0000312 while (n < context->fds_count - 1) {
313 context->fds[n] = context->fds[n + 1];
Andy Green4b6fbe12011-02-14 08:03:48 +0000314 n++;
315 }
Peter Hinz56885f32011-03-02 22:03:47 +0000316 context->fds_count--;
Andy Green4b6fbe12011-02-14 08:03:48 +0000317 /* we only have to deal with one */
Peter Hinz56885f32011-03-02 22:03:47 +0000318 n = context->fds_count;
Andy Green4b6fbe12011-02-14 08:03:48 +0000319 }
320
321 /* remove also from external POLL support via protocol 0 */
Andy Greena41314f2011-05-23 10:00:03 +0100322 if (wsi->sock)
323 context->protocols[0].callback(context, wsi,
Andy Green4b6fbe12011-02-14 08:03:48 +0000324 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
325
Andy Green251f6fa2010-11-03 11:13:06 +0000326 wsi->state = WSI_STATE_DEAD_SOCKET;
327
Andy Green4b6fbe12011-02-14 08:03:48 +0000328 /* tell the user it's all over for this guy */
329
Andy Greend4302732011-02-28 07:45:29 +0000330 if (wsi->protocol && wsi->protocol->callback &&
Andy Green6ee372f2012-04-09 15:09:01 +0800331 ((old_state == WSI_STATE_ESTABLISHED) ||
332 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
333 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
Andy Green43db0452013-01-10 19:50:35 +0800334 lwsl_debug("calling back CLOSED\n");
Peter Hinz56885f32011-03-02 22:03:47 +0000335 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
Andy Greene77ddd82010-11-13 10:03:47 +0000336 wsi->user_space, NULL, 0);
Andy Greencc012472011-11-07 19:53:23 +0800337 } else
Andy Green43db0452013-01-10 19:50:35 +0800338 lwsl_debug("not calling back closed, old_state=%d\n", old_state);
Andy Green251f6fa2010-11-03 11:13:06 +0000339
Andy Greenef660a92011-03-06 10:29:38 +0000340 /* deallocate any active extension contexts */
341
342 for (n = 0; n < wsi->count_active_extensions; n++) {
343 if (!wsi->active_extensions[n]->callback)
344 continue;
345
Andy Green46c2ea02011-03-22 09:04:01 +0000346 wsi->active_extensions[n]->callback(context,
347 wsi->active_extensions[n], wsi,
348 LWS_EXT_CALLBACK_DESTROY,
349 wsi->active_extensions_user[n], NULL, 0);
Andy Greenef660a92011-03-06 10:29:38 +0000350
351 free(wsi->active_extensions_user[n]);
352 }
353
Andy Greena41314f2011-05-23 10:00:03 +0100354 /*
355 * inform all extensions in case they tracked this guy out of band
356 * even though not active on him specifically
357 */
358
359 ext = context->extensions;
360 while (ext && ext->callback) {
361 ext->callback(context, ext, wsi,
362 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
363 NULL, NULL, 0);
364 ext++;
365 }
366
Andy Greenef660a92011-03-06 10:29:38 +0000367 /* free up his parsing allocations */
Andy Green4b6fbe12011-02-14 08:03:48 +0000368
Andy Green251f6fa2010-11-03 11:13:06 +0000369 for (n = 0; n < WSI_TOKEN_COUNT; n++)
370 if (wsi->utf8_token[n].token)
371 free(wsi->utf8_token[n].token);
372
Andy Greena41314f2011-05-23 10:00:03 +0100373 if (wsi->c_address)
374 free(wsi->c_address);
375
Andy Green43db0452013-01-10 19:50:35 +0800376/* lwsl_info("closing fd=%d\n", wsi->sock); */
Andy Green251f6fa2010-11-03 11:13:06 +0000377
Andy Green3faa9c72010-11-08 17:03:03 +0000378#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +0000379 if (wsi->ssl) {
Andy Green3faa9c72010-11-08 17:03:03 +0000380 n = SSL_get_fd(wsi->ssl);
381 SSL_shutdown(wsi->ssl);
Andy Green3fc2c652013-01-14 15:35:02 +0800382 compatible_close(n);
Andy Green3faa9c72010-11-08 17:03:03 +0000383 SSL_free(wsi->ssl);
384 } else {
385#endif
386 shutdown(wsi->sock, SHUT_RDWR);
Andy Green3fc2c652013-01-14 15:35:02 +0800387
Andy Green66a16f32011-05-24 22:07:45 +0100388 if (wsi->sock)
Andy Green3fc2c652013-01-14 15:35:02 +0800389 compatible_close(wsi->sock);
Andy Green3faa9c72010-11-08 17:03:03 +0000390#ifdef LWS_OPENSSL_SUPPORT
391 }
392#endif
David Brooks2c60d952012-04-20 12:19:01 +0800393 if (wsi->protocol && wsi->protocol->per_session_data_size && wsi->user_space) /* user code may own */
Andy Green4f3943a2010-11-12 10:44:16 +0000394 free(wsi->user_space);
395
Andy Green251f6fa2010-11-03 11:13:06 +0000396 free(wsi);
397}
398
Andy Green07034092011-02-13 08:37:12 +0000399/**
Andy Greenf7ee5492011-02-13 09:04:21 +0000400 * libwebsockets_hangup_on_client() - Server calls to terminate client
Andy Green6ee372f2012-04-09 15:09:01 +0800401 * connection
Peter Hinz56885f32011-03-02 22:03:47 +0000402 * @context: libwebsockets context
Andy Greenf7ee5492011-02-13 09:04:21 +0000403 * @fd: Connection socket descriptor
404 */
405
406void
Peter Hinz56885f32011-03-02 22:03:47 +0000407libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
Andy Greenf7ee5492011-02-13 09:04:21 +0000408{
Peter Hinz56885f32011-03-02 22:03:47 +0000409 struct libwebsocket *wsi = wsi_from_fd(context, fd);
Andy Greenf7ee5492011-02-13 09:04:21 +0000410
411 if (wsi == NULL)
412 return;
413
Peter Hinz56885f32011-03-02 22:03:47 +0000414 libwebsocket_close_and_free_session(context, wsi,
Andy Green6da560c2011-02-26 11:06:27 +0000415 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenf7ee5492011-02-13 09:04:21 +0000416}
417
418
419/**
Andy Green07034092011-02-13 08:37:12 +0000420 * libwebsockets_get_peer_addresses() - Get client address information
421 * @fd: Connection socket descriptor
422 * @name: Buffer to take client address name
423 * @name_len: Length of client address name buffer
424 * @rip: Buffer to take client address IP qotted quad
425 * @rip_len: Length of client address IP buffer
426 *
427 * This function fills in @name and @rip with the name and IP of
Andy Green6ee372f2012-04-09 15:09:01 +0800428 * the client connected with socket descriptor @fd. Names may be
429 * truncated if there is not enough room. If either cannot be
430 * determined, they will be returned as valid zero-length strings.
Andy Green07034092011-02-13 08:37:12 +0000431 */
432
433void
434libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
435 char *rip, int rip_len)
436{
437 unsigned int len;
438 struct sockaddr_in sin;
439 struct hostent *host;
440 struct hostent *host1;
441 char ip[128];
Andy Greenf92def72011-03-09 15:02:20 +0000442 unsigned char *p;
Andy Green07034092011-02-13 08:37:12 +0000443 int n;
David Galeanocb193682013-01-09 15:29:00 +0800444#ifdef AF_LOCAL
445 struct sockaddr_un *un;
446#endif
Andy Green07034092011-02-13 08:37:12 +0000447
448 rip[0] = '\0';
449 name[0] = '\0';
450
451 len = sizeof sin;
452 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
453 perror("getpeername");
454 return;
455 }
Andy Green6ee372f2012-04-09 15:09:01 +0800456
Andy Green07034092011-02-13 08:37:12 +0000457 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
458 AF_INET);
459 if (host == NULL) {
460 perror("gethostbyaddr");
461 return;
462 }
463
464 strncpy(name, host->h_name, name_len);
465 name[name_len - 1] = '\0';
466
467 host1 = gethostbyname(host->h_name);
468 if (host1 == NULL)
469 return;
Andy Greenf92def72011-03-09 15:02:20 +0000470 p = (unsigned char *)host1;
Andy Green07034092011-02-13 08:37:12 +0000471 n = 0;
472 while (p != NULL) {
Andy Greenf92def72011-03-09 15:02:20 +0000473 p = (unsigned char *)host1->h_addr_list[n++];
Andy Green07034092011-02-13 08:37:12 +0000474 if (p == NULL)
475 continue;
Peter Hinzbb45a902011-03-10 18:14:01 +0000476 if ((host1->h_addrtype != AF_INET)
477#ifdef AF_LOCAL
478 && (host1->h_addrtype != AF_LOCAL)
479#endif
480 )
Andy Green07034092011-02-13 08:37:12 +0000481 continue;
482
Andy Green7627af52011-03-09 15:13:52 +0000483 if (host1->h_addrtype == AF_INET)
484 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
Peter Hinzbb45a902011-03-10 18:14:01 +0000485#ifdef AF_LOCAL
Andy Green7627af52011-03-09 15:13:52 +0000486 else {
487 un = (struct sockaddr_un *)p;
Andy Green6ee372f2012-04-09 15:09:01 +0800488 strncpy(ip, un->sun_path, sizeof(ip) - 1);
Andy Green7627af52011-03-09 15:13:52 +0000489 ip[sizeof(ip) - 1] = '\0';
490 }
Peter Hinzbb45a902011-03-10 18:14:01 +0000491#endif
Andy Green07034092011-02-13 08:37:12 +0000492 p = NULL;
493 strncpy(rip, ip, rip_len);
494 rip[rip_len - 1] = '\0';
495 }
496}
Andy Green9f990342011-02-12 11:57:45 +0000497
Peter Hinz56885f32011-03-02 22:03:47 +0000498int libwebsockets_get_random(struct libwebsocket_context *context,
499 void *buf, int len)
500{
501 int n;
Aaron Zinman4550f1d2013-01-10 12:35:18 +0800502 char *p = (char *)buf;
Peter Hinz56885f32011-03-02 22:03:47 +0000503
504#ifdef WIN32
505 for (n = 0; n < len; n++)
506 p[n] = (unsigned char)rand();
507#else
508 n = read(context->fd_random, p, len);
509#endif
510
511 return n;
512}
513
Andy Green2836c642011-03-07 20:47:41 +0000514unsigned char *
515libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md)
516{
517 return SHA1(d, n, md);
518}
519
Andy Green95a7b5d2011-03-06 10:29:39 +0000520int lws_send_pipe_choked(struct libwebsocket *wsi)
521{
522 struct pollfd fds;
523
524 fds.fd = wsi->sock;
525 fds.events = POLLOUT;
526 fds.revents = 0;
527
528 if (poll(&fds, 1, 0) != 1)
529 return 1;
530
531 if ((fds.revents & POLLOUT) == 0)
532 return 1;
533
534 /* okay to send another packet without blocking */
535
536 return 0;
537}
538
Andy Greena41314f2011-05-23 10:00:03 +0100539int
Andy Green3b84c002011-03-06 13:14:42 +0000540lws_handle_POLLOUT_event(struct libwebsocket_context *context,
541 struct libwebsocket *wsi, struct pollfd *pollfd)
542{
543 struct lws_tokens eff_buf;
544 int n;
545 int ret;
546 int m;
Andy Greena41314f2011-05-23 10:00:03 +0100547 int handled = 0;
Andy Green3b84c002011-03-06 13:14:42 +0000548
Andy Greena41314f2011-05-23 10:00:03 +0100549 for (n = 0; n < wsi->count_active_extensions; n++) {
550 if (!wsi->active_extensions[n]->callback)
551 continue;
552
553 m = wsi->active_extensions[n]->callback(context,
554 wsi->active_extensions[n], wsi,
555 LWS_EXT_CALLBACK_IS_WRITEABLE,
556 wsi->active_extensions_user[n], NULL, 0);
557 if (m > handled)
558 handled = m;
559 }
560
561 if (handled == 1)
562 goto notify_action;
563
564 if (!wsi->extension_data_pending || handled == 2)
Andy Green3b84c002011-03-06 13:14:42 +0000565 goto user_service;
566
567 /*
568 * check in on the active extensions, see if they
569 * had pending stuff to spill... they need to get the
570 * first look-in otherwise sequence will be disordered
571 *
572 * NULL, zero-length eff_buf means just spill pending
573 */
574
575 ret = 1;
576 while (ret == 1) {
577
578 /* default to nobody has more to spill */
579
580 ret = 0;
581 eff_buf.token = NULL;
582 eff_buf.token_len = 0;
583
584 /* give every extension a chance to spill */
585
586 for (n = 0; n < wsi->count_active_extensions; n++) {
587 m = wsi->active_extensions[n]->callback(
Andy Green46c2ea02011-03-22 09:04:01 +0000588 wsi->protocol->owning_server,
589 wsi->active_extensions[n], wsi,
Andy Green3b84c002011-03-06 13:14:42 +0000590 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
591 wsi->active_extensions_user[n], &eff_buf, 0);
592 if (m < 0) {
Andy Green43db0452013-01-10 19:50:35 +0800593 lwsl_err("ext reports fatal error\n");
Andy Green3b84c002011-03-06 13:14:42 +0000594 return -1;
595 }
596 if (m)
597 /*
598 * at least one extension told us he has more
599 * to spill, so we will go around again after
600 */
601 ret = 1;
602 }
603
604 /* assuming they gave us something to send, send it */
605
606 if (eff_buf.token_len) {
607 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
608 eff_buf.token_len))
609 return -1;
610 } else
611 continue;
612
613 /* no extension has more to spill */
614
615 if (!ret)
616 continue;
617
618 /*
619 * There's more to spill from an extension, but we just sent
620 * something... did that leave the pipe choked?
621 */
622
623 if (!lws_send_pipe_choked(wsi))
624 /* no we could add more */
625 continue;
626
Andy Green43db0452013-01-10 19:50:35 +0800627 lwsl_info("choked in POLLOUT service\n");
Andy Green3b84c002011-03-06 13:14:42 +0000628
629 /*
630 * Yes, he's choked. Leave the POLLOUT masked on so we will
631 * come back here when he is unchoked. Don't call the user
632 * callback to enforce ordering of spilling, he'll get called
633 * when we come back here and there's nothing more to spill.
634 */
635
636 return 0;
637 }
638
639 wsi->extension_data_pending = 0;
640
641user_service:
642 /* one shot */
643
Andy Greena41314f2011-05-23 10:00:03 +0100644 if (pollfd) {
645 pollfd->events &= ~POLLOUT;
Andy Green3b84c002011-03-06 13:14:42 +0000646
Andy Greena41314f2011-05-23 10:00:03 +0100647 /* external POLL support via protocol 0 */
648 context->protocols[0].callback(context, wsi,
649 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
650 (void *)(long)wsi->sock, NULL, POLLOUT);
651 }
652
653notify_action:
Andy Green3b84c002011-03-06 13:14:42 +0000654
Andy Green9e4c2b62011-03-07 20:47:39 +0000655 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
656 n = LWS_CALLBACK_CLIENT_WRITEABLE;
657 else
658 n = LWS_CALLBACK_SERVER_WRITEABLE;
659
Aaron Zinman4550f1d2013-01-10 12:35:18 +0800660 wsi->protocol->callback(context, wsi, (enum libwebsocket_callback_reasons) n, wsi->user_space, NULL, 0);
Andy Green3b84c002011-03-06 13:14:42 +0000661
662 return 0;
663}
664
665
666
Andy Greena41314f2011-05-23 10:00:03 +0100667void
668libwebsocket_service_timeout_check(struct libwebsocket_context *context,
669 struct libwebsocket *wsi, unsigned int sec)
670{
671 int n;
672
673 /*
674 * if extensions want in on it (eg, we are a mux parent)
675 * give them a chance to service child timeouts
676 */
677
678 for (n = 0; n < wsi->count_active_extensions; n++)
679 wsi->active_extensions[n]->callback(
680 context, wsi->active_extensions[n],
681 wsi, LWS_EXT_CALLBACK_1HZ,
682 wsi->active_extensions_user[n], NULL, sec);
683
684 if (!wsi->pending_timeout)
685 return;
Andy Green6ee372f2012-04-09 15:09:01 +0800686
Andy Greena41314f2011-05-23 10:00:03 +0100687 /*
688 * if we went beyond the allowed time, kill the
689 * connection
690 */
691
692 if (sec > wsi->pending_timeout_limit) {
Andy Green43db0452013-01-10 19:50:35 +0800693 lwsl_info("TIMEDOUT WAITING\n");
Andy Greena41314f2011-05-23 10:00:03 +0100694 libwebsocket_close_and_free_session(context,
695 wsi, LWS_CLOSE_STATUS_NOSTATUS);
696 }
697}
698
699struct libwebsocket *
700libwebsocket_create_new_server_wsi(struct libwebsocket_context *context)
701{
702 struct libwebsocket *new_wsi;
703 int n;
704
Aaron Zinman4550f1d2013-01-10 12:35:18 +0800705 new_wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
Andy Greena41314f2011-05-23 10:00:03 +0100706 if (new_wsi == NULL) {
Andy Green43db0452013-01-10 19:50:35 +0800707 lwsl_err("Out of memory for new connection\n");
Andy Greena41314f2011-05-23 10:00:03 +0100708 return NULL;
709 }
710
Andy Green6ee372f2012-04-09 15:09:01 +0800711 memset(new_wsi, 0, sizeof(struct libwebsocket));
Andy Greena41314f2011-05-23 10:00:03 +0100712 new_wsi->count_active_extensions = 0;
713 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
714
715 /* intialize the instance struct */
716
717 new_wsi->state = WSI_STATE_HTTP;
718 new_wsi->name_buffer_pos = 0;
Andy Greend280b6e2013-01-15 13:40:23 +0800719 new_wsi->mode = LWS_CONNMODE_HTTP_SERVING;
Andy Greena41314f2011-05-23 10:00:03 +0100720
721 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
722 new_wsi->utf8_token[n].token = NULL;
723 new_wsi->utf8_token[n].token_len = 0;
724 }
725
726 /*
727 * these can only be set once the protocol is known
728 * we set an unestablished connection's protocol pointer
729 * to the start of the supported list, so it can look
730 * for matching ones during the handshake
731 */
732 new_wsi->protocol = context->protocols;
733 new_wsi->user_space = NULL;
734
735 /*
736 * Default protocol is 76 / 00
737 * After 76, there's a header specified to inform which
738 * draft the client wants, when that's seen we modify
739 * the individual connection's spec revision accordingly
740 */
741 new_wsi->ietf_spec_revision = 0;
742
743 return new_wsi;
744}
745
Andy Greena41314f2011-05-23 10:00:03 +0100746
Andy Green9f990342011-02-12 11:57:45 +0000747/**
748 * libwebsocket_service_fd() - Service polled socket with something waiting
Peter Hinz56885f32011-03-02 22:03:47 +0000749 * @context: Websocket context
Andy Green9f990342011-02-12 11:57:45 +0000750 * @pollfd: The pollfd entry describing the socket fd and which events
Andy Green6ee372f2012-04-09 15:09:01 +0800751 * happened.
Andy Green9f990342011-02-12 11:57:45 +0000752 *
753 * This function closes any active connections and then frees the
754 * context. After calling this, any further use of the context is
755 * undefined.
756 */
757
758int
Peter Hinz56885f32011-03-02 22:03:47 +0000759libwebsocket_service_fd(struct libwebsocket_context *context,
Andy Green0d338332011-02-12 11:57:43 +0000760 struct pollfd *pollfd)
Andy Greenb45993c2010-12-18 15:13:50 +0000761{
Andy Green6ee372f2012-04-09 15:09:01 +0800762 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
763 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
Andy Greena71eafc2011-02-14 17:59:43 +0000764 struct libwebsocket *wsi;
Andy Green0d338332011-02-12 11:57:43 +0000765 struct libwebsocket *new_wsi;
Andy Greenb45993c2010-12-18 15:13:50 +0000766 int n;
Andy Green0d338332011-02-12 11:57:43 +0000767 int m;
Tobias Maiere8c9b562012-04-05 11:57:12 +0200768 ssize_t len;
Andy Green0d338332011-02-12 11:57:43 +0000769 int accept_fd;
770 unsigned int clilen;
771 struct sockaddr_in cli_addr;
Andy Greena71eafc2011-02-14 17:59:43 +0000772 struct timeval tv;
Andy Green2366b1c2011-03-06 13:15:31 +0000773 int more = 1;
Andy Green98a717c2011-03-06 13:14:15 +0000774 struct lws_tokens eff_buf;
Andy Green6c939552011-03-08 08:56:57 +0000775 int opt = 1;
Andy Green76f61e72013-01-16 11:53:05 +0800776 extern int lws_client_socket_service(struct libwebsocket_context *context, struct libwebsocket *wsi, struct pollfd *pollfd);
Andy Greenc6517fa2011-03-06 13:15:29 +0000777
Andy Greena71eafc2011-02-14 17:59:43 +0000778 /*
779 * you can call us with pollfd = NULL to just allow the once-per-second
780 * global timeout checks; if less than a second since the last check
781 * it returns immediately then.
782 */
783
784 gettimeofday(&tv, NULL);
785
Peter Hinz56885f32011-03-02 22:03:47 +0000786 if (context->last_timeout_check_s != tv.tv_sec) {
787 context->last_timeout_check_s = tv.tv_sec;
Andy Greena71eafc2011-02-14 17:59:43 +0000788
789 /* global timeout check once per second */
790
Peter Hinz56885f32011-03-02 22:03:47 +0000791 for (n = 0; n < context->fds_count; n++) {
792 wsi = wsi_from_fd(context, context->fds[n].fd);
Andy Greena71eafc2011-02-14 17:59:43 +0000793
Andy Greena41314f2011-05-23 10:00:03 +0100794 libwebsocket_service_timeout_check(context, wsi,
795 tv.tv_sec);
Andy Greena71eafc2011-02-14 17:59:43 +0000796 }
797 }
798
799 /* just here for timeout management? */
800
801 if (pollfd == NULL)
802 return 0;
803
804 /* no, here to service a socket descriptor */
805
Andy Green65b0e912013-01-16 07:59:47 +0800806 /*
807 * deal with listen service piggybacking
808 * every listen_service_modulo services of other fds, we
809 * sneak one in to service the listen socket if there's anything waiting
810 *
811 * To handle connection storms, as found in ab, if we previously saw a
812 * pending connection here, it causes us to check again next time.
813 */
814
815 if (context->listen_service_fd && pollfd->fd != context->listen_service_fd) {
816 context->listen_service_count++;
817 if (context->listen_service_extraseen ||
818 context->listen_service_count == context->listen_service_modulo) {
819 context->listen_service_count = 0;
820 m = 1;
821 if (context->listen_service_extraseen > 5)
822 m = 2;
823 while (m--) {
824 /* even with extpoll, we prepared this internal fds for listen */
825 n = poll(&context->fds[0], 1, 0);
826 if (n > 0) { /* there's a connection waiting for us */
827 libwebsocket_service_fd(context, &context->fds[0]);
828 context->listen_service_extraseen++;
829 } else {
830 if (context->listen_service_extraseen)
831 context->listen_service_extraseen--;
832 break;
833 }
834 }
835 }
836
837 }
838
839 /* okay, what we came here to do... */
840
Peter Hinz56885f32011-03-02 22:03:47 +0000841 wsi = wsi_from_fd(context, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +0000842
Andy Greend280b6e2013-01-15 13:40:23 +0800843 if (wsi == NULL) {
844 lwsl_debug("hm fd %d has NULL wsi\n", pollfd->fd);
Andy Greenfa3f4052012-10-07 20:40:35 +0800845 return 0;
Andy Greend280b6e2013-01-15 13:40:23 +0800846 }
Andy Green8f037e42010-12-19 22:13:26 +0000847
Andy Green0d338332011-02-12 11:57:43 +0000848 switch (wsi->mode) {
Andy Greend280b6e2013-01-15 13:40:23 +0800849
850 case LWS_CONNMODE_HTTP_SERVING:
851
852 /* handle http headers coming in */
853
854 /* any incoming data ready? */
855
856 if (pollfd->revents & POLLIN) {
857
858 #ifdef LWS_OPENSSL_SUPPORT
859 if (wsi->ssl)
860 len = SSL_read(wsi->ssl, buf, sizeof buf);
861 else
862 #endif
863 len = recv(pollfd->fd, buf, sizeof buf, 0);
864
865 if (len < 0) {
866 lwsl_debug("Socket read returned %d\n", len);
867 if (errno != EINTR && errno != EAGAIN)
868 libwebsocket_close_and_free_session(context,
869 wsi, LWS_CLOSE_STATUS_NOSTATUS);
870 return 1;
871 }
872 if (!len) {
873 libwebsocket_close_and_free_session(context, wsi,
874 LWS_CLOSE_STATUS_NOSTATUS);
875 return 0;
876 }
877
878 n = libwebsocket_read(context, wsi, buf, len);
879 if (n < 0)
880 /* we closed wsi */
881 return 1;
882 }
883
884 /* this handles POLLOUT for http serving fragments */
885
886 if (!(pollfd->revents & POLLOUT))
887 break;
888
889 /* one shot */
890 pollfd->events &= ~POLLOUT;
891
892 if (wsi->state != WSI_STATE_HTTP_ISSUING_FILE)
893 break;
894
895 if (libwebsockets_serve_http_file_fragment(context, wsi) < 0)
896 libwebsocket_close_and_free_session(context, wsi,
897 LWS_CLOSE_STATUS_NOSTATUS);
898 else
899 if (wsi->state == WSI_STATE_HTTP && wsi->protocol->callback)
900 if (wsi->protocol->callback(context, wsi, LWS_CALLBACK_HTTP_FILE_COMPLETION, wsi->user_space,
901 wsi->filepath, wsi->filepos))
902 libwebsocket_close_and_free_session(context, wsi, LWS_CLOSE_STATUS_NOSTATUS);
903 break;
904
Andy Green0d338332011-02-12 11:57:43 +0000905 case LWS_CONNMODE_SERVER_LISTENER:
906
907 /* pollin means a client has connected to us then */
908
David Galeanob88e0962013-01-10 09:54:10 +0800909 if (!(pollfd->revents & POLLIN))
Andy Green0d338332011-02-12 11:57:43 +0000910 break;
911
David Galeanof7009352011-09-26 12:09:54 +0100912 if (context->fds_count >= MAX_CLIENTS) {
Andy Green43db0452013-01-10 19:50:35 +0800913 lwsl_warn("too busy to accept new client\n");
David Galeanof7009352011-09-26 12:09:54 +0100914 break;
915 }
916
Andy Green0d338332011-02-12 11:57:43 +0000917 /* listen socket got an unencrypted connection... */
918
919 clilen = sizeof(cli_addr);
920 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
921 &clilen);
922 if (accept_fd < 0) {
Andy Green1023d2b2013-01-16 11:43:53 +0800923 lwsl_warn("ERROR on accept: %s\n", strerror(errno));
924 break;
Andy Green0d338332011-02-12 11:57:43 +0000925 }
926
Andy Green6c939552011-03-08 08:56:57 +0000927 /* Disable Nagle */
928 opt = 1;
Andy Green6ee372f2012-04-09 15:09:01 +0800929 setsockopt(accept_fd, IPPROTO_TCP, TCP_NODELAY,
930 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +0000931
Andy Green07034092011-02-13 08:37:12 +0000932 /*
933 * look at who we connected to and give user code a chance
934 * to reject based on client IP. There's no protocol selected
935 * yet so we issue this to protocols[0]
936 */
937
Peter Hinz56885f32011-03-02 22:03:47 +0000938 if ((context->protocols[0].callback)(context, wsi,
Andy Green07034092011-02-13 08:37:12 +0000939 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
Andy Green6ee372f2012-04-09 15:09:01 +0800940 (void *)(long)accept_fd, NULL, 0)) {
Andy Green43db0452013-01-10 19:50:35 +0800941 lwsl_debug("Callback denied network connection\n");
Andy Green3fc2c652013-01-14 15:35:02 +0800942 compatible_close(accept_fd);
Andy Green07034092011-02-13 08:37:12 +0000943 break;
944 }
945
Andy Greena41314f2011-05-23 10:00:03 +0100946 new_wsi = libwebsocket_create_new_server_wsi(context);
David Galeanoed3c8402013-01-10 10:45:24 +0800947 if (new_wsi == NULL) {
Andy Green3fc2c652013-01-14 15:35:02 +0800948 compatible_close(accept_fd);
Andy Green0d338332011-02-12 11:57:43 +0000949 break;
David Galeanoed3c8402013-01-10 10:45:24 +0800950 }
Andy Green0d338332011-02-12 11:57:43 +0000951
Andy Green0d338332011-02-12 11:57:43 +0000952 new_wsi->sock = accept_fd;
Andy Greena41314f2011-05-23 10:00:03 +0100953
Andy Green0d338332011-02-12 11:57:43 +0000954
955#ifdef LWS_OPENSSL_SUPPORT
956 new_wsi->ssl = NULL;
Andy Green0d338332011-02-12 11:57:43 +0000957
Peter Hinz56885f32011-03-02 22:03:47 +0000958 if (context->use_ssl) {
Andy Green0d338332011-02-12 11:57:43 +0000959
Peter Hinz56885f32011-03-02 22:03:47 +0000960 new_wsi->ssl = SSL_new(context->ssl_ctx);
Andy Green0d338332011-02-12 11:57:43 +0000961 if (new_wsi->ssl == NULL) {
Andy Green43db0452013-01-10 19:50:35 +0800962 lwsl_err("SSL_new failed: %s\n",
Andy Green0d338332011-02-12 11:57:43 +0000963 ERR_error_string(SSL_get_error(
964 new_wsi->ssl, 0), NULL));
Andy Green1f9bf522011-02-14 21:14:37 +0000965 libwebsockets_decode_ssl_error();
Andy Green0d338332011-02-12 11:57:43 +0000966 free(new_wsi);
Andy Green3fc2c652013-01-14 15:35:02 +0800967 compatible_close(accept_fd);
Andy Green0d338332011-02-12 11:57:43 +0000968 break;
969 }
970
Larry Hayes455d1fe2013-01-15 01:03:58 +0800971 SSL_set_ex_data(new_wsi->ssl,
972 openssl_websocket_private_data_index, context);
973
Andy Green0d338332011-02-12 11:57:43 +0000974 SSL_set_fd(new_wsi->ssl, accept_fd);
975
976 n = SSL_accept(new_wsi->ssl);
977 if (n != 1) {
978 /*
979 * browsers seem to probe with various
980 * ssl params which fail then retry
981 * and succeed
982 */
Andy Green43db0452013-01-10 19:50:35 +0800983 lwsl_debug("SSL_accept failed skt %u: %s\n",
Andy Green0d338332011-02-12 11:57:43 +0000984 pollfd->fd,
985 ERR_error_string(SSL_get_error(
986 new_wsi->ssl, n), NULL));
987 SSL_free(
988 new_wsi->ssl);
989 free(new_wsi);
Andy Green3fc2c652013-01-14 15:35:02 +0800990 compatible_close(accept_fd);
Andy Green0d338332011-02-12 11:57:43 +0000991 break;
992 }
Andy Green6ee372f2012-04-09 15:09:01 +0800993
Andy Green43db0452013-01-10 19:50:35 +0800994 lwsl_debug("accepted new SSL conn "
Andy Green0d338332011-02-12 11:57:43 +0000995 "port %u on fd=%d SSL ver %s\n",
996 ntohs(cli_addr.sin_port), accept_fd,
997 SSL_get_version(new_wsi->ssl));
998
999 } else
1000#endif
Andy Green43db0452013-01-10 19:50:35 +08001001 lwsl_debug("accepted new conn port %u on fd=%d\n",
Andy Green0d338332011-02-12 11:57:43 +00001002 ntohs(cli_addr.sin_port), accept_fd);
1003
Peter Hinz56885f32011-03-02 22:03:47 +00001004 insert_wsi(context, new_wsi);
Andy Green0d338332011-02-12 11:57:43 +00001005
Andy Green0d338332011-02-12 11:57:43 +00001006 /*
1007 * make sure NO events are seen yet on this new socket
1008 * (otherwise we inherit old fds[client].revents from
1009 * previous socket there and die mysteriously! )
1010 */
Peter Hinz56885f32011-03-02 22:03:47 +00001011 context->fds[context->fds_count].revents = 0;
Andy Green0d338332011-02-12 11:57:43 +00001012
Peter Hinz56885f32011-03-02 22:03:47 +00001013 context->fds[context->fds_count].events = POLLIN;
1014 context->fds[context->fds_count++].fd = accept_fd;
Andy Green0d338332011-02-12 11:57:43 +00001015
Andy Green3221f922011-02-12 13:14:11 +00001016 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001017 context->protocols[0].callback(context, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +00001018 LWS_CALLBACK_ADD_POLL_FD,
1019 (void *)(long)accept_fd, NULL, POLLIN);
1020
Andy Green0d338332011-02-12 11:57:43 +00001021 break;
1022
1023 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
1024
1025 /* as we are listening, POLLIN means accept() is needed */
Andy Green6ee372f2012-04-09 15:09:01 +08001026
David Galeanob88e0962013-01-10 09:54:10 +08001027 if (!(pollfd->revents & POLLIN))
Andy Green0d338332011-02-12 11:57:43 +00001028 break;
1029
1030 /* listen socket got an unencrypted connection... */
1031
1032 clilen = sizeof(cli_addr);
1033 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1034 &clilen);
1035 if (accept_fd < 0) {
Andy Green43db0452013-01-10 19:50:35 +08001036 lwsl_warn("ERROR on accept %d\n", accept_fd);
Andy Green3928f612012-07-20 12:58:38 +08001037 return -1;
Andy Green0d338332011-02-12 11:57:43 +00001038 }
1039
Peter Hinz56885f32011-03-02 22:03:47 +00001040 if (context->fds_count >= MAX_CLIENTS) {
Andy Green43db0452013-01-10 19:50:35 +08001041 lwsl_err("too busy to accept new broadcast "
Andy Green3221f922011-02-12 13:14:11 +00001042 "proxy client\n");
Andy Green41c58032013-01-12 13:21:08 +08001043 goto bail_prox_listener;
Andy Green0d338332011-02-12 11:57:43 +00001044 }
1045
1046 /* create a dummy wsi for the connection and add it */
1047
Aaron Zinman4550f1d2013-01-10 12:35:18 +08001048 new_wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
Andy Green41c58032013-01-12 13:21:08 +08001049 if (new_wsi == NULL) {
1050 lwsl_err("Out of mem\n");
1051 goto bail_prox_listener;
1052 }
Aaron Zinman4550f1d2013-01-10 12:35:18 +08001053 memset(new_wsi, 0, sizeof (struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00001054 new_wsi->sock = accept_fd;
1055 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
1056 new_wsi->state = WSI_STATE_ESTABLISHED;
Andy Greend6e09112011-03-05 16:12:15 +00001057 new_wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00001058 /* note which protocol we are proxying */
1059 new_wsi->protocol_index_for_broadcast_proxy =
1060 wsi->protocol_index_for_broadcast_proxy;
Peter Hinz56885f32011-03-02 22:03:47 +00001061 insert_wsi(context, new_wsi);
Andy Green0d338332011-02-12 11:57:43 +00001062
1063 /* add connected socket to internal poll array */
1064
Peter Hinz56885f32011-03-02 22:03:47 +00001065 context->fds[context->fds_count].revents = 0;
1066 context->fds[context->fds_count].events = POLLIN;
1067 context->fds[context->fds_count++].fd = accept_fd;
Andy Green0d338332011-02-12 11:57:43 +00001068
Andy Green3221f922011-02-12 13:14:11 +00001069 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001070 context->protocols[0].callback(context, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +00001071 LWS_CALLBACK_ADD_POLL_FD,
1072 (void *)(long)accept_fd, NULL, POLLIN);
1073
Andy Green0d338332011-02-12 11:57:43 +00001074 break;
1075
Andy Green41c58032013-01-12 13:21:08 +08001076bail_prox_listener:
Andy Green3fc2c652013-01-14 15:35:02 +08001077 compatible_close(accept_fd);
Andy Green41c58032013-01-12 13:21:08 +08001078 break;
1079
Andy Green0d338332011-02-12 11:57:43 +00001080 case LWS_CONNMODE_BROADCAST_PROXY:
Andy Green8f037e42010-12-19 22:13:26 +00001081
Andy Greenb45993c2010-12-18 15:13:50 +00001082 /* handle session socket closed */
Andy Green8f037e42010-12-19 22:13:26 +00001083
Andy Green0d338332011-02-12 11:57:43 +00001084 if (pollfd->revents & (POLLERR | POLLHUP)) {
Andy Green8f037e42010-12-19 22:13:26 +00001085
Andy Green43db0452013-01-10 19:50:35 +08001086 lwsl_debug("Session Socket %p (fd=%d) dead\n",
Timothy J Fontaineb86d64e2011-02-14 17:55:27 +00001087 (void *)wsi, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +00001088
Peter Hinz56885f32011-03-02 22:03:47 +00001089 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001090 LWS_CLOSE_STATUS_NORMAL);
Andy Green4b6fbe12011-02-14 08:03:48 +00001091 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001092 }
Andy Green8f037e42010-12-19 22:13:26 +00001093
Andy Green3b84c002011-03-06 13:14:42 +00001094 /*
1095 * either extension code with stuff to spill, or the user code,
1096 * requested a callback when it was OK to write
1097 */
Andy Green90c7cbc2011-01-27 06:26:52 +00001098
Andy Green3b84c002011-03-06 13:14:42 +00001099 if (pollfd->revents & POLLOUT)
Andy Green6ee372f2012-04-09 15:09:01 +08001100 if (lws_handle_POLLOUT_event(context, wsi,
1101 pollfd) < 0) {
1102 libwebsocket_close_and_free_session(
1103 context, wsi, LWS_CLOSE_STATUS_NORMAL);
Andy Green3b84c002011-03-06 13:14:42 +00001104 return 1;
1105 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001106
Andy Greenb45993c2010-12-18 15:13:50 +00001107 /* any incoming data ready? */
1108
Andy Green0d338332011-02-12 11:57:43 +00001109 if (!(pollfd->revents & POLLIN))
1110 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001111
Andy Green0d338332011-02-12 11:57:43 +00001112 /* get the issued broadcast payload from the socket */
Andy Greenb45993c2010-12-18 15:13:50 +00001113
Andy Green0d338332011-02-12 11:57:43 +00001114 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
1115 MAX_BROADCAST_PAYLOAD);
1116 if (len < 0) {
Andy Green43db0452013-01-10 19:50:35 +08001117 lwsl_err("Error reading broadcast payload\n");
Andy Green4b6fbe12011-02-14 08:03:48 +00001118 break;
Andy Green0d338332011-02-12 11:57:43 +00001119 }
Andy Greenb45993c2010-12-18 15:13:50 +00001120
Andy Green0d338332011-02-12 11:57:43 +00001121 /* broadcast it to all guys with this protocol index */
Andy Green8f037e42010-12-19 22:13:26 +00001122
Andy Green0d338332011-02-12 11:57:43 +00001123 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Green8f037e42010-12-19 22:13:26 +00001124
Peter Hinz56885f32011-03-02 22:03:47 +00001125 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +00001126
Peter Hinz56885f32011-03-02 22:03:47 +00001127 new_wsi = context->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +00001128
Andy Green0d338332011-02-12 11:57:43 +00001129 /* only to clients we are serving to */
Andy Greenb45993c2010-12-18 15:13:50 +00001130
Andy Green0d338332011-02-12 11:57:43 +00001131 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
Andy Greenb45993c2010-12-18 15:13:50 +00001132 continue;
1133
1134 /*
1135 * never broadcast to non-established
1136 * connection
1137 */
1138
Andy Green0d338332011-02-12 11:57:43 +00001139 if (new_wsi->state != WSI_STATE_ESTABLISHED)
Andy Green4739e5c2011-01-22 12:51:57 +00001140 continue;
1141
Andy Greenb45993c2010-12-18 15:13:50 +00001142 /*
1143 * only broadcast to connections using
1144 * the requested protocol
1145 */
1146
Andy Green0d338332011-02-12 11:57:43 +00001147 if (new_wsi->protocol->protocol_index !=
1148 wsi->protocol_index_for_broadcast_proxy)
Andy Greenb45993c2010-12-18 15:13:50 +00001149 continue;
1150
Andy Green8f037e42010-12-19 22:13:26 +00001151 /* broadcast it to this connection */
1152
Peter Hinz56885f32011-03-02 22:03:47 +00001153 new_wsi->protocol->callback(context, new_wsi,
Andy Green8f037e42010-12-19 22:13:26 +00001154 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +00001155 new_wsi->user_space,
Andy Green0ca6a172010-12-19 20:50:01 +00001156 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
Andy Greenb45993c2010-12-18 15:13:50 +00001157 }
Andy Green0d338332011-02-12 11:57:43 +00001158 }
1159 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001160
Andy Greenbe93fef2011-02-14 20:25:43 +00001161
Andy Green0d338332011-02-12 11:57:43 +00001162 case LWS_CONNMODE_WS_SERVING:
1163 case LWS_CONNMODE_WS_CLIENT:
1164
1165 /* handle session socket closed */
1166
1167 if (pollfd->revents & (POLLERR | POLLHUP)) {
1168
Andy Green43db0452013-01-10 19:50:35 +08001169 lwsl_debug("Session Socket %p (fd=%d) dead\n",
Andy Green0d338332011-02-12 11:57:43 +00001170 (void *)wsi, pollfd->fd);
1171
Peter Hinz56885f32011-03-02 22:03:47 +00001172 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001173 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green4b6fbe12011-02-14 08:03:48 +00001174 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001175 }
1176
Andy Green0d338332011-02-12 11:57:43 +00001177 /* the guy requested a callback when it was OK to write */
1178
Andy Greenda527df2011-03-07 07:08:12 +00001179 if ((pollfd->revents & POLLOUT) &&
1180 wsi->state == WSI_STATE_ESTABLISHED)
1181 if (lws_handle_POLLOUT_event(context, wsi,
1182 pollfd) < 0) {
1183 libwebsocket_close_and_free_session(
1184 context, wsi, LWS_CLOSE_STATUS_NORMAL);
Andy Green3b84c002011-03-06 13:14:42 +00001185 return 1;
1186 }
Andy Green0d338332011-02-12 11:57:43 +00001187
Andy Green0d338332011-02-12 11:57:43 +00001188
1189 /* any incoming data ready? */
1190
1191 if (!(pollfd->revents & POLLIN))
1192 break;
1193
Andy Greenb45993c2010-12-18 15:13:50 +00001194#ifdef LWS_OPENSSL_SUPPORT
David Galeano7ffbe1b2013-01-10 10:35:32 +08001195read_pending:
Andy Green0d338332011-02-12 11:57:43 +00001196 if (wsi->ssl)
Andy Green98a717c2011-03-06 13:14:15 +00001197 eff_buf.token_len = SSL_read(wsi->ssl, buf, sizeof buf);
Andy Greenb45993c2010-12-18 15:13:50 +00001198 else
1199#endif
Andy Green98a717c2011-03-06 13:14:15 +00001200 eff_buf.token_len =
Andy Green72c34322011-04-16 10:46:21 +01001201 recv(pollfd->fd, buf, sizeof buf, 0);
Andy Greenb45993c2010-12-18 15:13:50 +00001202
Andy Green98a717c2011-03-06 13:14:15 +00001203 if (eff_buf.token_len < 0) {
Andy Green43db0452013-01-10 19:50:35 +08001204 lwsl_debug("Socket read returned %d\n",
Andy Green98a717c2011-03-06 13:14:15 +00001205 eff_buf.token_len);
Alon Levydc93b7f2012-10-19 11:21:57 +02001206 if (errno != EINTR && errno != EAGAIN)
Andy Green6ee372f2012-04-09 15:09:01 +08001207 libwebsocket_close_and_free_session(context,
1208 wsi, LWS_CLOSE_STATUS_NOSTATUS);
Nick Dowellc04c1932012-04-05 10:29:39 +08001209 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001210 }
Andy Green98a717c2011-03-06 13:14:15 +00001211 if (!eff_buf.token_len) {
Peter Hinz56885f32011-03-02 22:03:47 +00001212 libwebsocket_close_and_free_session(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001213 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenfa3f4052012-10-07 20:40:35 +08001214 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00001215 }
1216
Andy Green98a717c2011-03-06 13:14:15 +00001217 /*
1218 * give any active extensions a chance to munge the buffer
1219 * before parse. We pass in a pointer to an lws_tokens struct
1220 * prepared with the default buffer and content length that's in
1221 * there. Rather than rewrite the default buffer, extensions
1222 * that expect to grow the buffer can adapt .token to
1223 * point to their own per-connection buffer in the extension
1224 * user allocation. By default with no extensions or no
1225 * extension callback handling, just the normal input buffer is
1226 * used then so it is efficient.
1227 */
Andy Greenb45993c2010-12-18 15:13:50 +00001228
Andy Green98a717c2011-03-06 13:14:15 +00001229 eff_buf.token = (char *)buf;
Andy Greenb45993c2010-12-18 15:13:50 +00001230
Andy Green98a717c2011-03-06 13:14:15 +00001231 more = 1;
1232 while (more) {
Andy Green0d338332011-02-12 11:57:43 +00001233
Andy Green98a717c2011-03-06 13:14:15 +00001234 more = 0;
1235
1236 for (n = 0; n < wsi->count_active_extensions; n++) {
Andy Green46c2ea02011-03-22 09:04:01 +00001237 m = wsi->active_extensions[n]->callback(context,
1238 wsi->active_extensions[n], wsi,
Andy Green98a717c2011-03-06 13:14:15 +00001239 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
Andy Green46c2ea02011-03-22 09:04:01 +00001240 wsi->active_extensions_user[n],
1241 &eff_buf, 0);
Andy Green98a717c2011-03-06 13:14:15 +00001242 if (m < 0) {
Andy Green43db0452013-01-10 19:50:35 +08001243 lwsl_ext(
Andy Green6ee372f2012-04-09 15:09:01 +08001244 "Extension reports fatal error\n");
1245 libwebsocket_close_and_free_session(
1246 context, wsi,
1247 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green98a717c2011-03-06 13:14:15 +00001248 return 1;
1249 }
1250 if (m)
1251 more = 1;
1252 }
1253
1254 /* service incoming data */
1255
1256 if (eff_buf.token_len) {
1257 n = libwebsocket_read(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001258 (unsigned char *)eff_buf.token,
1259 eff_buf.token_len);
Andy Green98a717c2011-03-06 13:14:15 +00001260 if (n < 0)
1261 /* we closed wsi */
1262 return 1;
1263 }
1264
1265 eff_buf.token = NULL;
1266 eff_buf.token_len = 0;
1267 }
David Galeano7ffbe1b2013-01-10 10:35:32 +08001268
1269#ifdef LWS_OPENSSL_SUPPORT
1270 if (wsi->ssl && SSL_pending(wsi->ssl))
1271 goto read_pending;
1272#endif
Andy Green98a717c2011-03-06 13:14:15 +00001273 break;
Andy Green76f61e72013-01-16 11:53:05 +08001274
1275 default:
1276 return lws_client_socket_service(context, wsi, pollfd);
Andy Greenb45993c2010-12-18 15:13:50 +00001277 }
1278
1279 return 0;
1280}
1281
Andy Green0d338332011-02-12 11:57:43 +00001282
Andy Green6964bb52011-01-23 16:50:33 +00001283/**
1284 * libwebsocket_context_destroy() - Destroy the websocket context
Peter Hinz56885f32011-03-02 22:03:47 +00001285 * @context: Websocket context
Andy Green6964bb52011-01-23 16:50:33 +00001286 *
1287 * This function closes any active connections and then frees the
1288 * context. After calling this, any further use of the context is
1289 * undefined.
1290 */
1291void
Peter Hinz56885f32011-03-02 22:03:47 +00001292libwebsocket_context_destroy(struct libwebsocket_context *context)
Andy Green6964bb52011-01-23 16:50:33 +00001293{
Andy Green0d338332011-02-12 11:57:43 +00001294 int n;
1295 int m;
1296 struct libwebsocket *wsi;
Andy Greena41314f2011-05-23 10:00:03 +01001297 struct libwebsocket_extension *ext;
Andy Green6964bb52011-01-23 16:50:33 +00001298
Andy Green4b6fbe12011-02-14 08:03:48 +00001299 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
Peter Hinz56885f32011-03-02 22:03:47 +00001300 for (m = 0; m < context->fd_hashtable[n].length; m++) {
1301 wsi = context->fd_hashtable[n].wsi[m];
1302 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001303 LWS_CLOSE_STATUS_GOINGAWAY);
Andy Greenf3d3b402011-02-09 07:16:34 +00001304 }
Andy Green6964bb52011-01-23 16:50:33 +00001305
Andy Greena41314f2011-05-23 10:00:03 +01001306 /*
1307 * give all extensions a chance to clean up any per-context
1308 * allocations they might have made
1309 */
1310
1311 ext = context->extensions;
1312 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
1313 if (context->listen_port)
1314 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
Paulo Roberto Urio1f680ab2012-06-04 08:40:28 +08001315 while (ext && ext->callback) {
Aaron Zinman4550f1d2013-01-10 12:35:18 +08001316 ext->callback(context, ext, NULL, (enum libwebsocket_extension_callback_reasons)m, NULL, NULL, 0);
Andy Greena41314f2011-05-23 10:00:03 +01001317 ext++;
1318 }
1319
Peter Hinz56885f32011-03-02 22:03:47 +00001320#ifdef WIN32
1321#else
1322 close(context->fd_random);
Andy Green6964bb52011-01-23 16:50:33 +00001323#endif
1324
Peter Hinz56885f32011-03-02 22:03:47 +00001325#ifdef LWS_OPENSSL_SUPPORT
1326 if (context->ssl_ctx)
1327 SSL_CTX_free(context->ssl_ctx);
1328 if (context->ssl_client_ctx)
1329 SSL_CTX_free(context->ssl_client_ctx);
1330#endif
1331
1332 free(context);
1333
1334#ifdef WIN32
1335 WSACleanup();
1336#endif
Andy Green6964bb52011-01-23 16:50:33 +00001337}
1338
Alon Levy0291eb32012-10-19 11:21:56 +02001339LWS_EXTERN void *
1340libwebsocket_context_user(struct libwebsocket_context *context)
1341{
1342 return context->user_space;
1343}
1344
Andy Green6964bb52011-01-23 16:50:33 +00001345/**
1346 * libwebsocket_service() - Service any pending websocket activity
Peter Hinz56885f32011-03-02 22:03:47 +00001347 * @context: Websocket context
Andy Green6964bb52011-01-23 16:50:33 +00001348 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1349 * service otherwise block and service immediately, returning
1350 * after the timeout if nothing needed service.
1351 *
1352 * This function deals with any pending websocket traffic, for three
1353 * kinds of event. It handles these events on both server and client
1354 * types of connection the same.
1355 *
1356 * 1) Accept new connections to our context's server
1357 *
1358 * 2) Perform pending broadcast writes initiated from other forked
1359 * processes (effectively serializing asynchronous broadcasts)
1360 *
1361 * 3) Call the receive callback for incoming frame data received by
1362 * server or client connections.
1363 *
1364 * You need to call this service function periodically to all the above
1365 * functions to happen; if your application is single-threaded you can
1366 * just call it in your main event loop.
1367 *
1368 * Alternatively you can fork a new process that asynchronously handles
1369 * calling this service in a loop. In that case you are happy if this
1370 * call blocks your thread until it needs to take care of something and
1371 * would call it with a large nonzero timeout. Your loop then takes no
1372 * CPU while there is nothing happening.
1373 *
1374 * If you are calling it in a single-threaded app, you don't want it to
1375 * wait around blocking other things in your loop from happening, so you
1376 * would call it with a timeout_ms of 0, so it returns immediately if
1377 * nothing is pending, or as soon as it services whatever was pending.
1378 */
1379
Andy Greenb45993c2010-12-18 15:13:50 +00001380
Andy Greene92cd172011-01-19 13:11:55 +00001381int
Peter Hinz56885f32011-03-02 22:03:47 +00001382libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
Andy Greene92cd172011-01-19 13:11:55 +00001383{
1384 int n;
Andy Greene92cd172011-01-19 13:11:55 +00001385
1386 /* stay dead once we are dead */
1387
Peter Hinz56885f32011-03-02 22:03:47 +00001388 if (context == NULL)
Andy Greene92cd172011-01-19 13:11:55 +00001389 return 1;
1390
Andy Green0d338332011-02-12 11:57:43 +00001391 /* wait for something to need service */
Andy Green4739e5c2011-01-22 12:51:57 +00001392
Peter Hinz56885f32011-03-02 22:03:47 +00001393 n = poll(context->fds, context->fds_count, timeout_ms);
Andy Green3221f922011-02-12 13:14:11 +00001394 if (n == 0) /* poll timeout */
1395 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00001396
Andy Greend280b6e2013-01-15 13:40:23 +08001397
1398
Andy Green62c54d22011-02-14 09:14:25 +00001399 if (n < 0) {
Andy Green5e1fa172011-02-10 09:07:05 +00001400 /*
Andy Green43db0452013-01-10 19:50:35 +08001401 lwsl_err("Listen Socket dead\n");
Andy Green5e1fa172011-02-10 09:07:05 +00001402 */
Andy Green3928f612012-07-20 12:58:38 +08001403 return -1;
Andy Greene92cd172011-01-19 13:11:55 +00001404 }
Andy Greene92cd172011-01-19 13:11:55 +00001405
1406 /* handle accept on listening socket? */
1407
Peter Hinz56885f32011-03-02 22:03:47 +00001408 for (n = 0; n < context->fds_count; n++)
1409 if (context->fds[n].revents)
Andy Green3928f612012-07-20 12:58:38 +08001410 if (libwebsocket_service_fd(context,
1411 &context->fds[n]) < 0)
1412 return -1;
Andy Greene92cd172011-01-19 13:11:55 +00001413 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00001414}
1415
Andy Greena41314f2011-05-23 10:00:03 +01001416int
1417lws_any_extension_handled(struct libwebsocket_context *context,
Andy Green6ee372f2012-04-09 15:09:01 +08001418 struct libwebsocket *wsi,
1419 enum libwebsocket_extension_callback_reasons r,
Andy Greena41314f2011-05-23 10:00:03 +01001420 void *v, size_t len)
1421{
1422 int n;
1423 int handled = 0;
1424
1425 /* maybe an extension will take care of it for us */
1426
1427 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
1428 if (!wsi->active_extensions[n]->callback)
1429 continue;
1430
1431 handled |= wsi->active_extensions[n]->callback(context,
1432 wsi->active_extensions[n], wsi,
1433 r, wsi->active_extensions_user[n], v, len);
1434 }
1435
1436 return handled;
1437}
1438
1439
1440void *
1441lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001442 struct libwebsocket_extension *ext)
Andy Greena41314f2011-05-23 10:00:03 +01001443{
1444 int n = 0;
1445
Andy Green68b45042011-05-25 21:41:57 +01001446 if (wsi == NULL)
1447 return NULL;
1448
Andy Greena41314f2011-05-23 10:00:03 +01001449 while (n < wsi->count_active_extensions) {
1450 if (wsi->active_extensions[n] != ext) {
1451 n++;
1452 continue;
1453 }
1454 return wsi->active_extensions_user[n];
1455 }
1456
1457 return NULL;
1458}
1459
Andy Green90c7cbc2011-01-27 06:26:52 +00001460/**
1461 * libwebsocket_callback_on_writable() - Request a callback when this socket
1462 * becomes able to be written to without
1463 * blocking
Andy Green32375b72011-02-19 08:32:53 +00001464 *
Peter Hinz56885f32011-03-02 22:03:47 +00001465 * @context: libwebsockets context
Andy Green90c7cbc2011-01-27 06:26:52 +00001466 * @wsi: Websocket connection instance to get callback for
1467 */
1468
1469int
Peter Hinz56885f32011-03-02 22:03:47 +00001470libwebsocket_callback_on_writable(struct libwebsocket_context *context,
Andy Green6ee372f2012-04-09 15:09:01 +08001471 struct libwebsocket *wsi)
Andy Green90c7cbc2011-01-27 06:26:52 +00001472{
Andy Green90c7cbc2011-01-27 06:26:52 +00001473 int n;
Andy Greena41314f2011-05-23 10:00:03 +01001474 int handled = 0;
1475
1476 /* maybe an extension will take care of it for us */
1477
1478 for (n = 0; n < wsi->count_active_extensions; n++) {
1479 if (!wsi->active_extensions[n]->callback)
1480 continue;
1481
1482 handled |= wsi->active_extensions[n]->callback(context,
1483 wsi->active_extensions[n], wsi,
1484 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
1485 wsi->active_extensions_user[n], NULL, 0);
1486 }
1487
1488 if (handled)
1489 return 1;
Andy Green90c7cbc2011-01-27 06:26:52 +00001490
Peter Hinz56885f32011-03-02 22:03:47 +00001491 for (n = 0; n < context->fds_count; n++)
1492 if (context->fds[n].fd == wsi->sock) {
1493 context->fds[n].events |= POLLOUT;
Andy Greena41314f2011-05-23 10:00:03 +01001494 n = context->fds_count + 1;
Andy Green90c7cbc2011-01-27 06:26:52 +00001495 }
1496
Andy Greena41314f2011-05-23 10:00:03 +01001497 if (n == context->fds_count)
Andy Green43db0452013-01-10 19:50:35 +08001498 lwsl_err("libwebsocket_callback_on_writable: "
Andy Green6ee372f2012-04-09 15:09:01 +08001499 "failed to find socket %d\n", wsi->sock);
Andy Greena41314f2011-05-23 10:00:03 +01001500
Andy Green3221f922011-02-12 13:14:11 +00001501 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001502 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001503 LWS_CALLBACK_SET_MODE_POLL_FD,
1504 (void *)(long)wsi->sock, NULL, POLLOUT);
1505
Andy Green90c7cbc2011-01-27 06:26:52 +00001506 return 1;
1507}
1508
1509/**
1510 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1511 * all connections using the given protocol when it
1512 * becomes possible to write to each socket without
1513 * blocking in turn.
1514 *
1515 * @protocol: Protocol whose connections will get callbacks
1516 */
1517
1518int
1519libwebsocket_callback_on_writable_all_protocol(
1520 const struct libwebsocket_protocols *protocol)
1521{
Peter Hinz56885f32011-03-02 22:03:47 +00001522 struct libwebsocket_context *context = protocol->owning_server;
Andy Green90c7cbc2011-01-27 06:26:52 +00001523 int n;
Andy Green0d338332011-02-12 11:57:43 +00001524 int m;
1525 struct libwebsocket *wsi;
Andy Green90c7cbc2011-01-27 06:26:52 +00001526
Andy Green0d338332011-02-12 11:57:43 +00001527 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1528
Peter Hinz56885f32011-03-02 22:03:47 +00001529 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Green0d338332011-02-12 11:57:43 +00001530
Peter Hinz56885f32011-03-02 22:03:47 +00001531 wsi = context->fd_hashtable[n].wsi[m];
Andy Green0d338332011-02-12 11:57:43 +00001532
1533 if (wsi->protocol == protocol)
Peter Hinz56885f32011-03-02 22:03:47 +00001534 libwebsocket_callback_on_writable(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00001535 }
1536 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001537
1538 return 0;
1539}
1540
Andy Greenbe93fef2011-02-14 20:25:43 +00001541/**
1542 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1543 *
1544 * You will not need this unless you are doing something special
1545 *
1546 * @wsi: Websocket connection instance
1547 * @reason: timeout reason
1548 * @secs: how many seconds
1549 */
1550
1551void
1552libwebsocket_set_timeout(struct libwebsocket *wsi,
1553 enum pending_timeout reason, int secs)
1554{
1555 struct timeval tv;
1556
1557 gettimeofday(&tv, NULL);
1558
1559 wsi->pending_timeout_limit = tv.tv_sec + secs;
1560 wsi->pending_timeout = reason;
1561}
1562
Andy Greena6cbece2011-01-27 20:06:03 +00001563
1564/**
1565 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1566 *
1567 * You will not need this unless you are doing something special
1568 *
1569 * @wsi: Websocket connection instance
1570 */
1571
1572int
1573libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1574{
1575 return wsi->sock;
1576}
1577
Andy Green90c7cbc2011-01-27 06:26:52 +00001578/**
1579 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1580 * receieved packets.
1581 *
1582 * If the output side of a server process becomes choked, this allows flow
1583 * control for the input side.
1584 *
1585 * @wsi: Websocket connection instance to get callback for
1586 * @enable: 0 = disable read servicing for this connection, 1 = enable
1587 */
1588
1589int
1590libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1591{
Peter Hinz56885f32011-03-02 22:03:47 +00001592 struct libwebsocket_context *context = wsi->protocol->owning_server;
Andy Green90c7cbc2011-01-27 06:26:52 +00001593 int n;
1594
Peter Hinz56885f32011-03-02 22:03:47 +00001595 for (n = 0; n < context->fds_count; n++)
1596 if (context->fds[n].fd == wsi->sock) {
Andy Green90c7cbc2011-01-27 06:26:52 +00001597 if (enable)
Peter Hinz56885f32011-03-02 22:03:47 +00001598 context->fds[n].events |= POLLIN;
Andy Green90c7cbc2011-01-27 06:26:52 +00001599 else
Peter Hinz56885f32011-03-02 22:03:47 +00001600 context->fds[n].events &= ~POLLIN;
Andy Green90c7cbc2011-01-27 06:26:52 +00001601
1602 return 0;
1603 }
1604
Andy Green3221f922011-02-12 13:14:11 +00001605 if (enable)
1606 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001607 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001608 LWS_CALLBACK_SET_MODE_POLL_FD,
1609 (void *)(long)wsi->sock, NULL, POLLIN);
1610 else
1611 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001612 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001613 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1614 (void *)(long)wsi->sock, NULL, POLLIN);
1615
Andy Greena41314f2011-05-23 10:00:03 +01001616#if 0
Andy Green43db0452013-01-10 19:50:35 +08001617 lwsl_err("libwebsocket_rx_flow_control unable to find socket\n");
Andy Greena41314f2011-05-23 10:00:03 +01001618#endif
Andy Green90c7cbc2011-01-27 06:26:52 +00001619 return 1;
1620}
1621
Andy Green2ac5a6f2011-01-28 10:00:18 +00001622/**
1623 * libwebsocket_canonical_hostname() - returns this host's hostname
1624 *
1625 * This is typically used by client code to fill in the host parameter
1626 * when making a client connection. You can only call it after the context
1627 * has been created.
1628 *
Peter Hinz56885f32011-03-02 22:03:47 +00001629 * @context: Websocket context
Andy Green2ac5a6f2011-01-28 10:00:18 +00001630 */
1631
1632
1633extern const char *
Peter Hinz56885f32011-03-02 22:03:47 +00001634libwebsocket_canonical_hostname(struct libwebsocket_context *context)
Andy Green2ac5a6f2011-01-28 10:00:18 +00001635{
Peter Hinz56885f32011-03-02 22:03:47 +00001636 return (const char *)context->canonical_hostname;
Andy Green2ac5a6f2011-01-28 10:00:18 +00001637}
1638
1639
Andy Green90c7cbc2011-01-27 06:26:52 +00001640static void sigpipe_handler(int x)
1641{
1642}
1643
Andy Green6901cb32011-02-21 08:06:47 +00001644#ifdef LWS_OPENSSL_SUPPORT
1645static int
1646OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1647{
1648
1649 SSL *ssl;
1650 int n;
Andy Green2e24da02011-03-05 16:12:04 +00001651 struct libwebsocket_context *context;
Andy Green6901cb32011-02-21 08:06:47 +00001652
1653 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1654 SSL_get_ex_data_X509_STORE_CTX_idx());
1655
1656 /*
Andy Green2e24da02011-03-05 16:12:04 +00001657 * !!! nasty openssl requires the index to come as a library-scope
1658 * static
Andy Green6901cb32011-02-21 08:06:47 +00001659 */
Andy Green2e24da02011-03-05 16:12:04 +00001660 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
Andy Green6ee372f2012-04-09 15:09:01 +08001661
Peter Hinz56885f32011-03-02 22:03:47 +00001662 n = context->protocols[0].callback(NULL, NULL,
Andy Green6901cb32011-02-21 08:06:47 +00001663 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1664 x509_ctx, ssl, preverify_ok);
1665
1666 /* convert return code from 0 = OK to 1 = OK */
1667
1668 if (!n)
1669 n = 1;
1670 else
1671 n = 0;
1672
1673 return n;
1674}
1675#endif
1676
Andy Greenb45993c2010-12-18 15:13:50 +00001677
Andy Greenab990e42010-10-31 12:42:52 +00001678/**
Andy Green4739e5c2011-01-22 12:51:57 +00001679 * libwebsocket_create_context() - Create the websocket handler
1680 * @port: Port to listen on... you can use 0 to suppress listening on
Andy Green6964bb52011-01-23 16:50:33 +00001681 * any port, that's what you want if you are not running a
1682 * websocket server at all but just using it as a client
Peter Hinz56885f32011-03-02 22:03:47 +00001683 * @interf: NULL to bind the listen socket to all interfaces, or the
Andy Green32375b72011-02-19 08:32:53 +00001684 * interface name, eg, "eth2"
Andy Green4f3943a2010-11-12 10:44:16 +00001685 * @protocols: Array of structures listing supported protocols and a protocol-
Andy Green8f037e42010-12-19 22:13:26 +00001686 * specific callback for each one. The list is ended with an
1687 * entry that has a NULL callback pointer.
Andy Green6964bb52011-01-23 16:50:33 +00001688 * It's not const because we write the owning_server member
Andy Greenc5114822011-03-06 10:29:35 +00001689 * @extensions: NULL or array of libwebsocket_extension structs listing the
Andy Green6ee372f2012-04-09 15:09:01 +08001690 * extensions this context supports
Andy Green3faa9c72010-11-08 17:03:03 +00001691 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
Andy Green8f037e42010-12-19 22:13:26 +00001692 * to listen using SSL, set to the filepath to fetch the
1693 * server cert from, otherwise NULL for unencrypted
Andy Green3faa9c72010-11-08 17:03:03 +00001694 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
Andy Green8f037e42010-12-19 22:13:26 +00001695 * else ignored
David Galeano2f82be82013-01-09 16:25:54 +08001696 * @ssl_ca_filepath: CA certificate filepath or NULL
Andy Green3faa9c72010-11-08 17:03:03 +00001697 * @gid: group id to change to after setting listen socket, or -1.
1698 * @uid: user id to change to after setting listen socket, or -1.
Andy Greenbfb051f2011-02-09 08:49:14 +00001699 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
Andy Green15e31f32012-10-19 18:36:28 +08001700 * @user: optional user pointer that can be recovered via the context
1701 * pointer using libwebsocket_context_user
Andy Green05464c62010-11-12 10:44:18 +00001702 *
Andy Green8f037e42010-12-19 22:13:26 +00001703 * This function creates the listening socket and takes care
1704 * of all initialization in one step.
1705 *
Andy Greene92cd172011-01-19 13:11:55 +00001706 * After initialization, it returns a struct libwebsocket_context * that
1707 * represents this server. After calling, user code needs to take care
1708 * of calling libwebsocket_service() with the context pointer to get the
1709 * server's sockets serviced. This can be done in the same process context
1710 * or a forked process, or another thread,
Andy Green05464c62010-11-12 10:44:18 +00001711 *
Andy Green8f037e42010-12-19 22:13:26 +00001712 * The protocol callback functions are called for a handful of events
1713 * including http requests coming in, websocket connections becoming
1714 * established, and data arriving; it's also called periodically to allow
1715 * async transmission.
1716 *
1717 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1718 * at that time websocket protocol has not been negotiated. Other
1719 * protocols after the first one never see any HTTP callack activity.
1720 *
1721 * The server created is a simple http server by default; part of the
1722 * websocket standard is upgrading this http connection to a websocket one.
1723 *
1724 * This allows the same server to provide files like scripts and favicon /
1725 * images or whatever over http and dynamic data over websockets all in
1726 * one place; they're all handled in the user callback.
Andy Greenab990e42010-10-31 12:42:52 +00001727 */
Andy Green4ea60062010-10-30 12:15:07 +01001728
Andy Greene92cd172011-01-19 13:11:55 +00001729struct libwebsocket_context *
Peter Hinz56885f32011-03-02 22:03:47 +00001730libwebsocket_create_context(int port, const char *interf,
Andy Greenb45993c2010-12-18 15:13:50 +00001731 struct libwebsocket_protocols *protocols,
Andy Greend6e09112011-03-05 16:12:15 +00001732 struct libwebsocket_extension *extensions,
Andy Green8f037e42010-12-19 22:13:26 +00001733 const char *ssl_cert_filepath,
1734 const char *ssl_private_key_filepath,
David Galeano2f82be82013-01-09 16:25:54 +08001735 const char *ssl_ca_filepath,
Alon Levy0291eb32012-10-19 11:21:56 +02001736 int gid, int uid, unsigned int options,
David Galeano2f82be82013-01-09 16:25:54 +08001737 void *user)
Andy Greenff95d7a2010-10-28 22:36:01 +01001738{
1739 int n;
Andy Greena41314f2011-05-23 10:00:03 +01001740 int m;
Andy Green4739e5c2011-01-22 12:51:57 +00001741 int sockfd = 0;
Andy Green251f6fa2010-11-03 11:13:06 +00001742 int fd;
Andy Greenff95d7a2010-10-28 22:36:01 +01001743 struct sockaddr_in serv_addr, cli_addr;
Andy Green251f6fa2010-11-03 11:13:06 +00001744 int opt = 1;
Peter Hinz56885f32011-03-02 22:03:47 +00001745 struct libwebsocket_context *context = NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001746 unsigned int slen;
Andy Green9659f372011-01-27 22:01:43 +00001747 char *p;
Paulo Roberto Urio1e326632012-06-04 10:52:19 +08001748 char hostname[1024] = "";
Andy Greena69f0512012-05-03 12:32:38 +08001749// struct hostent *he;
Andy Green0d338332011-02-12 11:57:43 +00001750 struct libwebsocket *wsi;
Andy Greena69f0512012-05-03 12:32:38 +08001751 struct sockaddr sa;
Andy Greenff95d7a2010-10-28 22:36:01 +01001752
Andy Green3faa9c72010-11-08 17:03:03 +00001753#ifdef LWS_OPENSSL_SUPPORT
Andy Greenf2f54d52010-11-15 22:08:00 +00001754 SSL_METHOD *method;
Andy Green3faa9c72010-11-08 17:03:03 +00001755 char ssl_err_buf[512];
Andy Green3faa9c72010-11-08 17:03:03 +00001756#endif
1757
Andy Green43db0452013-01-10 19:50:35 +08001758 lwsl_info("Initial logging level %d\n", log_level);
Andy Greenc0d6b632013-01-12 23:42:17 +08001759 lwsl_info(" FD_HASHTABLE_MODULUS: %u\n", FD_HASHTABLE_MODULUS);
1760 lwsl_info(" MAX_CLIENTS: %u\n", MAX_CLIENTS);
1761 lwsl_info(" LWS_MAX_HEADER_NAME_LENGTH: %u\n", LWS_MAX_HEADER_NAME_LENGTH);
1762 lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
1763 lwsl_info(" LWS_INITIAL_HDR_ALLOC: %u\n", LWS_INITIAL_HDR_ALLOC);
1764 lwsl_info(" LWS_ADDITIONAL_HDR_ALLOC: %u\n", LWS_ADDITIONAL_HDR_ALLOC);
1765 lwsl_info(" MAX_USER_RX_BUFFER: %u\n", MAX_USER_RX_BUFFER);
1766 lwsl_info(" MAX_BROADCAST_PAYLOAD: %u\n", MAX_BROADCAST_PAYLOAD);
1767 lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
1768 lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n", LWS_MAX_EXTENSIONS_ACTIVE);
1769 lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
1770 lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
1771 lwsl_info(" CIPHERS_LIST_STRING: '%s'\n", CIPHERS_LIST_STRING);
1772 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
1773 lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
Andy Green43db0452013-01-10 19:50:35 +08001774
Peter Hinz56885f32011-03-02 22:03:47 +00001775#ifdef _WIN32
1776 {
1777 WORD wVersionRequested;
1778 WSADATA wsaData;
1779 int err;
Andy Green6ee372f2012-04-09 15:09:01 +08001780 HMODULE wsdll;
Peter Hinz56885f32011-03-02 22:03:47 +00001781
1782 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1783 wVersionRequested = MAKEWORD(2, 2);
1784
1785 err = WSAStartup(wVersionRequested, &wsaData);
1786 if (err != 0) {
1787 /* Tell the user that we could not find a usable */
1788 /* Winsock DLL. */
Andy Green43db0452013-01-10 19:50:35 +08001789 lwsl_err("WSAStartup failed with error: %d\n", err);
Peter Hinz56885f32011-03-02 22:03:47 +00001790 return NULL;
1791 }
David Galeano7b11fec2011-10-04 19:55:18 +08001792
Andy Green6ee372f2012-04-09 15:09:01 +08001793 /* default to a poll() made out of select() */
1794 poll = emulated_poll;
David Galeano7b11fec2011-10-04 19:55:18 +08001795
Andy Green6ee372f2012-04-09 15:09:01 +08001796 /* if windows socket lib available, use his WSAPoll */
David Galeanocb193682013-01-09 15:29:00 +08001797 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
Andy Green6ee372f2012-04-09 15:09:01 +08001798 if (wsdll)
1799 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
Peter Hinz56885f32011-03-02 22:03:47 +00001800 }
1801#endif
1802
1803
Aaron Zinman4550f1d2013-01-10 12:35:18 +08001804 context = (struct libwebsocket_context *) malloc(sizeof(struct libwebsocket_context));
Peter Hinz56885f32011-03-02 22:03:47 +00001805 if (!context) {
Andy Green43db0452013-01-10 19:50:35 +08001806 lwsl_err("No memory for websocket context\n");
Andy Green90c7cbc2011-01-27 06:26:52 +00001807 return NULL;
1808 }
Peter Hinz56885f32011-03-02 22:03:47 +00001809 context->protocols = protocols;
1810 context->listen_port = port;
1811 context->http_proxy_port = 0;
1812 context->http_proxy_address[0] = '\0';
1813 context->options = options;
1814 context->fds_count = 0;
Andy Greend6e09112011-03-05 16:12:15 +00001815 context->extensions = extensions;
Paulo Roberto Urio1e326632012-06-04 10:52:19 +08001816 context->last_timeout_check_s = 0;
Alon Levy0291eb32012-10-19 11:21:56 +02001817 context->user_space = user;
Andy Green9659f372011-01-27 22:01:43 +00001818
Peter Hinz56885f32011-03-02 22:03:47 +00001819#ifdef WIN32
1820 context->fd_random = 0;
1821#else
1822 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1823 if (context->fd_random < 0) {
Andy Green43db0452013-01-10 19:50:35 +08001824 lwsl_err("Unable to open random device %s %d\n",
Peter Hinz56885f32011-03-02 22:03:47 +00001825 SYSTEM_RANDOM_FILEPATH, context->fd_random);
Andy Green44eee682011-02-10 09:32:24 +00001826 return NULL;
1827 }
Peter Hinz56885f32011-03-02 22:03:47 +00001828#endif
Andy Green44eee682011-02-10 09:32:24 +00001829
Peter Hinz56885f32011-03-02 22:03:47 +00001830#ifdef LWS_OPENSSL_SUPPORT
1831 context->use_ssl = 0;
1832 context->ssl_ctx = NULL;
1833 context->ssl_client_ctx = NULL;
Andy Green2e24da02011-03-05 16:12:04 +00001834 openssl_websocket_private_data_index = 0;
Peter Hinz56885f32011-03-02 22:03:47 +00001835#endif
Andy Green2ac5a6f2011-01-28 10:00:18 +00001836
Andy Green788c4a82012-10-22 12:29:57 +01001837 if (options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME) {
Andy Greena69f0512012-05-03 12:32:38 +08001838
Andy Green788c4a82012-10-22 12:29:57 +01001839 strcpy(context->canonical_hostname, "unknown");
Andy Greena69f0512012-05-03 12:32:38 +08001840
Andy Green788c4a82012-10-22 12:29:57 +01001841 } else {
1842
1843 /* find canonical hostname */
1844
1845 hostname[(sizeof hostname) - 1] = '\0';
1846 memset(&sa, 0, sizeof(sa));
1847 sa.sa_family = AF_INET;
1848 sa.sa_data[(sizeof sa.sa_data) - 1] = '\0';
1849 gethostname(hostname, (sizeof hostname) - 1);
1850
1851 n = 0;
1852
David Galeanoed3c8402013-01-10 10:45:24 +08001853 if (strlen(hostname) < sizeof(sa.sa_data) - 1) {
Andy Green788c4a82012-10-22 12:29:57 +01001854 strcpy(sa.sa_data, hostname);
Andy Green43db0452013-01-10 19:50:35 +08001855 // lwsl_debug("my host name is %s\n", sa.sa_data);
Andy Green788c4a82012-10-22 12:29:57 +01001856 n = getnameinfo(&sa, sizeof(sa), hostname,
1857 (sizeof hostname) - 1, NULL, 0, 0);
1858 }
1859
1860 if (!n) {
1861 strncpy(context->canonical_hostname, hostname,
1862 sizeof context->canonical_hostname - 1);
1863 context->canonical_hostname[
1864 sizeof context->canonical_hostname - 1] = '\0';
1865 } else
1866 strncpy(context->canonical_hostname, hostname,
1867 sizeof context->canonical_hostname - 1);
1868
Andy Green43db0452013-01-10 19:50:35 +08001869 // lwsl_debug("context->canonical_hostname = %s\n",
Andy Green788c4a82012-10-22 12:29:57 +01001870 // context->canonical_hostname);
Andy Greena69f0512012-05-03 12:32:38 +08001871 }
1872
Andy Green9659f372011-01-27 22:01:43 +00001873 /* split the proxy ads:port if given */
1874
1875 p = getenv("http_proxy");
1876 if (p) {
Peter Hinz56885f32011-03-02 22:03:47 +00001877 strncpy(context->http_proxy_address, p,
Andy Green6ee372f2012-04-09 15:09:01 +08001878 sizeof context->http_proxy_address - 1);
Peter Hinz56885f32011-03-02 22:03:47 +00001879 context->http_proxy_address[
1880 sizeof context->http_proxy_address - 1] = '\0';
Andy Green9659f372011-01-27 22:01:43 +00001881
Peter Hinz56885f32011-03-02 22:03:47 +00001882 p = strchr(context->http_proxy_address, ':');
Andy Green9659f372011-01-27 22:01:43 +00001883 if (p == NULL) {
Andy Green43db0452013-01-10 19:50:35 +08001884 lwsl_err("http_proxy needs to be ads:port\n");
Andy Green9659f372011-01-27 22:01:43 +00001885 return NULL;
1886 }
1887 *p = '\0';
Peter Hinz56885f32011-03-02 22:03:47 +00001888 context->http_proxy_port = atoi(p + 1);
Andy Green9659f372011-01-27 22:01:43 +00001889
Andy Green43db0452013-01-10 19:50:35 +08001890 lwsl_debug("Using proxy %s:%u\n",
Peter Hinz56885f32011-03-02 22:03:47 +00001891 context->http_proxy_address,
1892 context->http_proxy_port);
Andy Green9659f372011-01-27 22:01:43 +00001893 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001894
1895 if (port) {
1896
Andy Green3faa9c72010-11-08 17:03:03 +00001897#ifdef LWS_OPENSSL_SUPPORT
Peter Hinz56885f32011-03-02 22:03:47 +00001898 context->use_ssl = ssl_cert_filepath != NULL &&
Andy Green90c7cbc2011-01-27 06:26:52 +00001899 ssl_private_key_filepath != NULL;
Peter Hinz56885f32011-03-02 22:03:47 +00001900 if (context->use_ssl)
Andy Green43db0452013-01-10 19:50:35 +08001901 lwsl_info(" Compiled with SSL support, using it\n");
Andy Green90c7cbc2011-01-27 06:26:52 +00001902 else
Andy Green43db0452013-01-10 19:50:35 +08001903 lwsl_info(" Compiled with SSL support, not using it\n");
Andy Green3faa9c72010-11-08 17:03:03 +00001904
Andy Green90c7cbc2011-01-27 06:26:52 +00001905#else
1906 if (ssl_cert_filepath != NULL &&
1907 ssl_private_key_filepath != NULL) {
Andy Green43db0452013-01-10 19:50:35 +08001908 lwsl_info(" Not compiled for OpenSSl support!\n");
Andy Greene92cd172011-01-19 13:11:55 +00001909 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00001910 }
Andy Green43db0452013-01-10 19:50:35 +08001911 lwsl_info(" Compiled without SSL support, "
Andy Green90c7cbc2011-01-27 06:26:52 +00001912 "serving unencrypted\n");
1913#endif
1914 }
1915
1916 /* ignore SIGPIPE */
Peter Hinz56885f32011-03-02 22:03:47 +00001917#ifdef WIN32
1918#else
Andy Green90c7cbc2011-01-27 06:26:52 +00001919 signal(SIGPIPE, sigpipe_handler);
Peter Hinz56885f32011-03-02 22:03:47 +00001920#endif
Andy Green90c7cbc2011-01-27 06:26:52 +00001921
1922
1923#ifdef LWS_OPENSSL_SUPPORT
1924
1925 /* basic openssl init */
1926
1927 SSL_library_init();
1928
1929 OpenSSL_add_all_algorithms();
1930 SSL_load_error_strings();
1931
Andy Green2e24da02011-03-05 16:12:04 +00001932 openssl_websocket_private_data_index =
Andy Green6901cb32011-02-21 08:06:47 +00001933 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1934
Andy Green90c7cbc2011-01-27 06:26:52 +00001935 /*
1936 * Firefox insists on SSLv23 not SSLv3
1937 * Konq disables SSLv2 by default now, SSLv23 works
1938 */
1939
1940 method = (SSL_METHOD *)SSLv23_server_method();
1941 if (!method) {
Andy Green43db0452013-01-10 19:50:35 +08001942 lwsl_err("problem creating ssl method: %s\n",
Andy Green90c7cbc2011-01-27 06:26:52 +00001943 ERR_error_string(ERR_get_error(), ssl_err_buf));
1944 return NULL;
1945 }
Peter Hinz56885f32011-03-02 22:03:47 +00001946 context->ssl_ctx = SSL_CTX_new(method); /* create context */
1947 if (!context->ssl_ctx) {
Andy Green43db0452013-01-10 19:50:35 +08001948 lwsl_err("problem creating ssl context: %s\n",
Andy Green90c7cbc2011-01-27 06:26:52 +00001949 ERR_error_string(ERR_get_error(), ssl_err_buf));
1950 return NULL;
1951 }
1952
David Galeanocc148e42013-01-10 10:18:59 +08001953#ifdef SSL_OP_NO_COMPRESSION
David Galeanoc72f6f92013-01-10 10:11:57 +08001954 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
David Galeanocc148e42013-01-10 10:18:59 +08001955#endif
David Galeano77a677c2013-01-10 10:14:12 +08001956 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
David Galeanof177f2a2013-01-10 10:15:19 +08001957 SSL_CTX_set_cipher_list(context->ssl_ctx, CIPHERS_LIST_STRING);
David Galeanoc72f6f92013-01-10 10:11:57 +08001958
Andy Green90c7cbc2011-01-27 06:26:52 +00001959 /* client context */
Andy Green6ee372f2012-04-09 15:09:01 +08001960
1961 if (port == CONTEXT_PORT_NO_LISTEN) {
Peter Hinz56885f32011-03-02 22:03:47 +00001962 method = (SSL_METHOD *)SSLv23_client_method();
1963 if (!method) {
Andy Green43db0452013-01-10 19:50:35 +08001964 lwsl_err("problem creating ssl method: %s\n",
Peter Hinz56885f32011-03-02 22:03:47 +00001965 ERR_error_string(ERR_get_error(), ssl_err_buf));
1966 return NULL;
1967 }
1968 /* create context */
1969 context->ssl_client_ctx = SSL_CTX_new(method);
1970 if (!context->ssl_client_ctx) {
Andy Green43db0452013-01-10 19:50:35 +08001971 lwsl_err("problem creating ssl context: %s\n",
Peter Hinz56885f32011-03-02 22:03:47 +00001972 ERR_error_string(ERR_get_error(), ssl_err_buf));
1973 return NULL;
1974 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001975
David Galeanocc148e42013-01-10 10:18:59 +08001976#ifdef SSL_OP_NO_COMPRESSION
David Galeanoc72f6f92013-01-10 10:11:57 +08001977 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_NO_COMPRESSION);
David Galeanocc148e42013-01-10 10:18:59 +08001978#endif
David Galeano77a677c2013-01-10 10:14:12 +08001979 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
David Galeanof177f2a2013-01-10 10:15:19 +08001980 SSL_CTX_set_cipher_list(context->ssl_client_ctx, CIPHERS_LIST_STRING);
David Galeanoc72f6f92013-01-10 10:11:57 +08001981
Peter Hinz56885f32011-03-02 22:03:47 +00001982 /* openssl init for cert verification (for client sockets) */
David Galeano2f82be82013-01-09 16:25:54 +08001983 if (!ssl_ca_filepath) {
1984 if (!SSL_CTX_load_verify_locations(
1985 context->ssl_client_ctx, NULL,
1986 LWS_OPENSSL_CLIENT_CERTS))
Andy Green43db0452013-01-10 19:50:35 +08001987 lwsl_err(
David Galeano2f82be82013-01-09 16:25:54 +08001988 "Unable to load SSL Client certs from %s "
1989 "(set by --with-client-cert-dir= in configure) -- "
1990 " client ssl isn't going to work",
1991 LWS_OPENSSL_CLIENT_CERTS);
1992 } else
1993 if (!SSL_CTX_load_verify_locations(
1994 context->ssl_client_ctx, ssl_ca_filepath,
1995 NULL))
Andy Green43db0452013-01-10 19:50:35 +08001996 lwsl_err(
David Galeano2f82be82013-01-09 16:25:54 +08001997 "Unable to load SSL Client certs "
1998 "file from %s -- client ssl isn't "
1999 "going to work", ssl_ca_filepath);
Peter Hinz56885f32011-03-02 22:03:47 +00002000
2001 /*
2002 * callback allowing user code to load extra verification certs
2003 * helping the client to verify server identity
2004 */
2005
2006 context->protocols[0].callback(context, NULL,
2007 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
2008 context->ssl_client_ctx, NULL, 0);
Andy Green90c7cbc2011-01-27 06:26:52 +00002009 }
Andy Green6ee372f2012-04-09 15:09:01 +08002010
Andy Greenc6bf2c22011-02-20 11:10:47 +00002011 /* as a server, are we requiring clients to identify themselves? */
2012
2013 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
2014
2015 /* absolutely require the client cert */
Andy Green6ee372f2012-04-09 15:09:01 +08002016
Peter Hinz56885f32011-03-02 22:03:47 +00002017 SSL_CTX_set_verify(context->ssl_ctx,
Andy Green6901cb32011-02-21 08:06:47 +00002018 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2019 OpenSSL_verify_callback);
Andy Greenc6bf2c22011-02-20 11:10:47 +00002020
2021 /*
2022 * give user code a chance to load certs into the server
2023 * allowing it to verify incoming client certs
2024 */
2025
Peter Hinz56885f32011-03-02 22:03:47 +00002026 context->protocols[0].callback(context, NULL,
Andy Greenc6bf2c22011-02-20 11:10:47 +00002027 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
Peter Hinz56885f32011-03-02 22:03:47 +00002028 context->ssl_ctx, NULL, 0);
Andy Greenc6bf2c22011-02-20 11:10:47 +00002029 }
2030
Peter Hinz56885f32011-03-02 22:03:47 +00002031 if (context->use_ssl) {
Andy Green90c7cbc2011-01-27 06:26:52 +00002032
2033 /* openssl init for server sockets */
2034
Andy Green3faa9c72010-11-08 17:03:03 +00002035 /* set the local certificate from CertFile */
David Galeano9b3d4b22013-01-10 10:11:21 +08002036 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
2037 ssl_cert_filepath);
Andy Green3faa9c72010-11-08 17:03:03 +00002038 if (n != 1) {
Andy Green43db0452013-01-10 19:50:35 +08002039 lwsl_err("problem getting cert '%s': %s\n",
Andy Green3faa9c72010-11-08 17:03:03 +00002040 ssl_cert_filepath,
2041 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00002042 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002043 }
2044 /* set the private key from KeyFile */
Peter Hinz56885f32011-03-02 22:03:47 +00002045 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2046 ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
Andy Green43db0452013-01-10 19:50:35 +08002047 lwsl_err("ssl problem getting key '%s': %s\n",
Andy Green018d8eb2010-11-08 21:04:23 +00002048 ssl_private_key_filepath,
2049 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00002050 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002051 }
2052 /* verify private key */
Peter Hinz56885f32011-03-02 22:03:47 +00002053 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
Andy Green43db0452013-01-10 19:50:35 +08002054 lwsl_err("Private SSL key doesn't match cert\n");
Andy Greene92cd172011-01-19 13:11:55 +00002055 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002056 }
2057
2058 /* SSL is happy and has a cert it's content with */
2059 }
2060#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002061
Andy Greendf736162011-01-18 15:39:02 +00002062 /* selftest */
2063
2064 if (lws_b64_selftest())
Andy Greene92cd172011-01-19 13:11:55 +00002065 return NULL;
Andy Greendf736162011-01-18 15:39:02 +00002066
Andy Green0d338332011-02-12 11:57:43 +00002067 /* fd hashtable init */
2068
2069 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
Peter Hinz56885f32011-03-02 22:03:47 +00002070 context->fd_hashtable[n].length = 0;
Andy Green0d338332011-02-12 11:57:43 +00002071
Andy Greenb45993c2010-12-18 15:13:50 +00002072 /* set up our external listening socket we serve on */
Andy Green8f037e42010-12-19 22:13:26 +00002073
Andy Green4739e5c2011-01-22 12:51:57 +00002074 if (port) {
Andy Green8f037e42010-12-19 22:13:26 +00002075
Andy Green4739e5c2011-01-22 12:51:57 +00002076 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2077 if (sockfd < 0) {
Andy Greenf7609e92013-01-14 13:10:55 +08002078 lwsl_err("ERROR opening socket\n");
Andy Green4739e5c2011-01-22 12:51:57 +00002079 return NULL;
2080 }
Andy Green775c0dd2010-10-29 14:15:22 +01002081
Andy Green4739e5c2011-01-22 12:51:57 +00002082 /* allow us to restart even if old sockets in TIME_WAIT */
Andy Green6ee372f2012-04-09 15:09:01 +08002083 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2084 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +00002085
2086 /* Disable Nagle */
2087 opt = 1;
Andy Green6ee372f2012-04-09 15:09:01 +08002088 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2089 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +00002090
Andy Green4739e5c2011-01-22 12:51:57 +00002091 bzero((char *) &serv_addr, sizeof(serv_addr));
2092 serv_addr.sin_family = AF_INET;
Peter Hinz56885f32011-03-02 22:03:47 +00002093 if (interf == NULL)
Andy Green32375b72011-02-19 08:32:53 +00002094 serv_addr.sin_addr.s_addr = INADDR_ANY;
2095 else
Peter Hinz56885f32011-03-02 22:03:47 +00002096 interface_to_sa(interf, &serv_addr,
Andy Green32375b72011-02-19 08:32:53 +00002097 sizeof(serv_addr));
Andy Green4739e5c2011-01-22 12:51:57 +00002098 serv_addr.sin_port = htons(port);
2099
2100 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2101 sizeof(serv_addr));
2102 if (n < 0) {
Andy Green43db0452013-01-10 19:50:35 +08002103 lwsl_err("ERROR on binding to port %d (%d %d)\n",
Andy Green8f037e42010-12-19 22:13:26 +00002104 port, n, errno);
Andy Green41c58032013-01-12 13:21:08 +08002105 close(sockfd);
Andy Green4739e5c2011-01-22 12:51:57 +00002106 return NULL;
2107 }
Andy Green0d338332011-02-12 11:57:43 +00002108
Aaron Zinman4550f1d2013-01-10 12:35:18 +08002109 wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
Andy Green41c58032013-01-12 13:21:08 +08002110 if (wsi == NULL) {
2111 lwsl_err("Out of mem\n");
2112 close(sockfd);
2113 return NULL;
2114 }
Aaron Zinman4550f1d2013-01-10 12:35:18 +08002115 memset(wsi, 0, sizeof (struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00002116 wsi->sock = sockfd;
Andy Greend6e09112011-03-05 16:12:15 +00002117 wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00002118 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
Peter Hinz56885f32011-03-02 22:03:47 +00002119 insert_wsi(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00002120
Andy Green65b0e912013-01-16 07:59:47 +08002121 context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO;
2122 context->listen_service_count = 0;
2123 context->listen_service_fd = sockfd;
2124
Andy Greena824d182013-01-15 20:52:29 +08002125 listen(sockfd, LWS_SOMAXCONN);
Andy Green43db0452013-01-10 19:50:35 +08002126 lwsl_info(" Listening on port %d\n", port);
Andy Green0d338332011-02-12 11:57:43 +00002127
Andy Green65b0e912013-01-16 07:59:47 +08002128 /* list in the internal poll array - we're always first */
Andy Green6ee372f2012-04-09 15:09:01 +08002129
Peter Hinz56885f32011-03-02 22:03:47 +00002130 context->fds[context->fds_count].fd = sockfd;
2131 context->fds[context->fds_count++].events = POLLIN;
Andy Green3221f922011-02-12 13:14:11 +00002132
2133 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002134 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002135 LWS_CALLBACK_ADD_POLL_FD,
2136 (void *)(long)sockfd, NULL, POLLIN);
2137
Andy Green8f037e42010-12-19 22:13:26 +00002138 }
Andy Greenb45993c2010-12-18 15:13:50 +00002139
Andy Green6ee372f2012-04-09 15:09:01 +08002140 /*
2141 * drop any root privs for this process
2142 * to listen on port < 1023 we would have needed root, but now we are
2143 * listening, we don't want the power for anything else
2144 */
Peter Hinz56885f32011-03-02 22:03:47 +00002145#ifdef WIN32
2146#else
Andy Green3faa9c72010-11-08 17:03:03 +00002147 if (gid != -1)
2148 if (setgid(gid))
Andy Green43db0452013-01-10 19:50:35 +08002149 lwsl_warn("setgid: %s\n", strerror(errno));
Andy Green3faa9c72010-11-08 17:03:03 +00002150 if (uid != -1)
2151 if (setuid(uid))
Andy Green43db0452013-01-10 19:50:35 +08002152 lwsl_warn("setuid: %s\n", strerror(errno));
Peter Hinz56885f32011-03-02 22:03:47 +00002153#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002154
2155 /* set up our internal broadcast trigger sockets per-protocol */
2156
Peter Hinz56885f32011-03-02 22:03:47 +00002157 for (context->count_protocols = 0;
2158 protocols[context->count_protocols].callback;
2159 context->count_protocols++) {
Andy Green2d1301e2011-05-24 10:14:41 +01002160
Andy Green43db0452013-01-10 19:50:35 +08002161 lwsl_parser(" Protocol: %s\n",
2162 protocols[context->count_protocols].name);
Andy Green2d1301e2011-05-24 10:14:41 +01002163
Peter Hinz56885f32011-03-02 22:03:47 +00002164 protocols[context->count_protocols].owning_server = context;
2165 protocols[context->count_protocols].protocol_index =
2166 context->count_protocols;
Andy Greenb45993c2010-12-18 15:13:50 +00002167
2168 fd = socket(AF_INET, SOCK_STREAM, 0);
2169 if (fd < 0) {
Andy Greenf7609e92013-01-14 13:10:55 +08002170 lwsl_err("ERROR opening socket\n");
Andy Greene92cd172011-01-19 13:11:55 +00002171 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002172 }
Andy Green8f037e42010-12-19 22:13:26 +00002173
Andy Greenb45993c2010-12-18 15:13:50 +00002174 /* allow us to restart even if old sockets in TIME_WAIT */
Andy Green6ee372f2012-04-09 15:09:01 +08002175 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt,
2176 sizeof(opt));
Andy Greenb45993c2010-12-18 15:13:50 +00002177
2178 bzero((char *) &serv_addr, sizeof(serv_addr));
2179 serv_addr.sin_family = AF_INET;
2180 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2181 serv_addr.sin_port = 0; /* pick the port for us */
2182
2183 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2184 if (n < 0) {
Andy Green43db0452013-01-10 19:50:35 +08002185 lwsl_err("ERROR on binding to port %d (%d %d)\n",
Andy Greenb45993c2010-12-18 15:13:50 +00002186 port, n, errno);
Andy Greene92cd172011-01-19 13:11:55 +00002187 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002188 }
2189
2190 slen = sizeof cli_addr;
2191 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2192 if (n < 0) {
Andy Green43db0452013-01-10 19:50:35 +08002193 lwsl_err("getsockname failed\n");
Andy Greene92cd172011-01-19 13:11:55 +00002194 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002195 }
Peter Hinz56885f32011-03-02 22:03:47 +00002196 protocols[context->count_protocols].broadcast_socket_port =
Andy Greenb45993c2010-12-18 15:13:50 +00002197 ntohs(cli_addr.sin_port);
2198 listen(fd, 5);
2199
Andy Green43db0452013-01-10 19:50:35 +08002200 lwsl_debug(" Protocol %s broadcast socket %d\n",
Peter Hinz56885f32011-03-02 22:03:47 +00002201 protocols[context->count_protocols].name,
Andy Greenb45993c2010-12-18 15:13:50 +00002202 ntohs(cli_addr.sin_port));
2203
Andy Green0d338332011-02-12 11:57:43 +00002204 /* dummy wsi per broadcast proxy socket */
2205
Aaron Zinman4550f1d2013-01-10 12:35:18 +08002206 wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
Andy Green41c58032013-01-12 13:21:08 +08002207 if (wsi == NULL) {
2208 lwsl_err("Out of mem\n");
2209 close(fd);
2210 return NULL;
2211 }
Aaron Zinman4550f1d2013-01-10 12:35:18 +08002212 memset(wsi, 0, sizeof (struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00002213 wsi->sock = fd;
2214 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
Andy Greend6e09112011-03-05 16:12:15 +00002215 wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00002216 /* note which protocol we are proxying */
Peter Hinz56885f32011-03-02 22:03:47 +00002217 wsi->protocol_index_for_broadcast_proxy =
2218 context->count_protocols;
2219 insert_wsi(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00002220
2221 /* list in internal poll array */
2222
Peter Hinz56885f32011-03-02 22:03:47 +00002223 context->fds[context->fds_count].fd = fd;
2224 context->fds[context->fds_count].events = POLLIN;
2225 context->fds[context->fds_count].revents = 0;
2226 context->fds_count++;
Andy Green3221f922011-02-12 13:14:11 +00002227
2228 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002229 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002230 LWS_CALLBACK_ADD_POLL_FD,
2231 (void *)(long)fd, NULL, POLLIN);
Andy Greenb45993c2010-12-18 15:13:50 +00002232 }
2233
Andy Greena41314f2011-05-23 10:00:03 +01002234 /*
2235 * give all extensions a chance to create any per-context
2236 * allocations they need
2237 */
2238
2239 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2240 if (port)
2241 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
Andrew Chambersd5512172012-05-20 08:17:09 +08002242
2243 if (extensions) {
2244 while (extensions->callback) {
Andy Green43db0452013-01-10 19:50:35 +08002245 lwsl_ext(" Extension: %s\n", extensions->name);
Aaron Zinman4550f1d2013-01-10 12:35:18 +08002246 extensions->callback(context, extensions, NULL,
2247 (enum libwebsocket_extension_callback_reasons)m,
2248 NULL, NULL, 0);
Andrew Chambersd5512172012-05-20 08:17:09 +08002249 extensions++;
2250 }
Andy Greena41314f2011-05-23 10:00:03 +01002251 }
2252
Peter Hinz56885f32011-03-02 22:03:47 +00002253 return context;
Andy Greene92cd172011-01-19 13:11:55 +00002254}
Andy Greenb45993c2010-12-18 15:13:50 +00002255
Andy Green4739e5c2011-01-22 12:51:57 +00002256
Andy Greened11a022011-01-20 10:23:50 +00002257#ifndef LWS_NO_FORK
2258
Andy Greene92cd172011-01-19 13:11:55 +00002259/**
2260 * libwebsockets_fork_service_loop() - Optional helper function forks off
2261 * a process for the websocket server loop.
Andy Green6964bb52011-01-23 16:50:33 +00002262 * You don't have to use this but if not, you
2263 * have to make sure you are calling
2264 * libwebsocket_service periodically to service
2265 * the websocket traffic
Peter Hinz56885f32011-03-02 22:03:47 +00002266 * @context: server context returned by creation function
Andy Greene92cd172011-01-19 13:11:55 +00002267 */
Andy Greenb45993c2010-12-18 15:13:50 +00002268
Andy Greene92cd172011-01-19 13:11:55 +00002269int
Peter Hinz56885f32011-03-02 22:03:47 +00002270libwebsockets_fork_service_loop(struct libwebsocket_context *context)
Andy Greene92cd172011-01-19 13:11:55 +00002271{
Andy Greene92cd172011-01-19 13:11:55 +00002272 int fd;
2273 struct sockaddr_in cli_addr;
2274 int n;
Andy Green3221f922011-02-12 13:14:11 +00002275 int p;
Andy Greenb45993c2010-12-18 15:13:50 +00002276
Andy Greened11a022011-01-20 10:23:50 +00002277 n = fork();
2278 if (n < 0)
2279 return n;
2280
2281 if (!n) {
2282
2283 /* main process context */
2284
Andy Green3221f922011-02-12 13:14:11 +00002285 /*
2286 * set up the proxy sockets to allow broadcast from
2287 * service process context
2288 */
2289
Peter Hinz56885f32011-03-02 22:03:47 +00002290 for (p = 0; p < context->count_protocols; p++) {
Andy Greened11a022011-01-20 10:23:50 +00002291 fd = socket(AF_INET, SOCK_STREAM, 0);
2292 if (fd < 0) {
Andy Green43db0452013-01-10 19:50:35 +08002293 lwsl_err("Unable to create socket\n");
Andy Greened11a022011-01-20 10:23:50 +00002294 return -1;
2295 }
2296 cli_addr.sin_family = AF_INET;
2297 cli_addr.sin_port = htons(
Peter Hinz56885f32011-03-02 22:03:47 +00002298 context->protocols[p].broadcast_socket_port);
Andy Greened11a022011-01-20 10:23:50 +00002299 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2300 n = connect(fd, (struct sockaddr *)&cli_addr,
2301 sizeof cli_addr);
2302 if (n < 0) {
Andy Green43db0452013-01-10 19:50:35 +08002303 lwsl_err("Unable to connect to "
Andy Greened11a022011-01-20 10:23:50 +00002304 "broadcast socket %d, %s\n",
Andy Green3221f922011-02-12 13:14:11 +00002305 n, strerror(errno));
Andy Greened11a022011-01-20 10:23:50 +00002306 return -1;
2307 }
2308
Peter Hinz56885f32011-03-02 22:03:47 +00002309 context->protocols[p].broadcast_socket_user_fd = fd;
Andy Greened11a022011-01-20 10:23:50 +00002310 }
2311
Andy Greene92cd172011-01-19 13:11:55 +00002312 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00002313 }
2314
Artem Baguinski91531662011-12-14 22:14:03 +01002315#ifdef HAVE_SYS_PRCTL_H
Andy Greenb45993c2010-12-18 15:13:50 +00002316 /* we want a SIGHUP when our parent goes down */
2317 prctl(PR_SET_PDEATHSIG, SIGHUP);
Artem Baguinski91531662011-12-14 22:14:03 +01002318#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002319
2320 /* in this forked process, sit and service websocket connections */
Andy Green8f037e42010-12-19 22:13:26 +00002321
Artem Baguinski91531662011-12-14 22:14:03 +01002322 while (1) {
Peter Hinz56885f32011-03-02 22:03:47 +00002323 if (libwebsocket_service(context, 1000))
Andy Green3928f612012-07-20 12:58:38 +08002324 break;
Andy Green5e8967a2012-10-17 20:10:44 +08002325//#ifndef HAVE_SYS_PRCTL_H
Artem Baguinski91531662011-12-14 22:14:03 +01002326/*
2327 * on systems without prctl() (i.e. anything but linux) we can notice that our
2328 * parent is dead if getppid() returns 1. FIXME apparently this is not true for
2329 * solaris, could remember ppid right after fork and wait for it to change.
2330 */
2331
2332 if (getppid() == 1)
2333 break;
Andy Green5e8967a2012-10-17 20:10:44 +08002334//#endif
Artem Baguinski91531662011-12-14 22:14:03 +01002335 }
2336
Andy Green8f037e42010-12-19 22:13:26 +00002337
Andy Green3928f612012-07-20 12:58:38 +08002338 return 1;
Andy Greenff95d7a2010-10-28 22:36:01 +01002339}
2340
Andy Greened11a022011-01-20 10:23:50 +00002341#endif
2342
Andy Greenb45993c2010-12-18 15:13:50 +00002343/**
2344 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
Andy Green8f037e42010-12-19 22:13:26 +00002345 * connection.
Andy Greenb45993c2010-12-18 15:13:50 +00002346 * @wsi: pointer to struct websocket you want to know the protocol of
2347 *
Andy Green8f037e42010-12-19 22:13:26 +00002348 *
2349 * This is useful to get the protocol to broadcast back to from inside
Andy Greenb45993c2010-12-18 15:13:50 +00002350 * the callback.
2351 */
Andy Greenab990e42010-10-31 12:42:52 +00002352
Andy Greenb45993c2010-12-18 15:13:50 +00002353const struct libwebsocket_protocols *
2354libwebsockets_get_protocol(struct libwebsocket *wsi)
2355{
2356 return wsi->protocol;
2357}
2358
2359/**
Andy Greene92cd172011-01-19 13:11:55 +00002360 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
Andy Green8f037e42010-12-19 22:13:26 +00002361 * connections of the given protocol.
Andy Greenb45993c2010-12-18 15:13:50 +00002362 * @protocol: pointer to the protocol you will broadcast to all members of
2363 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
Andy Green8f037e42010-12-19 22:13:26 +00002364 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
2365 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
2366 * case you are calling this function from callback context.
Andy Greenb45993c2010-12-18 15:13:50 +00002367 * @len: length of payload data in buf, starting from buf.
Andy Green8f037e42010-12-19 22:13:26 +00002368 *
2369 * This function allows bulk sending of a packet to every connection using
Andy Greenb45993c2010-12-18 15:13:50 +00002370 * the given protocol. It does not send the data directly; instead it calls
2371 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
2372 * wants to actually send the data for that connection, the callback itself
2373 * should call libwebsocket_write().
2374 *
2375 * libwebsockets_broadcast() can be called from another fork context without
2376 * having to take any care about data visibility between the processes, it'll
2377 * "just work".
2378 */
2379
2380
2381int
Andy Green8f037e42010-12-19 22:13:26 +00002382libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
Andy Greenb45993c2010-12-18 15:13:50 +00002383 unsigned char *buf, size_t len)
2384{
Peter Hinz56885f32011-03-02 22:03:47 +00002385 struct libwebsocket_context *context = protocol->owning_server;
Andy Greenb45993c2010-12-18 15:13:50 +00002386 int n;
Andy Green0d338332011-02-12 11:57:43 +00002387 int m;
Andy Green6ee372f2012-04-09 15:09:01 +08002388 struct libwebsocket *wsi;
Andy Greenb45993c2010-12-18 15:13:50 +00002389
2390 if (!protocol->broadcast_socket_user_fd) {
2391 /*
Andy Greene92cd172011-01-19 13:11:55 +00002392 * We are either running unforked / flat, or we are being
2393 * called from poll thread context
Andy Greenb45993c2010-12-18 15:13:50 +00002394 * eg, from a callback. In that case don't use sockets for
2395 * broadcast IPC (since we can't open a socket connection to
2396 * a socket listening on our own thread) but directly do the
2397 * send action.
2398 *
2399 * Locking is not needed because we are by definition being
2400 * called in the poll thread context and are serialized.
2401 */
2402
Andy Green0d338332011-02-12 11:57:43 +00002403 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Greenb45993c2010-12-18 15:13:50 +00002404
Peter Hinz56885f32011-03-02 22:03:47 +00002405 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +00002406
Peter Hinz56885f32011-03-02 22:03:47 +00002407 wsi = context->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +00002408
Andy Green0d338332011-02-12 11:57:43 +00002409 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
2410 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00002411
Andy Green0d338332011-02-12 11:57:43 +00002412 /*
2413 * never broadcast to
2414 * non-established connections
2415 */
2416 if (wsi->state != WSI_STATE_ESTABLISHED)
2417 continue;
2418
2419 /* only broadcast to guys using
2420 * requested protocol
2421 */
2422 if (wsi->protocol != protocol)
2423 continue;
2424
Peter Hinz56885f32011-03-02 22:03:47 +00002425 wsi->protocol->callback(context, wsi,
Andy Green8f037e42010-12-19 22:13:26 +00002426 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +00002427 wsi->user_space,
Andy Greenb45993c2010-12-18 15:13:50 +00002428 buf, len);
Andy Green0d338332011-02-12 11:57:43 +00002429 }
Andy Greenb45993c2010-12-18 15:13:50 +00002430 }
2431
2432 return 0;
2433 }
2434
Andy Green0ca6a172010-12-19 20:50:01 +00002435 /*
2436 * We're being called from a different process context than the server
2437 * loop. Instead of broadcasting directly, we send our
2438 * payload on a socket to do the IPC; the server process will serialize
2439 * the broadcast action in its main poll() loop.
2440 *
2441 * There's one broadcast socket listening for each protocol supported
2442 * set up when the websocket server initializes
2443 */
2444
Andy Green6964bb52011-01-23 16:50:33 +00002445 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
Andy Greenb45993c2010-12-18 15:13:50 +00002446
2447 return n;
2448}
Andy Green82c3d542011-03-07 21:16:31 +00002449
2450int
2451libwebsocket_is_final_fragment(struct libwebsocket *wsi)
2452{
2453 return wsi->final;
2454}
Alex Bligh49146db2011-11-07 17:19:25 +08002455
David Galeanoe2cf9922013-01-09 18:06:55 +08002456unsigned char
2457libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
2458{
2459 return wsi->rsv;
2460}
2461
Alex Bligh49146db2011-11-07 17:19:25 +08002462void *
2463libwebsocket_ensure_user_space(struct libwebsocket *wsi)
2464{
2465 /* allocate the per-connection user memory (if any) */
2466
2467 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
2468 wsi->user_space = malloc(
2469 wsi->protocol->per_session_data_size);
2470 if (wsi->user_space == NULL) {
Andy Green43db0452013-01-10 19:50:35 +08002471 lwsl_err("Out of memory for conn user space\n");
Alex Bligh49146db2011-11-07 17:19:25 +08002472 return NULL;
2473 }
Andy Green6ee372f2012-04-09 15:09:01 +08002474 memset(wsi->user_space, 0,
2475 wsi->protocol->per_session_data_size);
Alex Bligh49146db2011-11-07 17:19:25 +08002476 }
2477 return wsi->user_space;
2478}
Andy Green43db0452013-01-10 19:50:35 +08002479
Andy Greende8f27a2013-01-12 09:17:42 +08002480
2481static void lwsl_emit_stderr(const char *line)
2482{
2483 fprintf(stderr, "%s", line);
2484}
2485
Andy Green43db0452013-01-10 19:50:35 +08002486void _lws_log(int filter, const char *format, ...)
2487{
Andy Greende8f27a2013-01-12 09:17:42 +08002488 char buf[256];
Andy Green43db0452013-01-10 19:50:35 +08002489 va_list ap;
2490 int n;
Andy Greende8f27a2013-01-12 09:17:42 +08002491 int pos = 0;
Andy Green8a265092013-01-12 09:25:07 +08002492 struct timeval tv;
Andy Green43db0452013-01-10 19:50:35 +08002493
2494 if (!(log_level & filter))
2495 return;
2496
Andy Green8a265092013-01-12 09:25:07 +08002497 gettimeofday(&tv, NULL);
2498
Andy Green43db0452013-01-10 19:50:35 +08002499 for (n = 0; n < LLL_COUNT; n++)
2500 if (filter == (1 << n)) {
Andy Green8a265092013-01-12 09:25:07 +08002501 pos = sprintf(buf, "[%ld:%04ld] %s: ", tv.tv_sec,
2502 tv.tv_usec / 100, log_level_names[n]);
Andy Green43db0452013-01-10 19:50:35 +08002503 break;
2504 }
2505
2506 va_start(ap, format);
Andy Greende8f27a2013-01-12 09:17:42 +08002507 vsnprintf(buf + pos, (sizeof buf) - pos, format, ap);
2508 buf[(sizeof buf) - 1] = '\0';
2509 va_end(ap);
2510
2511 lwsl_emit(buf);
Andy Green43db0452013-01-10 19:50:35 +08002512}
2513
2514/**
2515 * lws_set_log_level() - Set the logging bitfield
2516 * @level: OR together the LLL_ debug contexts you want output from
Andy Greende8f27a2013-01-12 09:17:42 +08002517 * @log_emit_function: NULL to leave it as it is, or a user-supplied
2518 * function to perform log string emission instead of
2519 * the default stderr one.
Andy Green43db0452013-01-10 19:50:35 +08002520 *
Andy Greende8f27a2013-01-12 09:17:42 +08002521 * log level defaults to "err" and "warn" contexts enabled only and
2522 * emission on stderr.
Andy Green43db0452013-01-10 19:50:35 +08002523 */
2524
Andy Greende8f27a2013-01-12 09:17:42 +08002525void lws_set_log_level(int level, void (*log_emit_function)(const char *line))
Andy Green43db0452013-01-10 19:50:35 +08002526{
2527 log_level = level;
Andy Greende8f27a2013-01-12 09:17:42 +08002528 if (log_emit_function)
2529 lwsl_emit = log_emit_function;
Andy Green43db0452013-01-10 19:50:35 +08002530}