blob: 6b2f2db143b307927270062d60eabacb05fd7747 [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 +000064int
Andy Greendfb23042013-01-17 12:26:48 +080065insert_wsi_socket_into_fds(struct libwebsocket_context *context, struct libwebsocket *wsi)
Andy Green0d338332011-02-12 11:57:43 +000066{
Andy Greendfb23042013-01-17 12:26:48 +080067 if (context->fds_count >= context->max_fds) {
68 lwsl_err("Reached limit of fds tracking (%d)\n", context->max_fds);
Andy Green0d338332011-02-12 11:57:43 +000069 return 1;
70 }
71
Andy Greendfb23042013-01-17 12:26:48 +080072 if (wsi->sock > context->max_fds) {
73 lwsl_err("Socket fd %d is beyond what we can index (%d)\n", wsi->sock, context->max_fds);
74 return 1;
75 }
76
77 assert(wsi);
78 assert(wsi->sock);
79
80 lwsl_info("insert_wsi_socket_into_fds: wsi=%p, sock=%d, fds pos=%d\n", wsi, wsi->sock, context->fds_count);
81
82 context->lws_lookup[wsi->sock] = wsi;
83 wsi->position_in_fds_table = context->fds_count;
84 context->fds[context->fds_count].fd = wsi->sock;
85 context->fds[context->fds_count].events = POLLIN;
86 context->fds[context->fds_count++].revents = 0;
87
88 /* external POLL support via protocol 0 */
89 context->protocols[0].callback(context, wsi,
90 LWS_CALLBACK_ADD_POLL_FD,
91 (void *)(long)wsi->sock, NULL, POLLIN);
Andy Green0d338332011-02-12 11:57:43 +000092
93 return 0;
94}
95
Andy Greendfb23042013-01-17 12:26:48 +080096static int
97remove_wsi_socket_from_fds(struct libwebsocket_context *context, struct libwebsocket *wsi)
Andy Green0d338332011-02-12 11:57:43 +000098{
Andy Greendfb23042013-01-17 12:26:48 +080099 int m;
Andy Green0d338332011-02-12 11:57:43 +0000100
Andy Greendfb23042013-01-17 12:26:48 +0800101 if (!--context->fds_count)
102 goto do_ext;
Andy Green0d338332011-02-12 11:57:43 +0000103
Andy Greendfb23042013-01-17 12:26:48 +0800104 if (wsi->sock > context->max_fds) {
105 lwsl_err("Socket fd %d is beyond what we can index (%d)\n", wsi->sock, context->max_fds);
106 return 1;
107 }
Andy Green0d338332011-02-12 11:57:43 +0000108
Andy Greendfb23042013-01-17 12:26:48 +0800109 lwsl_info("remove_wsi_socket_from_fds: wsi=%p, sock=%d, fds pos=%d\n", wsi, wsi->sock, wsi->position_in_fds_table);
110
111 m = wsi->position_in_fds_table; /* replace the contents for this */
112
113 /* have the last guy take up the vacant slot */
114 context->fds[m] = context->fds[context->fds_count]; /* vacant fds slot filled with end one */
115 /* end guy's fds_lookup entry remains unchanged (still same fd pointing to same wsi) */
116 /* end guy's "position in fds table" changed */
117 context->lws_lookup[context->fds[context->fds_count].fd]->position_in_fds_table = m;
118 /* deletion guy's lws_lookup entry needs nuking */
119 context->lws_lookup[wsi->sock] = NULL; /* no WSI for the socket of the wsi being removed*/
120 wsi->position_in_fds_table = -1; /* removed wsi has no position any more */
121
122do_ext:
123 /* remove also from external POLL support via protocol 0 */
124 if (wsi->sock)
125 context->protocols[0].callback(context, wsi,
126 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
127
128 return 0;
Andy Green0d338332011-02-12 11:57:43 +0000129}
130
Andy Green1f9bf522011-02-14 21:14:37 +0000131#ifdef LWS_OPENSSL_SUPPORT
132static void
133libwebsockets_decode_ssl_error(void)
134{
135 char buf[256];
136 u_long err;
137
138 while ((err = ERR_get_error()) != 0) {
139 ERR_error_string_n(err, buf, sizeof(buf));
Andy Green43db0452013-01-10 19:50:35 +0800140 lwsl_err("*** %s\n", buf);
Andy Green1f9bf522011-02-14 21:14:37 +0000141 }
142}
143#endif
Andy Green0d338332011-02-12 11:57:43 +0000144
Andy Green32375b72011-02-19 08:32:53 +0000145
146static int
Andy Green6ee372f2012-04-09 15:09:01 +0800147interface_to_sa(const char *ifname, struct sockaddr_in *addr, size_t addrlen)
Andy Green32375b72011-02-19 08:32:53 +0000148{
149 int rc = -1;
Peter Hinz56885f32011-03-02 22:03:47 +0000150#ifdef WIN32
Andy Green6ee372f2012-04-09 15:09:01 +0800151 /* TODO */
Peter Hinz56885f32011-03-02 22:03:47 +0000152#else
Andy Green32375b72011-02-19 08:32:53 +0000153 struct ifaddrs *ifr;
154 struct ifaddrs *ifc;
155 struct sockaddr_in *sin;
156
157 getifaddrs(&ifr);
158 for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
159 if (strcmp(ifc->ifa_name, ifname))
160 continue;
161 if (ifc->ifa_addr == NULL)
162 continue;
163 sin = (struct sockaddr_in *)ifc->ifa_addr;
164 if (sin->sin_family != AF_INET)
165 continue;
166 memcpy(addr, sin, addrlen);
Andy Green6ee372f2012-04-09 15:09:01 +0800167 rc = 0;
Andy Green32375b72011-02-19 08:32:53 +0000168 }
169
170 freeifaddrs(ifr);
Peter Hinz56885f32011-03-02 22:03:47 +0000171#endif
Andy Green32375b72011-02-19 08:32:53 +0000172 return rc;
173}
174
Andy Green8f037e42010-12-19 22:13:26 +0000175void
Peter Hinz56885f32011-03-02 22:03:47 +0000176libwebsocket_close_and_free_session(struct libwebsocket_context *context,
Andy Green687b0182011-02-26 11:04:01 +0000177 struct libwebsocket *wsi, enum lws_close_status reason)
Andy Green251f6fa2010-11-03 11:13:06 +0000178{
Andy Greenb45993c2010-12-18 15:13:50 +0000179 int n;
Andy Green62c54d22011-02-14 09:14:25 +0000180 int old_state;
Andy Green5e1fa172011-02-10 09:07:05 +0000181 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
182 LWS_SEND_BUFFER_POST_PADDING];
Andy Greenc44159f2011-03-07 07:08:18 +0000183 int ret;
184 int m;
185 struct lws_tokens eff_buf;
Andy Greena41314f2011-05-23 10:00:03 +0100186 struct libwebsocket_extension *ext;
Andy Greenb45993c2010-12-18 15:13:50 +0000187
Andy Green4b6fbe12011-02-14 08:03:48 +0000188 if (!wsi)
Andy Greenb45993c2010-12-18 15:13:50 +0000189 return;
190
Andy Green62c54d22011-02-14 09:14:25 +0000191 old_state = wsi->state;
Andy Green251f6fa2010-11-03 11:13:06 +0000192
Andy Green62c54d22011-02-14 09:14:25 +0000193 if (old_state == WSI_STATE_DEAD_SOCKET)
Andy Green5e1fa172011-02-10 09:07:05 +0000194 return;
195
Andy Greenda527df2011-03-07 07:08:12 +0000196 wsi->close_reason = reason;
197
198 /*
Andy Green68b45042011-05-25 21:41:57 +0100199 * are his extensions okay with him closing? Eg he might be a mux
200 * parent and just his ch1 aspect is closing?
201 */
202
203
204 for (n = 0; n < wsi->count_active_extensions; n++) {
205 if (!wsi->active_extensions[n]->callback)
206 continue;
207
208 m = wsi->active_extensions[n]->callback(context,
209 wsi->active_extensions[n], wsi,
210 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
211 wsi->active_extensions_user[n], NULL, 0);
212
213 /*
214 * if somebody vetoed actually closing him at this time....
215 * up to the extension to track the attempted close, let's
216 * just bail
217 */
218
219 if (m) {
Andy Green43db0452013-01-10 19:50:35 +0800220 lwsl_ext("extension vetoed close\n");
Andy Green68b45042011-05-25 21:41:57 +0100221 return;
222 }
223 }
224
225
226
227 /*
Andy Greenc44159f2011-03-07 07:08:18 +0000228 * flush any tx pending from extensions, since we may send close packet
229 * if there are problems with send, just nuke the connection
230 */
231
232 ret = 1;
233 while (ret == 1) {
234
235 /* default to nobody has more to spill */
236
237 ret = 0;
238 eff_buf.token = NULL;
239 eff_buf.token_len = 0;
240
241 /* show every extension the new incoming data */
242
243 for (n = 0; n < wsi->count_active_extensions; n++) {
244 m = wsi->active_extensions[n]->callback(
Andy Green46c2ea02011-03-22 09:04:01 +0000245 wsi->protocol->owning_server,
246 wsi->active_extensions[n], wsi,
Andy Greenc44159f2011-03-07 07:08:18 +0000247 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
248 wsi->active_extensions_user[n], &eff_buf, 0);
249 if (m < 0) {
Andy Green43db0452013-01-10 19:50:35 +0800250 lwsl_ext("Extension reports fatal error\n");
Andy Greenc44159f2011-03-07 07:08:18 +0000251 goto just_kill_connection;
252 }
253 if (m)
254 /*
255 * at least one extension told us he has more
256 * to spill, so we will go around again after
257 */
258 ret = 1;
259 }
260
261 /* assuming they left us something to send, send it */
262
263 if (eff_buf.token_len)
264 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
265 eff_buf.token_len))
266 goto just_kill_connection;
267 }
268
269 /*
Andy Greenda527df2011-03-07 07:08:12 +0000270 * signal we are closing, libsocket_write will
271 * add any necessary version-specific stuff. If the write fails,
272 * no worries we are closing anyway. If we didn't initiate this
273 * close, then our state has been changed to
274 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
275 *
276 * Likewise if it's a second call to close this connection after we
277 * sent the close indication to the peer already, we are in state
278 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
279 */
280
281 if (old_state == WSI_STATE_ESTABLISHED &&
282 reason != LWS_CLOSE_STATUS_NOSTATUS) {
Andy Green66a16f32011-05-24 22:07:45 +0100283
Andy Green43db0452013-01-10 19:50:35 +0800284 lwsl_debug("sending close indication...\n");
Andy Green66a16f32011-05-24 22:07:45 +0100285
Andy Greenda527df2011-03-07 07:08:12 +0000286 n = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
287 0, LWS_WRITE_CLOSE);
288 if (!n) {
289 /*
290 * we have sent a nice protocol level indication we
291 * now wish to close, we should not send anything more
292 */
293
294 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
295
296 /* and we should wait for a reply for a bit */
297
298 libwebsocket_set_timeout(wsi,
David Galeanoc9f1ff82013-01-09 18:01:23 +0800299 PENDING_TIMEOUT_CLOSE_ACK, AWAITING_TIMEOUT);
Andy Greenda527df2011-03-07 07:08:12 +0000300
Andy Green43db0452013-01-10 19:50:35 +0800301 lwsl_debug("sent close indication, awaiting ack\n");
Andy Greenda527df2011-03-07 07:08:12 +0000302
303 return;
304 }
305
306 /* else, the send failed and we should just hang up */
307 }
308
Andy Greenc44159f2011-03-07 07:08:18 +0000309just_kill_connection:
Andy Green66a16f32011-05-24 22:07:45 +0100310
Andy Green43db0452013-01-10 19:50:35 +0800311 lwsl_debug("libwebsocket_close_and_free_session: just_kill_connection\n");
Andy Green66a16f32011-05-24 22:07:45 +0100312
Andy Greenda527df2011-03-07 07:08:12 +0000313 /*
314 * we won't be servicing or receiving anything further from this guy
Andy Greendfb23042013-01-17 12:26:48 +0800315 * delete socket from the internal poll list if still present
Andy Greenda527df2011-03-07 07:08:12 +0000316 */
Andy Green4b6fbe12011-02-14 08:03:48 +0000317
Andy Greendfb23042013-01-17 12:26:48 +0800318 remove_wsi_socket_from_fds(context, wsi);
Andy Green4b6fbe12011-02-14 08:03:48 +0000319
Andy Green251f6fa2010-11-03 11:13:06 +0000320 wsi->state = WSI_STATE_DEAD_SOCKET;
321
Andy Green4b6fbe12011-02-14 08:03:48 +0000322 /* tell the user it's all over for this guy */
323
Andy Greend4302732011-02-28 07:45:29 +0000324 if (wsi->protocol && wsi->protocol->callback &&
Andy Green6ee372f2012-04-09 15:09:01 +0800325 ((old_state == WSI_STATE_ESTABLISHED) ||
326 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
327 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
Andy Green43db0452013-01-10 19:50:35 +0800328 lwsl_debug("calling back CLOSED\n");
Peter Hinz56885f32011-03-02 22:03:47 +0000329 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
Andy Greene77ddd82010-11-13 10:03:47 +0000330 wsi->user_space, NULL, 0);
Andy Greencc012472011-11-07 19:53:23 +0800331 } else
Andy Green43db0452013-01-10 19:50:35 +0800332 lwsl_debug("not calling back closed, old_state=%d\n", old_state);
Andy Green251f6fa2010-11-03 11:13:06 +0000333
Andy Greenef660a92011-03-06 10:29:38 +0000334 /* deallocate any active extension contexts */
335
336 for (n = 0; n < wsi->count_active_extensions; n++) {
337 if (!wsi->active_extensions[n]->callback)
338 continue;
339
Andy Green46c2ea02011-03-22 09:04:01 +0000340 wsi->active_extensions[n]->callback(context,
341 wsi->active_extensions[n], wsi,
342 LWS_EXT_CALLBACK_DESTROY,
343 wsi->active_extensions_user[n], NULL, 0);
Andy Greenef660a92011-03-06 10:29:38 +0000344
345 free(wsi->active_extensions_user[n]);
346 }
347
Andy Greena41314f2011-05-23 10:00:03 +0100348 /*
349 * inform all extensions in case they tracked this guy out of band
350 * even though not active on him specifically
351 */
352
353 ext = context->extensions;
354 while (ext && ext->callback) {
355 ext->callback(context, ext, wsi,
356 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
357 NULL, NULL, 0);
358 ext++;
359 }
360
Andy Greenef660a92011-03-06 10:29:38 +0000361 /* free up his parsing allocations */
Andy Green4b6fbe12011-02-14 08:03:48 +0000362
Andy Green251f6fa2010-11-03 11:13:06 +0000363 for (n = 0; n < WSI_TOKEN_COUNT; n++)
364 if (wsi->utf8_token[n].token)
365 free(wsi->utf8_token[n].token);
366
Andy Greena41314f2011-05-23 10:00:03 +0100367 if (wsi->c_address)
368 free(wsi->c_address);
369
Andy Green43db0452013-01-10 19:50:35 +0800370/* lwsl_info("closing fd=%d\n", wsi->sock); */
Andy Green251f6fa2010-11-03 11:13:06 +0000371
Andy Green3faa9c72010-11-08 17:03:03 +0000372#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +0000373 if (wsi->ssl) {
Andy Green3faa9c72010-11-08 17:03:03 +0000374 n = SSL_get_fd(wsi->ssl);
375 SSL_shutdown(wsi->ssl);
Andy Green3fc2c652013-01-14 15:35:02 +0800376 compatible_close(n);
Andy Green3faa9c72010-11-08 17:03:03 +0000377 SSL_free(wsi->ssl);
378 } else {
379#endif
380 shutdown(wsi->sock, SHUT_RDWR);
Andy Green3fc2c652013-01-14 15:35:02 +0800381
Andy Green66a16f32011-05-24 22:07:45 +0100382 if (wsi->sock)
Andy Green3fc2c652013-01-14 15:35:02 +0800383 compatible_close(wsi->sock);
Andy Green3faa9c72010-11-08 17:03:03 +0000384#ifdef LWS_OPENSSL_SUPPORT
385 }
386#endif
David Brooks2c60d952012-04-20 12:19:01 +0800387 if (wsi->protocol && wsi->protocol->per_session_data_size && wsi->user_space) /* user code may own */
Andy Green4f3943a2010-11-12 10:44:16 +0000388 free(wsi->user_space);
389
Andy Green251f6fa2010-11-03 11:13:06 +0000390 free(wsi);
391}
392
Andy Green07034092011-02-13 08:37:12 +0000393/**
Andy Greenf7ee5492011-02-13 09:04:21 +0000394 * libwebsockets_hangup_on_client() - Server calls to terminate client
Andy Green6ee372f2012-04-09 15:09:01 +0800395 * connection
Peter Hinz56885f32011-03-02 22:03:47 +0000396 * @context: libwebsockets context
Andy Greenf7ee5492011-02-13 09:04:21 +0000397 * @fd: Connection socket descriptor
398 */
399
400void
Peter Hinz56885f32011-03-02 22:03:47 +0000401libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
Andy Greenf7ee5492011-02-13 09:04:21 +0000402{
Andy Greendfb23042013-01-17 12:26:48 +0800403 struct libwebsocket *wsi = context->lws_lookup[fd];
Andy Greenf7ee5492011-02-13 09:04:21 +0000404
Andy Greendfb23042013-01-17 12:26:48 +0800405 if (wsi) {
406 libwebsocket_close_and_free_session(context,
407 wsi, LWS_CLOSE_STATUS_NOSTATUS);
408 } else
409 close(fd);
Andy Greenf7ee5492011-02-13 09:04:21 +0000410}
411
412
413/**
Andy Green07034092011-02-13 08:37:12 +0000414 * libwebsockets_get_peer_addresses() - Get client address information
415 * @fd: Connection socket descriptor
416 * @name: Buffer to take client address name
417 * @name_len: Length of client address name buffer
418 * @rip: Buffer to take client address IP qotted quad
419 * @rip_len: Length of client address IP buffer
420 *
421 * This function fills in @name and @rip with the name and IP of
Andy Green6ee372f2012-04-09 15:09:01 +0800422 * the client connected with socket descriptor @fd. Names may be
423 * truncated if there is not enough room. If either cannot be
424 * determined, they will be returned as valid zero-length strings.
Andy Green07034092011-02-13 08:37:12 +0000425 */
426
427void
428libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
429 char *rip, int rip_len)
430{
431 unsigned int len;
432 struct sockaddr_in sin;
433 struct hostent *host;
434 struct hostent *host1;
435 char ip[128];
Andy Greenf92def72011-03-09 15:02:20 +0000436 unsigned char *p;
Andy Green07034092011-02-13 08:37:12 +0000437 int n;
David Galeanocb193682013-01-09 15:29:00 +0800438#ifdef AF_LOCAL
439 struct sockaddr_un *un;
440#endif
Andy Green07034092011-02-13 08:37:12 +0000441
442 rip[0] = '\0';
443 name[0] = '\0';
444
445 len = sizeof sin;
446 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
447 perror("getpeername");
448 return;
449 }
Andy Green6ee372f2012-04-09 15:09:01 +0800450
Andy Green07034092011-02-13 08:37:12 +0000451 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
452 AF_INET);
453 if (host == NULL) {
454 perror("gethostbyaddr");
455 return;
456 }
457
458 strncpy(name, host->h_name, name_len);
459 name[name_len - 1] = '\0';
460
461 host1 = gethostbyname(host->h_name);
462 if (host1 == NULL)
463 return;
Andy Greenf92def72011-03-09 15:02:20 +0000464 p = (unsigned char *)host1;
Andy Green07034092011-02-13 08:37:12 +0000465 n = 0;
466 while (p != NULL) {
Andy Greenf92def72011-03-09 15:02:20 +0000467 p = (unsigned char *)host1->h_addr_list[n++];
Andy Green07034092011-02-13 08:37:12 +0000468 if (p == NULL)
469 continue;
Peter Hinzbb45a902011-03-10 18:14:01 +0000470 if ((host1->h_addrtype != AF_INET)
471#ifdef AF_LOCAL
472 && (host1->h_addrtype != AF_LOCAL)
473#endif
474 )
Andy Green07034092011-02-13 08:37:12 +0000475 continue;
476
Andy Green7627af52011-03-09 15:13:52 +0000477 if (host1->h_addrtype == AF_INET)
478 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
Peter Hinzbb45a902011-03-10 18:14:01 +0000479#ifdef AF_LOCAL
Andy Green7627af52011-03-09 15:13:52 +0000480 else {
481 un = (struct sockaddr_un *)p;
Andy Green6ee372f2012-04-09 15:09:01 +0800482 strncpy(ip, un->sun_path, sizeof(ip) - 1);
Andy Green7627af52011-03-09 15:13:52 +0000483 ip[sizeof(ip) - 1] = '\0';
484 }
Peter Hinzbb45a902011-03-10 18:14:01 +0000485#endif
Andy Green07034092011-02-13 08:37:12 +0000486 p = NULL;
487 strncpy(rip, ip, rip_len);
488 rip[rip_len - 1] = '\0';
489 }
490}
Andy Green9f990342011-02-12 11:57:45 +0000491
Peter Hinz56885f32011-03-02 22:03:47 +0000492int libwebsockets_get_random(struct libwebsocket_context *context,
493 void *buf, int len)
494{
495 int n;
Aaron Zinman4550f1d2013-01-10 12:35:18 +0800496 char *p = (char *)buf;
Peter Hinz56885f32011-03-02 22:03:47 +0000497
498#ifdef WIN32
499 for (n = 0; n < len; n++)
500 p[n] = (unsigned char)rand();
501#else
502 n = read(context->fd_random, p, len);
503#endif
504
505 return n;
506}
507
Andy Green2836c642011-03-07 20:47:41 +0000508unsigned char *
509libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md)
510{
511 return SHA1(d, n, md);
512}
513
Andy Green95a7b5d2011-03-06 10:29:39 +0000514int lws_send_pipe_choked(struct libwebsocket *wsi)
515{
516 struct pollfd fds;
517
518 fds.fd = wsi->sock;
519 fds.events = POLLOUT;
520 fds.revents = 0;
521
522 if (poll(&fds, 1, 0) != 1)
523 return 1;
524
525 if ((fds.revents & POLLOUT) == 0)
526 return 1;
527
528 /* okay to send another packet without blocking */
529
530 return 0;
531}
532
Andy Greena41314f2011-05-23 10:00:03 +0100533int
Andy Green3b84c002011-03-06 13:14:42 +0000534lws_handle_POLLOUT_event(struct libwebsocket_context *context,
535 struct libwebsocket *wsi, struct pollfd *pollfd)
536{
537 struct lws_tokens eff_buf;
538 int n;
539 int ret;
540 int m;
Andy Greena41314f2011-05-23 10:00:03 +0100541 int handled = 0;
Andy Green3b84c002011-03-06 13:14:42 +0000542
Andy Greena41314f2011-05-23 10:00:03 +0100543 for (n = 0; n < wsi->count_active_extensions; n++) {
544 if (!wsi->active_extensions[n]->callback)
545 continue;
546
547 m = wsi->active_extensions[n]->callback(context,
548 wsi->active_extensions[n], wsi,
549 LWS_EXT_CALLBACK_IS_WRITEABLE,
550 wsi->active_extensions_user[n], NULL, 0);
551 if (m > handled)
552 handled = m;
553 }
554
555 if (handled == 1)
556 goto notify_action;
557
558 if (!wsi->extension_data_pending || handled == 2)
Andy Green3b84c002011-03-06 13:14:42 +0000559 goto user_service;
560
561 /*
562 * check in on the active extensions, see if they
563 * had pending stuff to spill... they need to get the
564 * first look-in otherwise sequence will be disordered
565 *
566 * NULL, zero-length eff_buf means just spill pending
567 */
568
569 ret = 1;
570 while (ret == 1) {
571
572 /* default to nobody has more to spill */
573
574 ret = 0;
575 eff_buf.token = NULL;
576 eff_buf.token_len = 0;
577
578 /* give every extension a chance to spill */
579
580 for (n = 0; n < wsi->count_active_extensions; n++) {
581 m = wsi->active_extensions[n]->callback(
Andy Green46c2ea02011-03-22 09:04:01 +0000582 wsi->protocol->owning_server,
583 wsi->active_extensions[n], wsi,
Andy Green3b84c002011-03-06 13:14:42 +0000584 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
585 wsi->active_extensions_user[n], &eff_buf, 0);
586 if (m < 0) {
Andy Green43db0452013-01-10 19:50:35 +0800587 lwsl_err("ext reports fatal error\n");
Andy Green3b84c002011-03-06 13:14:42 +0000588 return -1;
589 }
590 if (m)
591 /*
592 * at least one extension told us he has more
593 * to spill, so we will go around again after
594 */
595 ret = 1;
596 }
597
598 /* assuming they gave us something to send, send it */
599
600 if (eff_buf.token_len) {
601 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
602 eff_buf.token_len))
603 return -1;
604 } else
605 continue;
606
607 /* no extension has more to spill */
608
609 if (!ret)
610 continue;
611
612 /*
613 * There's more to spill from an extension, but we just sent
614 * something... did that leave the pipe choked?
615 */
616
617 if (!lws_send_pipe_choked(wsi))
618 /* no we could add more */
619 continue;
620
Andy Green43db0452013-01-10 19:50:35 +0800621 lwsl_info("choked in POLLOUT service\n");
Andy Green3b84c002011-03-06 13:14:42 +0000622
623 /*
624 * Yes, he's choked. Leave the POLLOUT masked on so we will
625 * come back here when he is unchoked. Don't call the user
626 * callback to enforce ordering of spilling, he'll get called
627 * when we come back here and there's nothing more to spill.
628 */
629
630 return 0;
631 }
632
633 wsi->extension_data_pending = 0;
634
635user_service:
636 /* one shot */
637
Andy Greena41314f2011-05-23 10:00:03 +0100638 if (pollfd) {
639 pollfd->events &= ~POLLOUT;
Andy Green3b84c002011-03-06 13:14:42 +0000640
Andy Greena41314f2011-05-23 10:00:03 +0100641 /* external POLL support via protocol 0 */
642 context->protocols[0].callback(context, wsi,
643 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
644 (void *)(long)wsi->sock, NULL, POLLOUT);
645 }
646
647notify_action:
Andy Green3b84c002011-03-06 13:14:42 +0000648
Andy Green9e4c2b62011-03-07 20:47:39 +0000649 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
650 n = LWS_CALLBACK_CLIENT_WRITEABLE;
651 else
652 n = LWS_CALLBACK_SERVER_WRITEABLE;
653
Aaron Zinman4550f1d2013-01-10 12:35:18 +0800654 wsi->protocol->callback(context, wsi, (enum libwebsocket_callback_reasons) n, wsi->user_space, NULL, 0);
Andy Green3b84c002011-03-06 13:14:42 +0000655
656 return 0;
657}
658
659
660
Andy Greena41314f2011-05-23 10:00:03 +0100661void
662libwebsocket_service_timeout_check(struct libwebsocket_context *context,
663 struct libwebsocket *wsi, unsigned int sec)
664{
665 int n;
666
667 /*
668 * if extensions want in on it (eg, we are a mux parent)
669 * give them a chance to service child timeouts
670 */
671
672 for (n = 0; n < wsi->count_active_extensions; n++)
673 wsi->active_extensions[n]->callback(
674 context, wsi->active_extensions[n],
675 wsi, LWS_EXT_CALLBACK_1HZ,
676 wsi->active_extensions_user[n], NULL, sec);
677
678 if (!wsi->pending_timeout)
679 return;
Andy Green6ee372f2012-04-09 15:09:01 +0800680
Andy Greena41314f2011-05-23 10:00:03 +0100681 /*
682 * if we went beyond the allowed time, kill the
683 * connection
684 */
685
686 if (sec > wsi->pending_timeout_limit) {
Andy Green43db0452013-01-10 19:50:35 +0800687 lwsl_info("TIMEDOUT WAITING\n");
Andy Greena41314f2011-05-23 10:00:03 +0100688 libwebsocket_close_and_free_session(context,
689 wsi, LWS_CLOSE_STATUS_NOSTATUS);
690 }
691}
692
693struct libwebsocket *
694libwebsocket_create_new_server_wsi(struct libwebsocket_context *context)
695{
696 struct libwebsocket *new_wsi;
697 int n;
698
Aaron Zinman4550f1d2013-01-10 12:35:18 +0800699 new_wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
Andy Greena41314f2011-05-23 10:00:03 +0100700 if (new_wsi == NULL) {
Andy Green43db0452013-01-10 19:50:35 +0800701 lwsl_err("Out of memory for new connection\n");
Andy Greena41314f2011-05-23 10:00:03 +0100702 return NULL;
703 }
704
Andy Green6ee372f2012-04-09 15:09:01 +0800705 memset(new_wsi, 0, sizeof(struct libwebsocket));
Andy Greena41314f2011-05-23 10:00:03 +0100706 new_wsi->count_active_extensions = 0;
707 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
708
709 /* intialize the instance struct */
710
711 new_wsi->state = WSI_STATE_HTTP;
712 new_wsi->name_buffer_pos = 0;
Andy Greend280b6e2013-01-15 13:40:23 +0800713 new_wsi->mode = LWS_CONNMODE_HTTP_SERVING;
Andy Greena41314f2011-05-23 10:00:03 +0100714
715 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
716 new_wsi->utf8_token[n].token = NULL;
717 new_wsi->utf8_token[n].token_len = 0;
718 }
719
720 /*
721 * these can only be set once the protocol is known
722 * we set an unestablished connection's protocol pointer
723 * to the start of the supported list, so it can look
724 * for matching ones during the handshake
725 */
726 new_wsi->protocol = context->protocols;
727 new_wsi->user_space = NULL;
728
729 /*
730 * Default protocol is 76 / 00
731 * After 76, there's a header specified to inform which
732 * draft the client wants, when that's seen we modify
733 * the individual connection's spec revision accordingly
734 */
735 new_wsi->ietf_spec_revision = 0;
736
737 return new_wsi;
738}
739
Andy Greena41314f2011-05-23 10:00:03 +0100740
Andy Green9f990342011-02-12 11:57:45 +0000741/**
742 * libwebsocket_service_fd() - Service polled socket with something waiting
Peter Hinz56885f32011-03-02 22:03:47 +0000743 * @context: Websocket context
Andy Green9f990342011-02-12 11:57:45 +0000744 * @pollfd: The pollfd entry describing the socket fd and which events
Andy Green6ee372f2012-04-09 15:09:01 +0800745 * happened.
Andy Green9f990342011-02-12 11:57:45 +0000746 *
747 * This function closes any active connections and then frees the
748 * context. After calling this, any further use of the context is
749 * undefined.
750 */
751
752int
Peter Hinz56885f32011-03-02 22:03:47 +0000753libwebsocket_service_fd(struct libwebsocket_context *context,
Andy Green0d338332011-02-12 11:57:43 +0000754 struct pollfd *pollfd)
Andy Greenb45993c2010-12-18 15:13:50 +0000755{
Andy Green6ee372f2012-04-09 15:09:01 +0800756 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
757 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
Andy Greena71eafc2011-02-14 17:59:43 +0000758 struct libwebsocket *wsi;
Andy Green0d338332011-02-12 11:57:43 +0000759 struct libwebsocket *new_wsi;
Andy Greenb45993c2010-12-18 15:13:50 +0000760 int n;
Andy Green0d338332011-02-12 11:57:43 +0000761 int m;
Tobias Maiere8c9b562012-04-05 11:57:12 +0200762 ssize_t len;
Andy Green0d338332011-02-12 11:57:43 +0000763 int accept_fd;
764 unsigned int clilen;
765 struct sockaddr_in cli_addr;
Andy Greena71eafc2011-02-14 17:59:43 +0000766 struct timeval tv;
Andy Green2366b1c2011-03-06 13:15:31 +0000767 int more = 1;
Andy Green98a717c2011-03-06 13:14:15 +0000768 struct lws_tokens eff_buf;
Andy Green6c939552011-03-08 08:56:57 +0000769 int opt = 1;
Andy Green03674a62013-01-16 11:47:40 +0800770#ifndef LWS_NO_CLIENT
Andy Green76f61e72013-01-16 11:53:05 +0800771 extern int lws_client_socket_service(struct libwebsocket_context *context, struct libwebsocket *wsi, struct pollfd *pollfd);
Andy Green03674a62013-01-16 11:47:40 +0800772#endif
Andy Greena71eafc2011-02-14 17:59:43 +0000773 /*
774 * you can call us with pollfd = NULL to just allow the once-per-second
775 * global timeout checks; if less than a second since the last check
776 * it returns immediately then.
777 */
778
779 gettimeofday(&tv, NULL);
780
Peter Hinz56885f32011-03-02 22:03:47 +0000781 if (context->last_timeout_check_s != tv.tv_sec) {
782 context->last_timeout_check_s = tv.tv_sec;
Andy Greena71eafc2011-02-14 17:59:43 +0000783
784 /* global timeout check once per second */
785
Peter Hinz56885f32011-03-02 22:03:47 +0000786 for (n = 0; n < context->fds_count; n++) {
Andy Greendfb23042013-01-17 12:26:48 +0800787 struct libwebsocket *new_wsi = context->lws_lookup[context->fds[n].fd];
788 if (!new_wsi)
789 continue;
790 libwebsocket_service_timeout_check(context,
791 new_wsi, tv.tv_sec);
Andy Greena71eafc2011-02-14 17:59:43 +0000792 }
793 }
794
795 /* just here for timeout management? */
796
797 if (pollfd == NULL)
798 return 0;
799
800 /* no, here to service a socket descriptor */
801
Andy Green65b0e912013-01-16 07:59:47 +0800802 /*
803 * deal with listen service piggybacking
804 * every listen_service_modulo services of other fds, we
805 * sneak one in to service the listen socket if there's anything waiting
806 *
807 * To handle connection storms, as found in ab, if we previously saw a
808 * pending connection here, it causes us to check again next time.
809 */
810
811 if (context->listen_service_fd && pollfd->fd != context->listen_service_fd) {
812 context->listen_service_count++;
813 if (context->listen_service_extraseen ||
814 context->listen_service_count == context->listen_service_modulo) {
815 context->listen_service_count = 0;
816 m = 1;
817 if (context->listen_service_extraseen > 5)
818 m = 2;
819 while (m--) {
820 /* even with extpoll, we prepared this internal fds for listen */
821 n = poll(&context->fds[0], 1, 0);
822 if (n > 0) { /* there's a connection waiting for us */
823 libwebsocket_service_fd(context, &context->fds[0]);
824 context->listen_service_extraseen++;
825 } else {
826 if (context->listen_service_extraseen)
827 context->listen_service_extraseen--;
828 break;
829 }
830 }
831 }
832
833 }
834
835 /* okay, what we came here to do... */
836
Andy Greendfb23042013-01-17 12:26:48 +0800837 wsi = context->lws_lookup[pollfd->fd];
Andy Greend280b6e2013-01-15 13:40:23 +0800838 if (wsi == NULL) {
Andy Greendfb23042013-01-17 12:26:48 +0800839 if (pollfd->fd > 11)
840 lwsl_err("unexpected NULL wsi fd=%d fds_count=%d\n", pollfd->fd, context->fds_count);
Andy Greenfa3f4052012-10-07 20:40:35 +0800841 return 0;
Andy Greend280b6e2013-01-15 13:40:23 +0800842 }
Andy Green8f037e42010-12-19 22:13:26 +0000843
Andy Green0d338332011-02-12 11:57:43 +0000844 switch (wsi->mode) {
Andy Greend280b6e2013-01-15 13:40:23 +0800845
846 case LWS_CONNMODE_HTTP_SERVING:
847
848 /* handle http headers coming in */
849
850 /* any incoming data ready? */
851
852 if (pollfd->revents & POLLIN) {
853
854 #ifdef LWS_OPENSSL_SUPPORT
855 if (wsi->ssl)
856 len = SSL_read(wsi->ssl, buf, sizeof buf);
857 else
858 #endif
859 len = recv(pollfd->fd, buf, sizeof buf, 0);
860
861 if (len < 0) {
862 lwsl_debug("Socket read returned %d\n", len);
863 if (errno != EINTR && errno != EAGAIN)
864 libwebsocket_close_and_free_session(context,
865 wsi, LWS_CLOSE_STATUS_NOSTATUS);
Andy Green040d2ef2013-01-16 13:40:43 +0800866 return 0;
Andy Greend280b6e2013-01-15 13:40:23 +0800867 }
868 if (!len) {
869 libwebsocket_close_and_free_session(context, wsi,
870 LWS_CLOSE_STATUS_NOSTATUS);
871 return 0;
872 }
873
874 n = libwebsocket_read(context, wsi, buf, len);
875 if (n < 0)
876 /* we closed wsi */
Andy Green040d2ef2013-01-16 13:40:43 +0800877 return 0;
Andy Greend280b6e2013-01-15 13:40:23 +0800878 }
879
880 /* this handles POLLOUT for http serving fragments */
881
882 if (!(pollfd->revents & POLLOUT))
883 break;
884
885 /* one shot */
886 pollfd->events &= ~POLLOUT;
887
888 if (wsi->state != WSI_STATE_HTTP_ISSUING_FILE)
889 break;
890
891 if (libwebsockets_serve_http_file_fragment(context, wsi) < 0)
892 libwebsocket_close_and_free_session(context, wsi,
893 LWS_CLOSE_STATUS_NOSTATUS);
894 else
895 if (wsi->state == WSI_STATE_HTTP && wsi->protocol->callback)
896 if (wsi->protocol->callback(context, wsi, LWS_CALLBACK_HTTP_FILE_COMPLETION, wsi->user_space,
897 wsi->filepath, wsi->filepos))
898 libwebsocket_close_and_free_session(context, wsi, LWS_CLOSE_STATUS_NOSTATUS);
899 break;
900
Andy Green0d338332011-02-12 11:57:43 +0000901 case LWS_CONNMODE_SERVER_LISTENER:
902
903 /* pollin means a client has connected to us then */
904
David Galeanob88e0962013-01-10 09:54:10 +0800905 if (!(pollfd->revents & POLLIN))
Andy Green0d338332011-02-12 11:57:43 +0000906 break;
907
908 /* listen socket got an unencrypted connection... */
909
910 clilen = sizeof(cli_addr);
911 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
912 &clilen);
913 if (accept_fd < 0) {
Andy Green1023d2b2013-01-16 11:43:53 +0800914 lwsl_warn("ERROR on accept: %s\n", strerror(errno));
915 break;
Andy Green0d338332011-02-12 11:57:43 +0000916 }
917
Andy Green6c939552011-03-08 08:56:57 +0000918 /* Disable Nagle */
919 opt = 1;
Andy Green6ee372f2012-04-09 15:09:01 +0800920 setsockopt(accept_fd, IPPROTO_TCP, TCP_NODELAY,
921 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +0000922
Andy Green07034092011-02-13 08:37:12 +0000923 /*
924 * look at who we connected to and give user code a chance
925 * to reject based on client IP. There's no protocol selected
926 * yet so we issue this to protocols[0]
927 */
928
Peter Hinz56885f32011-03-02 22:03:47 +0000929 if ((context->protocols[0].callback)(context, wsi,
Andy Green07034092011-02-13 08:37:12 +0000930 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
Andy Green6ee372f2012-04-09 15:09:01 +0800931 (void *)(long)accept_fd, NULL, 0)) {
Andy Green43db0452013-01-10 19:50:35 +0800932 lwsl_debug("Callback denied network connection\n");
Andy Green3fc2c652013-01-14 15:35:02 +0800933 compatible_close(accept_fd);
Andy Green07034092011-02-13 08:37:12 +0000934 break;
935 }
936
Andy Greena41314f2011-05-23 10:00:03 +0100937 new_wsi = libwebsocket_create_new_server_wsi(context);
David Galeanoed3c8402013-01-10 10:45:24 +0800938 if (new_wsi == NULL) {
Andy Green3fc2c652013-01-14 15:35:02 +0800939 compatible_close(accept_fd);
Andy Green0d338332011-02-12 11:57:43 +0000940 break;
David Galeanoed3c8402013-01-10 10:45:24 +0800941 }
Andy Green0d338332011-02-12 11:57:43 +0000942
Andy Green0d338332011-02-12 11:57:43 +0000943 new_wsi->sock = accept_fd;
Andy Greena41314f2011-05-23 10:00:03 +0100944
Andy Green0d338332011-02-12 11:57:43 +0000945
946#ifdef LWS_OPENSSL_SUPPORT
947 new_wsi->ssl = NULL;
Andy Green0d338332011-02-12 11:57:43 +0000948
Peter Hinz56885f32011-03-02 22:03:47 +0000949 if (context->use_ssl) {
Andy Green0d338332011-02-12 11:57:43 +0000950
Peter Hinz56885f32011-03-02 22:03:47 +0000951 new_wsi->ssl = SSL_new(context->ssl_ctx);
Andy Green0d338332011-02-12 11:57:43 +0000952 if (new_wsi->ssl == NULL) {
Andy Green43db0452013-01-10 19:50:35 +0800953 lwsl_err("SSL_new failed: %s\n",
Andy Green0d338332011-02-12 11:57:43 +0000954 ERR_error_string(SSL_get_error(
955 new_wsi->ssl, 0), NULL));
Andy Green1f9bf522011-02-14 21:14:37 +0000956 libwebsockets_decode_ssl_error();
Andy Green0d338332011-02-12 11:57:43 +0000957 free(new_wsi);
Andy Green3fc2c652013-01-14 15:35:02 +0800958 compatible_close(accept_fd);
Andy Green0d338332011-02-12 11:57:43 +0000959 break;
960 }
961
Larry Hayes455d1fe2013-01-15 01:03:58 +0800962 SSL_set_ex_data(new_wsi->ssl,
963 openssl_websocket_private_data_index, context);
964
Andy Green0d338332011-02-12 11:57:43 +0000965 SSL_set_fd(new_wsi->ssl, accept_fd);
966
967 n = SSL_accept(new_wsi->ssl);
968 if (n != 1) {
969 /*
970 * browsers seem to probe with various
971 * ssl params which fail then retry
972 * and succeed
973 */
Andy Green43db0452013-01-10 19:50:35 +0800974 lwsl_debug("SSL_accept failed skt %u: %s\n",
Andy Green0d338332011-02-12 11:57:43 +0000975 pollfd->fd,
976 ERR_error_string(SSL_get_error(
977 new_wsi->ssl, n), NULL));
978 SSL_free(
979 new_wsi->ssl);
980 free(new_wsi);
Andy Green3fc2c652013-01-14 15:35:02 +0800981 compatible_close(accept_fd);
Andy Green0d338332011-02-12 11:57:43 +0000982 break;
983 }
Andy Green6ee372f2012-04-09 15:09:01 +0800984
Andy Green43db0452013-01-10 19:50:35 +0800985 lwsl_debug("accepted new SSL conn "
Andy Green0d338332011-02-12 11:57:43 +0000986 "port %u on fd=%d SSL ver %s\n",
987 ntohs(cli_addr.sin_port), accept_fd,
988 SSL_get_version(new_wsi->ssl));
989
990 } else
991#endif
Andy Green43db0452013-01-10 19:50:35 +0800992 lwsl_debug("accepted new conn port %u on fd=%d\n",
Andy Green0d338332011-02-12 11:57:43 +0000993 ntohs(cli_addr.sin_port), accept_fd);
994
Andy Greendfb23042013-01-17 12:26:48 +0800995 insert_wsi_socket_into_fds(context, new_wsi);
Andy Green0d338332011-02-12 11:57:43 +0000996 break;
997
998 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
999
1000 /* as we are listening, POLLIN means accept() is needed */
Andy Green6ee372f2012-04-09 15:09:01 +08001001
David Galeanob88e0962013-01-10 09:54:10 +08001002 if (!(pollfd->revents & POLLIN))
Andy Green0d338332011-02-12 11:57:43 +00001003 break;
1004
1005 /* listen socket got an unencrypted connection... */
1006
1007 clilen = sizeof(cli_addr);
1008 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1009 &clilen);
1010 if (accept_fd < 0) {
Andy Green43db0452013-01-10 19:50:35 +08001011 lwsl_warn("ERROR on accept %d\n", accept_fd);
Andy Green040d2ef2013-01-16 13:40:43 +08001012 return 0;
Andy Green0d338332011-02-12 11:57:43 +00001013 }
1014
Andy Green0d338332011-02-12 11:57:43 +00001015 /* create a dummy wsi for the connection and add it */
1016
Aaron Zinman4550f1d2013-01-10 12:35:18 +08001017 new_wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
Andy Green41c58032013-01-12 13:21:08 +08001018 if (new_wsi == NULL) {
1019 lwsl_err("Out of mem\n");
1020 goto bail_prox_listener;
1021 }
Aaron Zinman4550f1d2013-01-10 12:35:18 +08001022 memset(new_wsi, 0, sizeof (struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00001023 new_wsi->sock = accept_fd;
1024 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
1025 new_wsi->state = WSI_STATE_ESTABLISHED;
Andy Greend6e09112011-03-05 16:12:15 +00001026 new_wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00001027 /* note which protocol we are proxying */
1028 new_wsi->protocol_index_for_broadcast_proxy =
1029 wsi->protocol_index_for_broadcast_proxy;
Andy Green0d338332011-02-12 11:57:43 +00001030
Andy Greendfb23042013-01-17 12:26:48 +08001031 insert_wsi_socket_into_fds(context, new_wsi);
Andy Green0d338332011-02-12 11:57:43 +00001032 break;
1033
Andy Green41c58032013-01-12 13:21:08 +08001034bail_prox_listener:
Andy Green3fc2c652013-01-14 15:35:02 +08001035 compatible_close(accept_fd);
Andy Green41c58032013-01-12 13:21:08 +08001036 break;
1037
Andy Green0d338332011-02-12 11:57:43 +00001038 case LWS_CONNMODE_BROADCAST_PROXY:
Andy Green8f037e42010-12-19 22:13:26 +00001039
Andy Greenb45993c2010-12-18 15:13:50 +00001040 /* handle session socket closed */
Andy Green8f037e42010-12-19 22:13:26 +00001041
Andy Green0d338332011-02-12 11:57:43 +00001042 if (pollfd->revents & (POLLERR | POLLHUP)) {
Andy Green8f037e42010-12-19 22:13:26 +00001043
Andy Green43db0452013-01-10 19:50:35 +08001044 lwsl_debug("Session Socket %p (fd=%d) dead\n",
Timothy J Fontaineb86d64e2011-02-14 17:55:27 +00001045 (void *)wsi, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +00001046
Peter Hinz56885f32011-03-02 22:03:47 +00001047 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001048 LWS_CLOSE_STATUS_NORMAL);
Andy Green040d2ef2013-01-16 13:40:43 +08001049 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00001050 }
Andy Green8f037e42010-12-19 22:13:26 +00001051
Andy Green3b84c002011-03-06 13:14:42 +00001052 /*
1053 * either extension code with stuff to spill, or the user code,
1054 * requested a callback when it was OK to write
1055 */
Andy Green90c7cbc2011-01-27 06:26:52 +00001056
Andy Green3b84c002011-03-06 13:14:42 +00001057 if (pollfd->revents & POLLOUT)
Andy Green6ee372f2012-04-09 15:09:01 +08001058 if (lws_handle_POLLOUT_event(context, wsi,
1059 pollfd) < 0) {
1060 libwebsocket_close_and_free_session(
1061 context, wsi, LWS_CLOSE_STATUS_NORMAL);
Andy Green040d2ef2013-01-16 13:40:43 +08001062 return 0;
Andy Green3b84c002011-03-06 13:14:42 +00001063 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001064
Andy Greenb45993c2010-12-18 15:13:50 +00001065 /* any incoming data ready? */
1066
Andy Green0d338332011-02-12 11:57:43 +00001067 if (!(pollfd->revents & POLLIN))
1068 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001069
Andy Green0d338332011-02-12 11:57:43 +00001070 /* get the issued broadcast payload from the socket */
Andy Greenb45993c2010-12-18 15:13:50 +00001071
Andy Green0d338332011-02-12 11:57:43 +00001072 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
1073 MAX_BROADCAST_PAYLOAD);
1074 if (len < 0) {
Andy Green43db0452013-01-10 19:50:35 +08001075 lwsl_err("Error reading broadcast payload\n");
Andy Green4b6fbe12011-02-14 08:03:48 +00001076 break;
Andy Green0d338332011-02-12 11:57:43 +00001077 }
Andy Greenb45993c2010-12-18 15:13:50 +00001078
Andy Green0d338332011-02-12 11:57:43 +00001079 /* broadcast it to all guys with this protocol index */
Andy Green8f037e42010-12-19 22:13:26 +00001080
Andy Greendfb23042013-01-17 12:26:48 +08001081 for (n = 0; n < context->fds_count; n++) {
Andy Green8f037e42010-12-19 22:13:26 +00001082
Andy Greendfb23042013-01-17 12:26:48 +08001083 new_wsi = context->lws_lookup[context->fds[n].fd];
1084 if (new_wsi == NULL)
1085 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00001086
Andy Greendfb23042013-01-17 12:26:48 +08001087 /* only to clients we are serving to */
Andy Greenb45993c2010-12-18 15:13:50 +00001088
Andy Greendfb23042013-01-17 12:26:48 +08001089 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
1090 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00001091
Andy Greendfb23042013-01-17 12:26:48 +08001092 /*
1093 * never broadcast to non-established
1094 * connection
1095 */
Andy Greenb45993c2010-12-18 15:13:50 +00001096
Andy Greendfb23042013-01-17 12:26:48 +08001097 if (new_wsi->state != WSI_STATE_ESTABLISHED)
1098 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00001099
Andy Greendfb23042013-01-17 12:26:48 +08001100 /*
1101 * only broadcast to connections using
1102 * the requested protocol
1103 */
Andy Green4739e5c2011-01-22 12:51:57 +00001104
Andy Greendfb23042013-01-17 12:26:48 +08001105 if (new_wsi->protocol->protocol_index !=
1106 wsi->protocol_index_for_broadcast_proxy)
1107 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00001108
Andy Greendfb23042013-01-17 12:26:48 +08001109 /* broadcast it to this connection */
Andy Greenb45993c2010-12-18 15:13:50 +00001110
Andy Greendfb23042013-01-17 12:26:48 +08001111 new_wsi->protocol->callback(context, new_wsi,
1112 LWS_CALLBACK_BROADCAST,
1113 new_wsi->user_space,
1114 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
Andy Green0d338332011-02-12 11:57:43 +00001115 }
1116 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001117
Andy Greenbe93fef2011-02-14 20:25:43 +00001118
Andy Green0d338332011-02-12 11:57:43 +00001119 case LWS_CONNMODE_WS_SERVING:
1120 case LWS_CONNMODE_WS_CLIENT:
1121
1122 /* handle session socket closed */
1123
1124 if (pollfd->revents & (POLLERR | POLLHUP)) {
1125
Andy Green43db0452013-01-10 19:50:35 +08001126 lwsl_debug("Session Socket %p (fd=%d) dead\n",
Andy Green0d338332011-02-12 11:57:43 +00001127 (void *)wsi, pollfd->fd);
1128
Peter Hinz56885f32011-03-02 22:03:47 +00001129 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001130 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green040d2ef2013-01-16 13:40:43 +08001131 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00001132 }
1133
Andy Green0d338332011-02-12 11:57:43 +00001134 /* the guy requested a callback when it was OK to write */
1135
Andy Greenda527df2011-03-07 07:08:12 +00001136 if ((pollfd->revents & POLLOUT) &&
1137 wsi->state == WSI_STATE_ESTABLISHED)
1138 if (lws_handle_POLLOUT_event(context, wsi,
1139 pollfd) < 0) {
1140 libwebsocket_close_and_free_session(
1141 context, wsi, LWS_CLOSE_STATUS_NORMAL);
Andy Green040d2ef2013-01-16 13:40:43 +08001142 return 0;
Andy Green3b84c002011-03-06 13:14:42 +00001143 }
Andy Green0d338332011-02-12 11:57:43 +00001144
Andy Green0d338332011-02-12 11:57:43 +00001145
1146 /* any incoming data ready? */
1147
1148 if (!(pollfd->revents & POLLIN))
1149 break;
1150
Andy Greenb45993c2010-12-18 15:13:50 +00001151#ifdef LWS_OPENSSL_SUPPORT
David Galeano7ffbe1b2013-01-10 10:35:32 +08001152read_pending:
Andy Green0d338332011-02-12 11:57:43 +00001153 if (wsi->ssl)
Andy Green98a717c2011-03-06 13:14:15 +00001154 eff_buf.token_len = SSL_read(wsi->ssl, buf, sizeof buf);
Andy Greenb45993c2010-12-18 15:13:50 +00001155 else
1156#endif
Andy Green98a717c2011-03-06 13:14:15 +00001157 eff_buf.token_len =
Andy Green72c34322011-04-16 10:46:21 +01001158 recv(pollfd->fd, buf, sizeof buf, 0);
Andy Greenb45993c2010-12-18 15:13:50 +00001159
Andy Green98a717c2011-03-06 13:14:15 +00001160 if (eff_buf.token_len < 0) {
Andy Green43db0452013-01-10 19:50:35 +08001161 lwsl_debug("Socket read returned %d\n",
Andy Green98a717c2011-03-06 13:14:15 +00001162 eff_buf.token_len);
Alon Levydc93b7f2012-10-19 11:21:57 +02001163 if (errno != EINTR && errno != EAGAIN)
Andy Green6ee372f2012-04-09 15:09:01 +08001164 libwebsocket_close_and_free_session(context,
1165 wsi, LWS_CLOSE_STATUS_NOSTATUS);
Andy Green040d2ef2013-01-16 13:40:43 +08001166 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00001167 }
Andy Green98a717c2011-03-06 13:14:15 +00001168 if (!eff_buf.token_len) {
Peter Hinz56885f32011-03-02 22:03:47 +00001169 libwebsocket_close_and_free_session(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001170 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenfa3f4052012-10-07 20:40:35 +08001171 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00001172 }
1173
Andy Green98a717c2011-03-06 13:14:15 +00001174 /*
1175 * give any active extensions a chance to munge the buffer
1176 * before parse. We pass in a pointer to an lws_tokens struct
1177 * prepared with the default buffer and content length that's in
1178 * there. Rather than rewrite the default buffer, extensions
1179 * that expect to grow the buffer can adapt .token to
1180 * point to their own per-connection buffer in the extension
1181 * user allocation. By default with no extensions or no
1182 * extension callback handling, just the normal input buffer is
1183 * used then so it is efficient.
1184 */
Andy Greenb45993c2010-12-18 15:13:50 +00001185
Andy Green98a717c2011-03-06 13:14:15 +00001186 eff_buf.token = (char *)buf;
Andy Greenb45993c2010-12-18 15:13:50 +00001187
Andy Green98a717c2011-03-06 13:14:15 +00001188 more = 1;
1189 while (more) {
Andy Green0d338332011-02-12 11:57:43 +00001190
Andy Green98a717c2011-03-06 13:14:15 +00001191 more = 0;
1192
1193 for (n = 0; n < wsi->count_active_extensions; n++) {
Andy Green46c2ea02011-03-22 09:04:01 +00001194 m = wsi->active_extensions[n]->callback(context,
1195 wsi->active_extensions[n], wsi,
Andy Green98a717c2011-03-06 13:14:15 +00001196 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
Andy Green46c2ea02011-03-22 09:04:01 +00001197 wsi->active_extensions_user[n],
1198 &eff_buf, 0);
Andy Green98a717c2011-03-06 13:14:15 +00001199 if (m < 0) {
Andy Green43db0452013-01-10 19:50:35 +08001200 lwsl_ext(
Andy Green6ee372f2012-04-09 15:09:01 +08001201 "Extension reports fatal error\n");
1202 libwebsocket_close_and_free_session(
1203 context, wsi,
1204 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green040d2ef2013-01-16 13:40:43 +08001205 return 0;
Andy Green98a717c2011-03-06 13:14:15 +00001206 }
1207 if (m)
1208 more = 1;
1209 }
1210
1211 /* service incoming data */
1212
1213 if (eff_buf.token_len) {
1214 n = libwebsocket_read(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001215 (unsigned char *)eff_buf.token,
1216 eff_buf.token_len);
Andy Green98a717c2011-03-06 13:14:15 +00001217 if (n < 0)
1218 /* we closed wsi */
Andy Green040d2ef2013-01-16 13:40:43 +08001219 return 0;
Andy Green98a717c2011-03-06 13:14:15 +00001220 }
1221
1222 eff_buf.token = NULL;
1223 eff_buf.token_len = 0;
1224 }
David Galeano7ffbe1b2013-01-10 10:35:32 +08001225
1226#ifdef LWS_OPENSSL_SUPPORT
1227 if (wsi->ssl && SSL_pending(wsi->ssl))
1228 goto read_pending;
1229#endif
Andy Green98a717c2011-03-06 13:14:15 +00001230 break;
Andy Green76f61e72013-01-16 11:53:05 +08001231
1232 default:
Andy Green03674a62013-01-16 11:47:40 +08001233#ifdef LWS_NO_CLIENT
1234 break;
1235#else
Andy Green76f61e72013-01-16 11:53:05 +08001236 return lws_client_socket_service(context, wsi, pollfd);
Andy Green03674a62013-01-16 11:47:40 +08001237#endif
Andy Greenb45993c2010-12-18 15:13:50 +00001238 }
1239
1240 return 0;
1241}
1242
Andy Green0d338332011-02-12 11:57:43 +00001243
Andy Green6964bb52011-01-23 16:50:33 +00001244/**
1245 * libwebsocket_context_destroy() - Destroy the websocket context
Peter Hinz56885f32011-03-02 22:03:47 +00001246 * @context: Websocket context
Andy Green6964bb52011-01-23 16:50:33 +00001247 *
1248 * This function closes any active connections and then frees the
1249 * context. After calling this, any further use of the context is
1250 * undefined.
1251 */
1252void
Peter Hinz56885f32011-03-02 22:03:47 +00001253libwebsocket_context_destroy(struct libwebsocket_context *context)
Andy Green6964bb52011-01-23 16:50:33 +00001254{
Andy Green0d338332011-02-12 11:57:43 +00001255 int n;
1256 int m;
Andy Greena41314f2011-05-23 10:00:03 +01001257 struct libwebsocket_extension *ext;
Andy Green6964bb52011-01-23 16:50:33 +00001258
Andy Greendfb23042013-01-17 12:26:48 +08001259 for (n = 0; n < context->fds_count; n++) {
1260 struct libwebsocket *wsi = context->lws_lookup[context->fds[n].fd];
1261 libwebsocket_close_and_free_session(context,
1262 wsi, LWS_CLOSE_STATUS_GOINGAWAY);
1263 }
Andy Green6964bb52011-01-23 16:50:33 +00001264
Andy Greena41314f2011-05-23 10:00:03 +01001265 /*
1266 * give all extensions a chance to clean up any per-context
1267 * allocations they might have made
1268 */
1269
1270 ext = context->extensions;
1271 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
1272 if (context->listen_port)
1273 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
Paulo Roberto Urio1f680ab2012-06-04 08:40:28 +08001274 while (ext && ext->callback) {
Aaron Zinman4550f1d2013-01-10 12:35:18 +08001275 ext->callback(context, ext, NULL, (enum libwebsocket_extension_callback_reasons)m, NULL, NULL, 0);
Andy Greena41314f2011-05-23 10:00:03 +01001276 ext++;
1277 }
1278
Peter Hinz56885f32011-03-02 22:03:47 +00001279#ifdef WIN32
1280#else
1281 close(context->fd_random);
Andy Green6964bb52011-01-23 16:50:33 +00001282#endif
1283
Peter Hinz56885f32011-03-02 22:03:47 +00001284#ifdef LWS_OPENSSL_SUPPORT
1285 if (context->ssl_ctx)
1286 SSL_CTX_free(context->ssl_ctx);
1287 if (context->ssl_client_ctx)
1288 SSL_CTX_free(context->ssl_client_ctx);
1289#endif
1290
1291 free(context);
1292
1293#ifdef WIN32
1294 WSACleanup();
1295#endif
Andy Green6964bb52011-01-23 16:50:33 +00001296}
1297
Alon Levy0291eb32012-10-19 11:21:56 +02001298LWS_EXTERN void *
1299libwebsocket_context_user(struct libwebsocket_context *context)
1300{
1301 return context->user_space;
1302}
1303
Andy Green6964bb52011-01-23 16:50:33 +00001304/**
1305 * libwebsocket_service() - Service any pending websocket activity
Peter Hinz56885f32011-03-02 22:03:47 +00001306 * @context: Websocket context
Andy Green6964bb52011-01-23 16:50:33 +00001307 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1308 * service otherwise block and service immediately, returning
1309 * after the timeout if nothing needed service.
1310 *
1311 * This function deals with any pending websocket traffic, for three
1312 * kinds of event. It handles these events on both server and client
1313 * types of connection the same.
1314 *
1315 * 1) Accept new connections to our context's server
1316 *
1317 * 2) Perform pending broadcast writes initiated from other forked
1318 * processes (effectively serializing asynchronous broadcasts)
1319 *
1320 * 3) Call the receive callback for incoming frame data received by
1321 * server or client connections.
1322 *
1323 * You need to call this service function periodically to all the above
1324 * functions to happen; if your application is single-threaded you can
1325 * just call it in your main event loop.
1326 *
1327 * Alternatively you can fork a new process that asynchronously handles
1328 * calling this service in a loop. In that case you are happy if this
1329 * call blocks your thread until it needs to take care of something and
1330 * would call it with a large nonzero timeout. Your loop then takes no
1331 * CPU while there is nothing happening.
1332 *
1333 * If you are calling it in a single-threaded app, you don't want it to
1334 * wait around blocking other things in your loop from happening, so you
1335 * would call it with a timeout_ms of 0, so it returns immediately if
1336 * nothing is pending, or as soon as it services whatever was pending.
1337 */
1338
Andy Greenb45993c2010-12-18 15:13:50 +00001339
Andy Greene92cd172011-01-19 13:11:55 +00001340int
Peter Hinz56885f32011-03-02 22:03:47 +00001341libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
Andy Greene92cd172011-01-19 13:11:55 +00001342{
1343 int n;
Andy Greene92cd172011-01-19 13:11:55 +00001344
1345 /* stay dead once we are dead */
1346
Peter Hinz56885f32011-03-02 22:03:47 +00001347 if (context == NULL)
Andy Greene92cd172011-01-19 13:11:55 +00001348 return 1;
1349
Andy Green0d338332011-02-12 11:57:43 +00001350 /* wait for something to need service */
Andy Green4739e5c2011-01-22 12:51:57 +00001351
Peter Hinz56885f32011-03-02 22:03:47 +00001352 n = poll(context->fds, context->fds_count, timeout_ms);
Andy Green3221f922011-02-12 13:14:11 +00001353 if (n == 0) /* poll timeout */
1354 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00001355
Andy Greendfb23042013-01-17 12:26:48 +08001356 if (n < 0)
Andy Green3928f612012-07-20 12:58:38 +08001357 return -1;
Andy Greene92cd172011-01-19 13:11:55 +00001358
Andy Greendfb23042013-01-17 12:26:48 +08001359 /* any socket with events to service? */
Andy Greene92cd172011-01-19 13:11:55 +00001360
Peter Hinz56885f32011-03-02 22:03:47 +00001361 for (n = 0; n < context->fds_count; n++)
1362 if (context->fds[n].revents)
Andy Green3928f612012-07-20 12:58:38 +08001363 if (libwebsocket_service_fd(context,
1364 &context->fds[n]) < 0)
1365 return -1;
Andy Greene92cd172011-01-19 13:11:55 +00001366 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00001367}
1368
Andy Greena41314f2011-05-23 10:00:03 +01001369int
1370lws_any_extension_handled(struct libwebsocket_context *context,
Andy Green6ee372f2012-04-09 15:09:01 +08001371 struct libwebsocket *wsi,
1372 enum libwebsocket_extension_callback_reasons r,
Andy Greena41314f2011-05-23 10:00:03 +01001373 void *v, size_t len)
1374{
1375 int n;
1376 int handled = 0;
1377
1378 /* maybe an extension will take care of it for us */
1379
1380 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
1381 if (!wsi->active_extensions[n]->callback)
1382 continue;
1383
1384 handled |= wsi->active_extensions[n]->callback(context,
1385 wsi->active_extensions[n], wsi,
1386 r, wsi->active_extensions_user[n], v, len);
1387 }
1388
1389 return handled;
1390}
1391
1392
1393void *
1394lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001395 struct libwebsocket_extension *ext)
Andy Greena41314f2011-05-23 10:00:03 +01001396{
1397 int n = 0;
1398
Andy Green68b45042011-05-25 21:41:57 +01001399 if (wsi == NULL)
1400 return NULL;
1401
Andy Greena41314f2011-05-23 10:00:03 +01001402 while (n < wsi->count_active_extensions) {
1403 if (wsi->active_extensions[n] != ext) {
1404 n++;
1405 continue;
1406 }
1407 return wsi->active_extensions_user[n];
1408 }
1409
1410 return NULL;
1411}
1412
Andy Green90c7cbc2011-01-27 06:26:52 +00001413/**
1414 * libwebsocket_callback_on_writable() - Request a callback when this socket
1415 * becomes able to be written to without
1416 * blocking
Andy Green32375b72011-02-19 08:32:53 +00001417 *
Peter Hinz56885f32011-03-02 22:03:47 +00001418 * @context: libwebsockets context
Andy Green90c7cbc2011-01-27 06:26:52 +00001419 * @wsi: Websocket connection instance to get callback for
1420 */
1421
1422int
Peter Hinz56885f32011-03-02 22:03:47 +00001423libwebsocket_callback_on_writable(struct libwebsocket_context *context,
Andy Green6ee372f2012-04-09 15:09:01 +08001424 struct libwebsocket *wsi)
Andy Green90c7cbc2011-01-27 06:26:52 +00001425{
Andy Green90c7cbc2011-01-27 06:26:52 +00001426 int n;
Andy Greena41314f2011-05-23 10:00:03 +01001427 int handled = 0;
1428
1429 /* maybe an extension will take care of it for us */
1430
1431 for (n = 0; n < wsi->count_active_extensions; n++) {
1432 if (!wsi->active_extensions[n]->callback)
1433 continue;
1434
1435 handled |= wsi->active_extensions[n]->callback(context,
1436 wsi->active_extensions[n], wsi,
1437 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
1438 wsi->active_extensions_user[n], NULL, 0);
1439 }
1440
1441 if (handled)
1442 return 1;
Andy Green90c7cbc2011-01-27 06:26:52 +00001443
Andy Greendfb23042013-01-17 12:26:48 +08001444 if (wsi->position_in_fds_table < 0) {
Andy Green43db0452013-01-10 19:50:35 +08001445 lwsl_err("libwebsocket_callback_on_writable: "
Andy Green6ee372f2012-04-09 15:09:01 +08001446 "failed to find socket %d\n", wsi->sock);
Andy Greendfb23042013-01-17 12:26:48 +08001447 return -1;
1448 }
1449
1450 context->fds[wsi->position_in_fds_table].events |= POLLOUT;
Andy Greena41314f2011-05-23 10:00:03 +01001451
Andy Green3221f922011-02-12 13:14:11 +00001452 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001453 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001454 LWS_CALLBACK_SET_MODE_POLL_FD,
1455 (void *)(long)wsi->sock, NULL, POLLOUT);
1456
Andy Green90c7cbc2011-01-27 06:26:52 +00001457 return 1;
1458}
1459
1460/**
1461 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1462 * all connections using the given protocol when it
1463 * becomes possible to write to each socket without
1464 * blocking in turn.
1465 *
1466 * @protocol: Protocol whose connections will get callbacks
1467 */
1468
1469int
1470libwebsocket_callback_on_writable_all_protocol(
1471 const struct libwebsocket_protocols *protocol)
1472{
Peter Hinz56885f32011-03-02 22:03:47 +00001473 struct libwebsocket_context *context = protocol->owning_server;
Andy Green90c7cbc2011-01-27 06:26:52 +00001474 int n;
Andy Green0d338332011-02-12 11:57:43 +00001475 struct libwebsocket *wsi;
Andy Green90c7cbc2011-01-27 06:26:52 +00001476
Andy Greendfb23042013-01-17 12:26:48 +08001477 for (n = 0; n < context->fds_count; n++) {
1478 wsi = context->lws_lookup[context->fds[n].fd];
1479 if (!wsi)
1480 continue;
1481 if (wsi->protocol == protocol)
1482 libwebsocket_callback_on_writable(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00001483 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001484
1485 return 0;
1486}
1487
Andy Greenbe93fef2011-02-14 20:25:43 +00001488/**
1489 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1490 *
1491 * You will not need this unless you are doing something special
1492 *
1493 * @wsi: Websocket connection instance
1494 * @reason: timeout reason
1495 * @secs: how many seconds
1496 */
1497
1498void
1499libwebsocket_set_timeout(struct libwebsocket *wsi,
1500 enum pending_timeout reason, int secs)
1501{
1502 struct timeval tv;
1503
1504 gettimeofday(&tv, NULL);
1505
1506 wsi->pending_timeout_limit = tv.tv_sec + secs;
1507 wsi->pending_timeout = reason;
1508}
1509
Andy Greena6cbece2011-01-27 20:06:03 +00001510
1511/**
1512 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1513 *
1514 * You will not need this unless you are doing something special
1515 *
1516 * @wsi: Websocket connection instance
1517 */
1518
1519int
1520libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1521{
1522 return wsi->sock;
1523}
1524
Andy Green90c7cbc2011-01-27 06:26:52 +00001525/**
1526 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1527 * receieved packets.
1528 *
1529 * If the output side of a server process becomes choked, this allows flow
1530 * control for the input side.
1531 *
1532 * @wsi: Websocket connection instance to get callback for
1533 * @enable: 0 = disable read servicing for this connection, 1 = enable
1534 */
1535
1536int
1537libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1538{
Peter Hinz56885f32011-03-02 22:03:47 +00001539 struct libwebsocket_context *context = wsi->protocol->owning_server;
Andy Green90c7cbc2011-01-27 06:26:52 +00001540 int n;
1541
Peter Hinz56885f32011-03-02 22:03:47 +00001542 for (n = 0; n < context->fds_count; n++)
1543 if (context->fds[n].fd == wsi->sock) {
Andy Green90c7cbc2011-01-27 06:26:52 +00001544 if (enable)
Peter Hinz56885f32011-03-02 22:03:47 +00001545 context->fds[n].events |= POLLIN;
Andy Green90c7cbc2011-01-27 06:26:52 +00001546 else
Peter Hinz56885f32011-03-02 22:03:47 +00001547 context->fds[n].events &= ~POLLIN;
Andy Green90c7cbc2011-01-27 06:26:52 +00001548
1549 return 0;
1550 }
1551
Andy Green3221f922011-02-12 13:14:11 +00001552 if (enable)
1553 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001554 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001555 LWS_CALLBACK_SET_MODE_POLL_FD,
1556 (void *)(long)wsi->sock, NULL, POLLIN);
1557 else
1558 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001559 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001560 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1561 (void *)(long)wsi->sock, NULL, POLLIN);
1562
Andy Greena41314f2011-05-23 10:00:03 +01001563#if 0
Andy Green43db0452013-01-10 19:50:35 +08001564 lwsl_err("libwebsocket_rx_flow_control unable to find socket\n");
Andy Greena41314f2011-05-23 10:00:03 +01001565#endif
Andy Green90c7cbc2011-01-27 06:26:52 +00001566 return 1;
1567}
1568
Andy Green2ac5a6f2011-01-28 10:00:18 +00001569/**
1570 * libwebsocket_canonical_hostname() - returns this host's hostname
1571 *
1572 * This is typically used by client code to fill in the host parameter
1573 * when making a client connection. You can only call it after the context
1574 * has been created.
1575 *
Peter Hinz56885f32011-03-02 22:03:47 +00001576 * @context: Websocket context
Andy Green2ac5a6f2011-01-28 10:00:18 +00001577 */
1578
1579
1580extern const char *
Peter Hinz56885f32011-03-02 22:03:47 +00001581libwebsocket_canonical_hostname(struct libwebsocket_context *context)
Andy Green2ac5a6f2011-01-28 10:00:18 +00001582{
Peter Hinz56885f32011-03-02 22:03:47 +00001583 return (const char *)context->canonical_hostname;
Andy Green2ac5a6f2011-01-28 10:00:18 +00001584}
1585
1586
Andy Green90c7cbc2011-01-27 06:26:52 +00001587static void sigpipe_handler(int x)
1588{
1589}
1590
Andy Green6901cb32011-02-21 08:06:47 +00001591#ifdef LWS_OPENSSL_SUPPORT
1592static int
1593OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1594{
1595
1596 SSL *ssl;
1597 int n;
Andy Green2e24da02011-03-05 16:12:04 +00001598 struct libwebsocket_context *context;
Andy Green6901cb32011-02-21 08:06:47 +00001599
1600 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1601 SSL_get_ex_data_X509_STORE_CTX_idx());
1602
1603 /*
Andy Green2e24da02011-03-05 16:12:04 +00001604 * !!! nasty openssl requires the index to come as a library-scope
1605 * static
Andy Green6901cb32011-02-21 08:06:47 +00001606 */
Andy Green2e24da02011-03-05 16:12:04 +00001607 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
Andy Green6ee372f2012-04-09 15:09:01 +08001608
Peter Hinz56885f32011-03-02 22:03:47 +00001609 n = context->protocols[0].callback(NULL, NULL,
Andy Green6901cb32011-02-21 08:06:47 +00001610 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1611 x509_ctx, ssl, preverify_ok);
1612
1613 /* convert return code from 0 = OK to 1 = OK */
1614
1615 if (!n)
1616 n = 1;
1617 else
1618 n = 0;
1619
1620 return n;
1621}
1622#endif
1623
Andy Greenb45993c2010-12-18 15:13:50 +00001624
Andy Greenab990e42010-10-31 12:42:52 +00001625/**
Andy Green4739e5c2011-01-22 12:51:57 +00001626 * libwebsocket_create_context() - Create the websocket handler
1627 * @port: Port to listen on... you can use 0 to suppress listening on
Andy Green6964bb52011-01-23 16:50:33 +00001628 * any port, that's what you want if you are not running a
1629 * websocket server at all but just using it as a client
Peter Hinz56885f32011-03-02 22:03:47 +00001630 * @interf: NULL to bind the listen socket to all interfaces, or the
Andy Green32375b72011-02-19 08:32:53 +00001631 * interface name, eg, "eth2"
Andy Green4f3943a2010-11-12 10:44:16 +00001632 * @protocols: Array of structures listing supported protocols and a protocol-
Andy Green8f037e42010-12-19 22:13:26 +00001633 * specific callback for each one. The list is ended with an
1634 * entry that has a NULL callback pointer.
Andy Green6964bb52011-01-23 16:50:33 +00001635 * It's not const because we write the owning_server member
Andy Greenc5114822011-03-06 10:29:35 +00001636 * @extensions: NULL or array of libwebsocket_extension structs listing the
Andy Green6ee372f2012-04-09 15:09:01 +08001637 * extensions this context supports
Andy Green3faa9c72010-11-08 17:03:03 +00001638 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
Andy Green8f037e42010-12-19 22:13:26 +00001639 * to listen using SSL, set to the filepath to fetch the
1640 * server cert from, otherwise NULL for unencrypted
Andy Green3faa9c72010-11-08 17:03:03 +00001641 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
Andy Green8f037e42010-12-19 22:13:26 +00001642 * else ignored
David Galeano2f82be82013-01-09 16:25:54 +08001643 * @ssl_ca_filepath: CA certificate filepath or NULL
Andy Green3faa9c72010-11-08 17:03:03 +00001644 * @gid: group id to change to after setting listen socket, or -1.
1645 * @uid: user id to change to after setting listen socket, or -1.
Andy Greenbfb051f2011-02-09 08:49:14 +00001646 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
Andy Green15e31f32012-10-19 18:36:28 +08001647 * @user: optional user pointer that can be recovered via the context
1648 * pointer using libwebsocket_context_user
Andy Green05464c62010-11-12 10:44:18 +00001649 *
Andy Green8f037e42010-12-19 22:13:26 +00001650 * This function creates the listening socket and takes care
1651 * of all initialization in one step.
1652 *
Andy Greene92cd172011-01-19 13:11:55 +00001653 * After initialization, it returns a struct libwebsocket_context * that
1654 * represents this server. After calling, user code needs to take care
1655 * of calling libwebsocket_service() with the context pointer to get the
1656 * server's sockets serviced. This can be done in the same process context
1657 * or a forked process, or another thread,
Andy Green05464c62010-11-12 10:44:18 +00001658 *
Andy Green8f037e42010-12-19 22:13:26 +00001659 * The protocol callback functions are called for a handful of events
1660 * including http requests coming in, websocket connections becoming
1661 * established, and data arriving; it's also called periodically to allow
1662 * async transmission.
1663 *
1664 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1665 * at that time websocket protocol has not been negotiated. Other
1666 * protocols after the first one never see any HTTP callack activity.
1667 *
1668 * The server created is a simple http server by default; part of the
1669 * websocket standard is upgrading this http connection to a websocket one.
1670 *
1671 * This allows the same server to provide files like scripts and favicon /
1672 * images or whatever over http and dynamic data over websockets all in
1673 * one place; they're all handled in the user callback.
Andy Greenab990e42010-10-31 12:42:52 +00001674 */
Andy Green4ea60062010-10-30 12:15:07 +01001675
Andy Greene92cd172011-01-19 13:11:55 +00001676struct libwebsocket_context *
Peter Hinz56885f32011-03-02 22:03:47 +00001677libwebsocket_create_context(int port, const char *interf,
Andy Greenb45993c2010-12-18 15:13:50 +00001678 struct libwebsocket_protocols *protocols,
Andy Greend6e09112011-03-05 16:12:15 +00001679 struct libwebsocket_extension *extensions,
Andy Green8f037e42010-12-19 22:13:26 +00001680 const char *ssl_cert_filepath,
1681 const char *ssl_private_key_filepath,
David Galeano2f82be82013-01-09 16:25:54 +08001682 const char *ssl_ca_filepath,
Alon Levy0291eb32012-10-19 11:21:56 +02001683 int gid, int uid, unsigned int options,
David Galeano2f82be82013-01-09 16:25:54 +08001684 void *user)
Andy Greenff95d7a2010-10-28 22:36:01 +01001685{
1686 int n;
Andy Greena41314f2011-05-23 10:00:03 +01001687 int m;
Andy Green4739e5c2011-01-22 12:51:57 +00001688 int sockfd = 0;
Andy Green251f6fa2010-11-03 11:13:06 +00001689 int fd;
Andy Greenff95d7a2010-10-28 22:36:01 +01001690 struct sockaddr_in serv_addr, cli_addr;
Andy Green251f6fa2010-11-03 11:13:06 +00001691 int opt = 1;
Peter Hinz56885f32011-03-02 22:03:47 +00001692 struct libwebsocket_context *context = NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001693 unsigned int slen;
Andy Green9659f372011-01-27 22:01:43 +00001694 char *p;
Paulo Roberto Urio1e326632012-06-04 10:52:19 +08001695 char hostname[1024] = "";
Andy Greena69f0512012-05-03 12:32:38 +08001696// struct hostent *he;
Andy Green0d338332011-02-12 11:57:43 +00001697 struct libwebsocket *wsi;
Andy Greena69f0512012-05-03 12:32:38 +08001698 struct sockaddr sa;
Andy Greenff95d7a2010-10-28 22:36:01 +01001699
Andy Green3faa9c72010-11-08 17:03:03 +00001700#ifdef LWS_OPENSSL_SUPPORT
Andy Greenf2f54d52010-11-15 22:08:00 +00001701 SSL_METHOD *method;
Andy Green3faa9c72010-11-08 17:03:03 +00001702 char ssl_err_buf[512];
Andy Green3faa9c72010-11-08 17:03:03 +00001703#endif
1704
Andy Green43db0452013-01-10 19:50:35 +08001705 lwsl_info("Initial logging level %d\n", log_level);
Andy Greenc0d6b632013-01-12 23:42:17 +08001706 lwsl_info(" LWS_MAX_HEADER_NAME_LENGTH: %u\n", LWS_MAX_HEADER_NAME_LENGTH);
1707 lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
1708 lwsl_info(" LWS_INITIAL_HDR_ALLOC: %u\n", LWS_INITIAL_HDR_ALLOC);
1709 lwsl_info(" LWS_ADDITIONAL_HDR_ALLOC: %u\n", LWS_ADDITIONAL_HDR_ALLOC);
1710 lwsl_info(" MAX_USER_RX_BUFFER: %u\n", MAX_USER_RX_BUFFER);
1711 lwsl_info(" MAX_BROADCAST_PAYLOAD: %u\n", MAX_BROADCAST_PAYLOAD);
1712 lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
1713 lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n", LWS_MAX_EXTENSIONS_ACTIVE);
1714 lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
1715 lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
1716 lwsl_info(" CIPHERS_LIST_STRING: '%s'\n", CIPHERS_LIST_STRING);
1717 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
1718 lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
Andy Green43db0452013-01-10 19:50:35 +08001719
Peter Hinz56885f32011-03-02 22:03:47 +00001720#ifdef _WIN32
1721 {
1722 WORD wVersionRequested;
1723 WSADATA wsaData;
1724 int err;
Andy Green6ee372f2012-04-09 15:09:01 +08001725 HMODULE wsdll;
Peter Hinz56885f32011-03-02 22:03:47 +00001726
1727 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1728 wVersionRequested = MAKEWORD(2, 2);
1729
1730 err = WSAStartup(wVersionRequested, &wsaData);
1731 if (err != 0) {
1732 /* Tell the user that we could not find a usable */
1733 /* Winsock DLL. */
Andy Green43db0452013-01-10 19:50:35 +08001734 lwsl_err("WSAStartup failed with error: %d\n", err);
Peter Hinz56885f32011-03-02 22:03:47 +00001735 return NULL;
1736 }
David Galeano7b11fec2011-10-04 19:55:18 +08001737
Andy Green6ee372f2012-04-09 15:09:01 +08001738 /* default to a poll() made out of select() */
1739 poll = emulated_poll;
David Galeano7b11fec2011-10-04 19:55:18 +08001740
Andy Green6ee372f2012-04-09 15:09:01 +08001741 /* if windows socket lib available, use his WSAPoll */
David Galeanocb193682013-01-09 15:29:00 +08001742 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
Andy Green6ee372f2012-04-09 15:09:01 +08001743 if (wsdll)
1744 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
Peter Hinz56885f32011-03-02 22:03:47 +00001745 }
1746#endif
1747
1748
Aaron Zinman4550f1d2013-01-10 12:35:18 +08001749 context = (struct libwebsocket_context *) malloc(sizeof(struct libwebsocket_context));
Peter Hinz56885f32011-03-02 22:03:47 +00001750 if (!context) {
Andy Green43db0452013-01-10 19:50:35 +08001751 lwsl_err("No memory for websocket context\n");
Andy Green90c7cbc2011-01-27 06:26:52 +00001752 return NULL;
1753 }
Peter Hinz56885f32011-03-02 22:03:47 +00001754 context->protocols = protocols;
1755 context->listen_port = port;
1756 context->http_proxy_port = 0;
1757 context->http_proxy_address[0] = '\0';
1758 context->options = options;
Andy Greendfb23042013-01-17 12:26:48 +08001759 /* to reduce this allocation, */
1760 context->max_fds = getdtablesize();
1761 lwsl_info(" max fd tracked: %u\n", context->max_fds);
1762
1763 context->fds = (struct pollfd *)malloc(sizeof(struct pollfd) * context->max_fds);
1764 if (context->fds == NULL) {
1765 lwsl_err("Unable to allocate fds array for %d connections\n", context->max_fds);
1766 free(context);
1767 return NULL;
1768 }
1769 context->lws_lookup = (struct libwebsocket **)malloc(sizeof(struct libwebsocke *) * context->max_fds);
1770 if (context->lws_lookup == NULL) {
1771 lwsl_err("Unable to allocate lws_lookup array for %d connections\n", context->max_fds);
1772 free(context->fds);
1773 free(context);
1774 return NULL;
1775 }
Peter Hinz56885f32011-03-02 22:03:47 +00001776 context->fds_count = 0;
Andy Greend6e09112011-03-05 16:12:15 +00001777 context->extensions = extensions;
Paulo Roberto Urio1e326632012-06-04 10:52:19 +08001778 context->last_timeout_check_s = 0;
Andy Greendfb23042013-01-17 12:26:48 +08001779 context->user_space = user;
Andy Green9659f372011-01-27 22:01:43 +00001780
Peter Hinz56885f32011-03-02 22:03:47 +00001781#ifdef WIN32
1782 context->fd_random = 0;
1783#else
1784 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1785 if (context->fd_random < 0) {
Andy Greendfb23042013-01-17 12:26:48 +08001786 free(context);
Andy Green43db0452013-01-10 19:50:35 +08001787 lwsl_err("Unable to open random device %s %d\n",
Peter Hinz56885f32011-03-02 22:03:47 +00001788 SYSTEM_RANDOM_FILEPATH, context->fd_random);
Andy Green44eee682011-02-10 09:32:24 +00001789 return NULL;
1790 }
Peter Hinz56885f32011-03-02 22:03:47 +00001791#endif
Andy Green44eee682011-02-10 09:32:24 +00001792
Peter Hinz56885f32011-03-02 22:03:47 +00001793#ifdef LWS_OPENSSL_SUPPORT
1794 context->use_ssl = 0;
1795 context->ssl_ctx = NULL;
1796 context->ssl_client_ctx = NULL;
Andy Green2e24da02011-03-05 16:12:04 +00001797 openssl_websocket_private_data_index = 0;
Peter Hinz56885f32011-03-02 22:03:47 +00001798#endif
Andy Green2ac5a6f2011-01-28 10:00:18 +00001799
Andy Green788c4a82012-10-22 12:29:57 +01001800 if (options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME) {
Andy Greena69f0512012-05-03 12:32:38 +08001801
Andy Green788c4a82012-10-22 12:29:57 +01001802 strcpy(context->canonical_hostname, "unknown");
Andy Greena69f0512012-05-03 12:32:38 +08001803
Andy Green788c4a82012-10-22 12:29:57 +01001804 } else {
1805
1806 /* find canonical hostname */
1807
1808 hostname[(sizeof hostname) - 1] = '\0';
1809 memset(&sa, 0, sizeof(sa));
1810 sa.sa_family = AF_INET;
1811 sa.sa_data[(sizeof sa.sa_data) - 1] = '\0';
1812 gethostname(hostname, (sizeof hostname) - 1);
1813
1814 n = 0;
1815
David Galeanoed3c8402013-01-10 10:45:24 +08001816 if (strlen(hostname) < sizeof(sa.sa_data) - 1) {
Andy Green788c4a82012-10-22 12:29:57 +01001817 strcpy(sa.sa_data, hostname);
Andy Green43db0452013-01-10 19:50:35 +08001818 // lwsl_debug("my host name is %s\n", sa.sa_data);
Andy Green788c4a82012-10-22 12:29:57 +01001819 n = getnameinfo(&sa, sizeof(sa), hostname,
1820 (sizeof hostname) - 1, NULL, 0, 0);
1821 }
1822
1823 if (!n) {
1824 strncpy(context->canonical_hostname, hostname,
1825 sizeof context->canonical_hostname - 1);
1826 context->canonical_hostname[
1827 sizeof context->canonical_hostname - 1] = '\0';
1828 } else
1829 strncpy(context->canonical_hostname, hostname,
1830 sizeof context->canonical_hostname - 1);
1831
Andy Green43db0452013-01-10 19:50:35 +08001832 // lwsl_debug("context->canonical_hostname = %s\n",
Andy Green788c4a82012-10-22 12:29:57 +01001833 // context->canonical_hostname);
Andy Greena69f0512012-05-03 12:32:38 +08001834 }
1835
Andy Green9659f372011-01-27 22:01:43 +00001836 /* split the proxy ads:port if given */
1837
1838 p = getenv("http_proxy");
1839 if (p) {
Peter Hinz56885f32011-03-02 22:03:47 +00001840 strncpy(context->http_proxy_address, p,
Andy Green6ee372f2012-04-09 15:09:01 +08001841 sizeof context->http_proxy_address - 1);
Peter Hinz56885f32011-03-02 22:03:47 +00001842 context->http_proxy_address[
1843 sizeof context->http_proxy_address - 1] = '\0';
Andy Green9659f372011-01-27 22:01:43 +00001844
Peter Hinz56885f32011-03-02 22:03:47 +00001845 p = strchr(context->http_proxy_address, ':');
Andy Green9659f372011-01-27 22:01:43 +00001846 if (p == NULL) {
Andy Green43db0452013-01-10 19:50:35 +08001847 lwsl_err("http_proxy needs to be ads:port\n");
Andy Green9659f372011-01-27 22:01:43 +00001848 return NULL;
1849 }
1850 *p = '\0';
Peter Hinz56885f32011-03-02 22:03:47 +00001851 context->http_proxy_port = atoi(p + 1);
Andy Green9659f372011-01-27 22:01:43 +00001852
Andy Green43db0452013-01-10 19:50:35 +08001853 lwsl_debug("Using proxy %s:%u\n",
Peter Hinz56885f32011-03-02 22:03:47 +00001854 context->http_proxy_address,
1855 context->http_proxy_port);
Andy Green9659f372011-01-27 22:01:43 +00001856 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001857
1858 if (port) {
1859
Andy Green3faa9c72010-11-08 17:03:03 +00001860#ifdef LWS_OPENSSL_SUPPORT
Peter Hinz56885f32011-03-02 22:03:47 +00001861 context->use_ssl = ssl_cert_filepath != NULL &&
Andy Green90c7cbc2011-01-27 06:26:52 +00001862 ssl_private_key_filepath != NULL;
Peter Hinz56885f32011-03-02 22:03:47 +00001863 if (context->use_ssl)
Andy Green43db0452013-01-10 19:50:35 +08001864 lwsl_info(" Compiled with SSL support, using it\n");
Andy Green90c7cbc2011-01-27 06:26:52 +00001865 else
Andy Green43db0452013-01-10 19:50:35 +08001866 lwsl_info(" Compiled with SSL support, not using it\n");
Andy Green3faa9c72010-11-08 17:03:03 +00001867
Andy Green90c7cbc2011-01-27 06:26:52 +00001868#else
1869 if (ssl_cert_filepath != NULL &&
1870 ssl_private_key_filepath != NULL) {
Andy Green43db0452013-01-10 19:50:35 +08001871 lwsl_info(" Not compiled for OpenSSl support!\n");
Andy Greene92cd172011-01-19 13:11:55 +00001872 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00001873 }
Andy Green43db0452013-01-10 19:50:35 +08001874 lwsl_info(" Compiled without SSL support, "
Andy Green90c7cbc2011-01-27 06:26:52 +00001875 "serving unencrypted\n");
1876#endif
1877 }
1878
1879 /* ignore SIGPIPE */
Peter Hinz56885f32011-03-02 22:03:47 +00001880#ifdef WIN32
1881#else
Andy Green90c7cbc2011-01-27 06:26:52 +00001882 signal(SIGPIPE, sigpipe_handler);
Peter Hinz56885f32011-03-02 22:03:47 +00001883#endif
Andy Green90c7cbc2011-01-27 06:26:52 +00001884
1885
1886#ifdef LWS_OPENSSL_SUPPORT
1887
1888 /* basic openssl init */
1889
1890 SSL_library_init();
1891
1892 OpenSSL_add_all_algorithms();
1893 SSL_load_error_strings();
1894
Andy Green2e24da02011-03-05 16:12:04 +00001895 openssl_websocket_private_data_index =
Andy Green6901cb32011-02-21 08:06:47 +00001896 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1897
Andy Green90c7cbc2011-01-27 06:26:52 +00001898 /*
1899 * Firefox insists on SSLv23 not SSLv3
1900 * Konq disables SSLv2 by default now, SSLv23 works
1901 */
1902
1903 method = (SSL_METHOD *)SSLv23_server_method();
1904 if (!method) {
Andy Green43db0452013-01-10 19:50:35 +08001905 lwsl_err("problem creating ssl method: %s\n",
Andy Green90c7cbc2011-01-27 06:26:52 +00001906 ERR_error_string(ERR_get_error(), ssl_err_buf));
1907 return NULL;
1908 }
Peter Hinz56885f32011-03-02 22:03:47 +00001909 context->ssl_ctx = SSL_CTX_new(method); /* create context */
1910 if (!context->ssl_ctx) {
Andy Green43db0452013-01-10 19:50:35 +08001911 lwsl_err("problem creating ssl context: %s\n",
Andy Green90c7cbc2011-01-27 06:26:52 +00001912 ERR_error_string(ERR_get_error(), ssl_err_buf));
1913 return NULL;
1914 }
1915
David Galeanocc148e42013-01-10 10:18:59 +08001916#ifdef SSL_OP_NO_COMPRESSION
David Galeanoc72f6f92013-01-10 10:11:57 +08001917 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
David Galeanocc148e42013-01-10 10:18:59 +08001918#endif
David Galeano77a677c2013-01-10 10:14:12 +08001919 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
David Galeanof177f2a2013-01-10 10:15:19 +08001920 SSL_CTX_set_cipher_list(context->ssl_ctx, CIPHERS_LIST_STRING);
David Galeanoc72f6f92013-01-10 10:11:57 +08001921
Andy Green90c7cbc2011-01-27 06:26:52 +00001922 /* client context */
Andy Green6ee372f2012-04-09 15:09:01 +08001923
1924 if (port == CONTEXT_PORT_NO_LISTEN) {
Peter Hinz56885f32011-03-02 22:03:47 +00001925 method = (SSL_METHOD *)SSLv23_client_method();
1926 if (!method) {
Andy Green43db0452013-01-10 19:50:35 +08001927 lwsl_err("problem creating ssl method: %s\n",
Peter Hinz56885f32011-03-02 22:03:47 +00001928 ERR_error_string(ERR_get_error(), ssl_err_buf));
1929 return NULL;
1930 }
1931 /* create context */
1932 context->ssl_client_ctx = SSL_CTX_new(method);
1933 if (!context->ssl_client_ctx) {
Andy Green43db0452013-01-10 19:50:35 +08001934 lwsl_err("problem creating ssl context: %s\n",
Peter Hinz56885f32011-03-02 22:03:47 +00001935 ERR_error_string(ERR_get_error(), ssl_err_buf));
1936 return NULL;
1937 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001938
David Galeanocc148e42013-01-10 10:18:59 +08001939#ifdef SSL_OP_NO_COMPRESSION
David Galeanoc72f6f92013-01-10 10:11:57 +08001940 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_NO_COMPRESSION);
David Galeanocc148e42013-01-10 10:18:59 +08001941#endif
David Galeano77a677c2013-01-10 10:14:12 +08001942 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
David Galeanof177f2a2013-01-10 10:15:19 +08001943 SSL_CTX_set_cipher_list(context->ssl_client_ctx, CIPHERS_LIST_STRING);
David Galeanoc72f6f92013-01-10 10:11:57 +08001944
Peter Hinz56885f32011-03-02 22:03:47 +00001945 /* openssl init for cert verification (for client sockets) */
David Galeano2f82be82013-01-09 16:25:54 +08001946 if (!ssl_ca_filepath) {
1947 if (!SSL_CTX_load_verify_locations(
1948 context->ssl_client_ctx, NULL,
1949 LWS_OPENSSL_CLIENT_CERTS))
Andy Green43db0452013-01-10 19:50:35 +08001950 lwsl_err(
David Galeano2f82be82013-01-09 16:25:54 +08001951 "Unable to load SSL Client certs from %s "
1952 "(set by --with-client-cert-dir= in configure) -- "
1953 " client ssl isn't going to work",
1954 LWS_OPENSSL_CLIENT_CERTS);
1955 } else
1956 if (!SSL_CTX_load_verify_locations(
1957 context->ssl_client_ctx, ssl_ca_filepath,
1958 NULL))
Andy Green43db0452013-01-10 19:50:35 +08001959 lwsl_err(
David Galeano2f82be82013-01-09 16:25:54 +08001960 "Unable to load SSL Client certs "
1961 "file from %s -- client ssl isn't "
1962 "going to work", ssl_ca_filepath);
Peter Hinz56885f32011-03-02 22:03:47 +00001963
1964 /*
1965 * callback allowing user code to load extra verification certs
1966 * helping the client to verify server identity
1967 */
1968
1969 context->protocols[0].callback(context, NULL,
1970 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1971 context->ssl_client_ctx, NULL, 0);
Andy Green90c7cbc2011-01-27 06:26:52 +00001972 }
Andy Green6ee372f2012-04-09 15:09:01 +08001973
Andy Greenc6bf2c22011-02-20 11:10:47 +00001974 /* as a server, are we requiring clients to identify themselves? */
1975
1976 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1977
1978 /* absolutely require the client cert */
Andy Green6ee372f2012-04-09 15:09:01 +08001979
Peter Hinz56885f32011-03-02 22:03:47 +00001980 SSL_CTX_set_verify(context->ssl_ctx,
Andy Green6901cb32011-02-21 08:06:47 +00001981 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1982 OpenSSL_verify_callback);
Andy Greenc6bf2c22011-02-20 11:10:47 +00001983
1984 /*
1985 * give user code a chance to load certs into the server
1986 * allowing it to verify incoming client certs
1987 */
1988
Peter Hinz56885f32011-03-02 22:03:47 +00001989 context->protocols[0].callback(context, NULL,
Andy Greenc6bf2c22011-02-20 11:10:47 +00001990 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
Peter Hinz56885f32011-03-02 22:03:47 +00001991 context->ssl_ctx, NULL, 0);
Andy Greenc6bf2c22011-02-20 11:10:47 +00001992 }
1993
Peter Hinz56885f32011-03-02 22:03:47 +00001994 if (context->use_ssl) {
Andy Green90c7cbc2011-01-27 06:26:52 +00001995
1996 /* openssl init for server sockets */
1997
Andy Green3faa9c72010-11-08 17:03:03 +00001998 /* set the local certificate from CertFile */
David Galeano9b3d4b22013-01-10 10:11:21 +08001999 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
2000 ssl_cert_filepath);
Andy Green3faa9c72010-11-08 17:03:03 +00002001 if (n != 1) {
Andy Green43db0452013-01-10 19:50:35 +08002002 lwsl_err("problem getting cert '%s': %s\n",
Andy Green3faa9c72010-11-08 17:03:03 +00002003 ssl_cert_filepath,
2004 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00002005 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002006 }
2007 /* set the private key from KeyFile */
Peter Hinz56885f32011-03-02 22:03:47 +00002008 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2009 ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
Andy Green43db0452013-01-10 19:50:35 +08002010 lwsl_err("ssl problem getting key '%s': %s\n",
Andy Green018d8eb2010-11-08 21:04:23 +00002011 ssl_private_key_filepath,
2012 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00002013 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002014 }
2015 /* verify private key */
Peter Hinz56885f32011-03-02 22:03:47 +00002016 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
Andy Green43db0452013-01-10 19:50:35 +08002017 lwsl_err("Private SSL key doesn't match cert\n");
Andy Greene92cd172011-01-19 13:11:55 +00002018 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002019 }
2020
2021 /* SSL is happy and has a cert it's content with */
2022 }
2023#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002024
Andy Greendf736162011-01-18 15:39:02 +00002025 /* selftest */
2026
2027 if (lws_b64_selftest())
Andy Greene92cd172011-01-19 13:11:55 +00002028 return NULL;
Andy Greendf736162011-01-18 15:39:02 +00002029
Andy Greenb45993c2010-12-18 15:13:50 +00002030 /* set up our external listening socket we serve on */
Andy Green8f037e42010-12-19 22:13:26 +00002031
Andy Green4739e5c2011-01-22 12:51:57 +00002032 if (port) {
Andy Green8f037e42010-12-19 22:13:26 +00002033
Andy Green4739e5c2011-01-22 12:51:57 +00002034 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2035 if (sockfd < 0) {
Andy Greenf7609e92013-01-14 13:10:55 +08002036 lwsl_err("ERROR opening socket\n");
Andy Green4739e5c2011-01-22 12:51:57 +00002037 return NULL;
2038 }
Andy Green775c0dd2010-10-29 14:15:22 +01002039
Andy Green4739e5c2011-01-22 12:51:57 +00002040 /* allow us to restart even if old sockets in TIME_WAIT */
Andy Green6ee372f2012-04-09 15:09:01 +08002041 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2042 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +00002043
2044 /* Disable Nagle */
2045 opt = 1;
Andy Green6ee372f2012-04-09 15:09:01 +08002046 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2047 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +00002048
Andy Green4739e5c2011-01-22 12:51:57 +00002049 bzero((char *) &serv_addr, sizeof(serv_addr));
2050 serv_addr.sin_family = AF_INET;
Peter Hinz56885f32011-03-02 22:03:47 +00002051 if (interf == NULL)
Andy Green32375b72011-02-19 08:32:53 +00002052 serv_addr.sin_addr.s_addr = INADDR_ANY;
2053 else
Peter Hinz56885f32011-03-02 22:03:47 +00002054 interface_to_sa(interf, &serv_addr,
Andy Green32375b72011-02-19 08:32:53 +00002055 sizeof(serv_addr));
Andy Green4739e5c2011-01-22 12:51:57 +00002056 serv_addr.sin_port = htons(port);
2057
2058 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2059 sizeof(serv_addr));
2060 if (n < 0) {
Andy Green43db0452013-01-10 19:50:35 +08002061 lwsl_err("ERROR on binding to port %d (%d %d)\n",
Andy Green8f037e42010-12-19 22:13:26 +00002062 port, n, errno);
Andy Green41c58032013-01-12 13:21:08 +08002063 close(sockfd);
Andy Green4739e5c2011-01-22 12:51:57 +00002064 return NULL;
2065 }
Andy Green0d338332011-02-12 11:57:43 +00002066
Aaron Zinman4550f1d2013-01-10 12:35:18 +08002067 wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
Andy Green41c58032013-01-12 13:21:08 +08002068 if (wsi == NULL) {
2069 lwsl_err("Out of mem\n");
2070 close(sockfd);
2071 return NULL;
2072 }
Aaron Zinman4550f1d2013-01-10 12:35:18 +08002073 memset(wsi, 0, sizeof (struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00002074 wsi->sock = sockfd;
Andy Greend6e09112011-03-05 16:12:15 +00002075 wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00002076 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
Andy Greendfb23042013-01-17 12:26:48 +08002077
2078 insert_wsi_socket_into_fds(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00002079
Andy Green65b0e912013-01-16 07:59:47 +08002080 context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO;
2081 context->listen_service_count = 0;
2082 context->listen_service_fd = sockfd;
2083
Andy Greena824d182013-01-15 20:52:29 +08002084 listen(sockfd, LWS_SOMAXCONN);
Andy Green43db0452013-01-10 19:50:35 +08002085 lwsl_info(" Listening on port %d\n", port);
Andy Green8f037e42010-12-19 22:13:26 +00002086 }
Andy Greenb45993c2010-12-18 15:13:50 +00002087
Andy Green6ee372f2012-04-09 15:09:01 +08002088 /*
2089 * drop any root privs for this process
2090 * to listen on port < 1023 we would have needed root, but now we are
2091 * listening, we don't want the power for anything else
2092 */
Peter Hinz56885f32011-03-02 22:03:47 +00002093#ifdef WIN32
2094#else
Andy Green3faa9c72010-11-08 17:03:03 +00002095 if (gid != -1)
2096 if (setgid(gid))
Andy Green43db0452013-01-10 19:50:35 +08002097 lwsl_warn("setgid: %s\n", strerror(errno));
Andy Green3faa9c72010-11-08 17:03:03 +00002098 if (uid != -1)
2099 if (setuid(uid))
Andy Green43db0452013-01-10 19:50:35 +08002100 lwsl_warn("setuid: %s\n", strerror(errno));
Peter Hinz56885f32011-03-02 22:03:47 +00002101#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002102
2103 /* set up our internal broadcast trigger sockets per-protocol */
2104
Peter Hinz56885f32011-03-02 22:03:47 +00002105 for (context->count_protocols = 0;
2106 protocols[context->count_protocols].callback;
2107 context->count_protocols++) {
Andy Green2d1301e2011-05-24 10:14:41 +01002108
Andy Green43db0452013-01-10 19:50:35 +08002109 lwsl_parser(" Protocol: %s\n",
2110 protocols[context->count_protocols].name);
Andy Green2d1301e2011-05-24 10:14:41 +01002111
Peter Hinz56885f32011-03-02 22:03:47 +00002112 protocols[context->count_protocols].owning_server = context;
2113 protocols[context->count_protocols].protocol_index =
2114 context->count_protocols;
Andy Greenb45993c2010-12-18 15:13:50 +00002115
2116 fd = socket(AF_INET, SOCK_STREAM, 0);
2117 if (fd < 0) {
Andy Greenf7609e92013-01-14 13:10:55 +08002118 lwsl_err("ERROR opening socket\n");
Andy Greene92cd172011-01-19 13:11:55 +00002119 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002120 }
Andy Green8f037e42010-12-19 22:13:26 +00002121
Andy Greenb45993c2010-12-18 15:13:50 +00002122 /* allow us to restart even if old sockets in TIME_WAIT */
Andy Green6ee372f2012-04-09 15:09:01 +08002123 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt,
2124 sizeof(opt));
Andy Greenb45993c2010-12-18 15:13:50 +00002125
2126 bzero((char *) &serv_addr, sizeof(serv_addr));
2127 serv_addr.sin_family = AF_INET;
2128 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2129 serv_addr.sin_port = 0; /* pick the port for us */
2130
2131 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2132 if (n < 0) {
Andy Green43db0452013-01-10 19:50:35 +08002133 lwsl_err("ERROR on binding to port %d (%d %d)\n",
Andy Greenb45993c2010-12-18 15:13:50 +00002134 port, n, errno);
Andy Greene92cd172011-01-19 13:11:55 +00002135 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002136 }
2137
2138 slen = sizeof cli_addr;
2139 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2140 if (n < 0) {
Andy Green43db0452013-01-10 19:50:35 +08002141 lwsl_err("getsockname failed\n");
Andy Greene92cd172011-01-19 13:11:55 +00002142 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002143 }
Peter Hinz56885f32011-03-02 22:03:47 +00002144 protocols[context->count_protocols].broadcast_socket_port =
Andy Greenb45993c2010-12-18 15:13:50 +00002145 ntohs(cli_addr.sin_port);
2146 listen(fd, 5);
2147
Andy Green43db0452013-01-10 19:50:35 +08002148 lwsl_debug(" Protocol %s broadcast socket %d\n",
Peter Hinz56885f32011-03-02 22:03:47 +00002149 protocols[context->count_protocols].name,
Andy Greenb45993c2010-12-18 15:13:50 +00002150 ntohs(cli_addr.sin_port));
2151
Andy Green0d338332011-02-12 11:57:43 +00002152 /* dummy wsi per broadcast proxy socket */
2153
Aaron Zinman4550f1d2013-01-10 12:35:18 +08002154 wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
Andy Green41c58032013-01-12 13:21:08 +08002155 if (wsi == NULL) {
2156 lwsl_err("Out of mem\n");
2157 close(fd);
2158 return NULL;
2159 }
Aaron Zinman4550f1d2013-01-10 12:35:18 +08002160 memset(wsi, 0, sizeof (struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00002161 wsi->sock = fd;
2162 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
Andy Greend6e09112011-03-05 16:12:15 +00002163 wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00002164 /* note which protocol we are proxying */
Peter Hinz56885f32011-03-02 22:03:47 +00002165 wsi->protocol_index_for_broadcast_proxy =
2166 context->count_protocols;
Andy Green0d338332011-02-12 11:57:43 +00002167
Andy Greendfb23042013-01-17 12:26:48 +08002168 insert_wsi_socket_into_fds(context, wsi);
Andy Greenb45993c2010-12-18 15:13:50 +00002169 }
2170
Andy Greena41314f2011-05-23 10:00:03 +01002171 /*
2172 * give all extensions a chance to create any per-context
2173 * allocations they need
2174 */
2175
2176 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2177 if (port)
2178 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
Andrew Chambersd5512172012-05-20 08:17:09 +08002179
2180 if (extensions) {
2181 while (extensions->callback) {
Andy Green43db0452013-01-10 19:50:35 +08002182 lwsl_ext(" Extension: %s\n", extensions->name);
Aaron Zinman4550f1d2013-01-10 12:35:18 +08002183 extensions->callback(context, extensions, NULL,
2184 (enum libwebsocket_extension_callback_reasons)m,
2185 NULL, NULL, 0);
Andrew Chambersd5512172012-05-20 08:17:09 +08002186 extensions++;
2187 }
Andy Greena41314f2011-05-23 10:00:03 +01002188 }
2189
Peter Hinz56885f32011-03-02 22:03:47 +00002190 return context;
Andy Greene92cd172011-01-19 13:11:55 +00002191}
Andy Greenb45993c2010-12-18 15:13:50 +00002192
Andy Green4739e5c2011-01-22 12:51:57 +00002193
Andy Greened11a022011-01-20 10:23:50 +00002194#ifndef LWS_NO_FORK
2195
Andy Greene92cd172011-01-19 13:11:55 +00002196/**
2197 * libwebsockets_fork_service_loop() - Optional helper function forks off
2198 * a process for the websocket server loop.
Andy Green6964bb52011-01-23 16:50:33 +00002199 * You don't have to use this but if not, you
2200 * have to make sure you are calling
2201 * libwebsocket_service periodically to service
2202 * the websocket traffic
Peter Hinz56885f32011-03-02 22:03:47 +00002203 * @context: server context returned by creation function
Andy Greene92cd172011-01-19 13:11:55 +00002204 */
Andy Greenb45993c2010-12-18 15:13:50 +00002205
Andy Greene92cd172011-01-19 13:11:55 +00002206int
Peter Hinz56885f32011-03-02 22:03:47 +00002207libwebsockets_fork_service_loop(struct libwebsocket_context *context)
Andy Greene92cd172011-01-19 13:11:55 +00002208{
Andy Greene92cd172011-01-19 13:11:55 +00002209 int fd;
2210 struct sockaddr_in cli_addr;
2211 int n;
Andy Green3221f922011-02-12 13:14:11 +00002212 int p;
Andy Greenb45993c2010-12-18 15:13:50 +00002213
Andy Greened11a022011-01-20 10:23:50 +00002214 n = fork();
2215 if (n < 0)
2216 return n;
2217
2218 if (!n) {
2219
2220 /* main process context */
2221
Andy Green3221f922011-02-12 13:14:11 +00002222 /*
2223 * set up the proxy sockets to allow broadcast from
2224 * service process context
2225 */
2226
Peter Hinz56885f32011-03-02 22:03:47 +00002227 for (p = 0; p < context->count_protocols; p++) {
Andy Greened11a022011-01-20 10:23:50 +00002228 fd = socket(AF_INET, SOCK_STREAM, 0);
2229 if (fd < 0) {
Andy Green43db0452013-01-10 19:50:35 +08002230 lwsl_err("Unable to create socket\n");
Andy Greened11a022011-01-20 10:23:50 +00002231 return -1;
2232 }
2233 cli_addr.sin_family = AF_INET;
2234 cli_addr.sin_port = htons(
Peter Hinz56885f32011-03-02 22:03:47 +00002235 context->protocols[p].broadcast_socket_port);
Andy Greened11a022011-01-20 10:23:50 +00002236 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2237 n = connect(fd, (struct sockaddr *)&cli_addr,
2238 sizeof cli_addr);
2239 if (n < 0) {
Andy Green43db0452013-01-10 19:50:35 +08002240 lwsl_err("Unable to connect to "
Andy Greened11a022011-01-20 10:23:50 +00002241 "broadcast socket %d, %s\n",
Andy Green3221f922011-02-12 13:14:11 +00002242 n, strerror(errno));
Andy Greened11a022011-01-20 10:23:50 +00002243 return -1;
2244 }
2245
Peter Hinz56885f32011-03-02 22:03:47 +00002246 context->protocols[p].broadcast_socket_user_fd = fd;
Andy Greened11a022011-01-20 10:23:50 +00002247 }
2248
Andy Greene92cd172011-01-19 13:11:55 +00002249 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00002250 }
2251
Artem Baguinski91531662011-12-14 22:14:03 +01002252#ifdef HAVE_SYS_PRCTL_H
Andy Greenb45993c2010-12-18 15:13:50 +00002253 /* we want a SIGHUP when our parent goes down */
2254 prctl(PR_SET_PDEATHSIG, SIGHUP);
Artem Baguinski91531662011-12-14 22:14:03 +01002255#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002256
2257 /* in this forked process, sit and service websocket connections */
Andy Green8f037e42010-12-19 22:13:26 +00002258
Artem Baguinski91531662011-12-14 22:14:03 +01002259 while (1) {
Peter Hinz56885f32011-03-02 22:03:47 +00002260 if (libwebsocket_service(context, 1000))
Andy Green3928f612012-07-20 12:58:38 +08002261 break;
Andy Green5e8967a2012-10-17 20:10:44 +08002262//#ifndef HAVE_SYS_PRCTL_H
Artem Baguinski91531662011-12-14 22:14:03 +01002263/*
2264 * on systems without prctl() (i.e. anything but linux) we can notice that our
2265 * parent is dead if getppid() returns 1. FIXME apparently this is not true for
2266 * solaris, could remember ppid right after fork and wait for it to change.
2267 */
2268
2269 if (getppid() == 1)
2270 break;
Andy Green5e8967a2012-10-17 20:10:44 +08002271//#endif
Artem Baguinski91531662011-12-14 22:14:03 +01002272 }
2273
Andy Green8f037e42010-12-19 22:13:26 +00002274
Andy Green3928f612012-07-20 12:58:38 +08002275 return 1;
Andy Greenff95d7a2010-10-28 22:36:01 +01002276}
2277
Andy Greened11a022011-01-20 10:23:50 +00002278#endif
2279
Andy Greenb45993c2010-12-18 15:13:50 +00002280/**
2281 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
Andy Green8f037e42010-12-19 22:13:26 +00002282 * connection.
Andy Greenb45993c2010-12-18 15:13:50 +00002283 * @wsi: pointer to struct websocket you want to know the protocol of
2284 *
Andy Green8f037e42010-12-19 22:13:26 +00002285 *
2286 * This is useful to get the protocol to broadcast back to from inside
Andy Greenb45993c2010-12-18 15:13:50 +00002287 * the callback.
2288 */
Andy Greenab990e42010-10-31 12:42:52 +00002289
Andy Greenb45993c2010-12-18 15:13:50 +00002290const struct libwebsocket_protocols *
2291libwebsockets_get_protocol(struct libwebsocket *wsi)
2292{
2293 return wsi->protocol;
2294}
2295
2296/**
Andy Greene92cd172011-01-19 13:11:55 +00002297 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
Andy Green8f037e42010-12-19 22:13:26 +00002298 * connections of the given protocol.
Andy Greenb45993c2010-12-18 15:13:50 +00002299 * @protocol: pointer to the protocol you will broadcast to all members of
2300 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
Andy Green8f037e42010-12-19 22:13:26 +00002301 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
2302 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
2303 * case you are calling this function from callback context.
Andy Greenb45993c2010-12-18 15:13:50 +00002304 * @len: length of payload data in buf, starting from buf.
Andy Green8f037e42010-12-19 22:13:26 +00002305 *
2306 * This function allows bulk sending of a packet to every connection using
Andy Greenb45993c2010-12-18 15:13:50 +00002307 * the given protocol. It does not send the data directly; instead it calls
2308 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
2309 * wants to actually send the data for that connection, the callback itself
2310 * should call libwebsocket_write().
2311 *
2312 * libwebsockets_broadcast() can be called from another fork context without
2313 * having to take any care about data visibility between the processes, it'll
2314 * "just work".
2315 */
2316
2317
2318int
Andy Green8f037e42010-12-19 22:13:26 +00002319libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
Andy Greenb45993c2010-12-18 15:13:50 +00002320 unsigned char *buf, size_t len)
2321{
Peter Hinz56885f32011-03-02 22:03:47 +00002322 struct libwebsocket_context *context = protocol->owning_server;
Andy Greenb45993c2010-12-18 15:13:50 +00002323 int n;
Andy Green6ee372f2012-04-09 15:09:01 +08002324 struct libwebsocket *wsi;
Andy Greenb45993c2010-12-18 15:13:50 +00002325
2326 if (!protocol->broadcast_socket_user_fd) {
2327 /*
Andy Greene92cd172011-01-19 13:11:55 +00002328 * We are either running unforked / flat, or we are being
2329 * called from poll thread context
Andy Greenb45993c2010-12-18 15:13:50 +00002330 * eg, from a callback. In that case don't use sockets for
2331 * broadcast IPC (since we can't open a socket connection to
2332 * a socket listening on our own thread) but directly do the
2333 * send action.
2334 *
2335 * Locking is not needed because we are by definition being
2336 * called in the poll thread context and are serialized.
2337 */
2338
Andy Greendfb23042013-01-17 12:26:48 +08002339 for (n = 0; n < context->fds_count; n++) {
Andy Greenb45993c2010-12-18 15:13:50 +00002340
Andy Greendfb23042013-01-17 12:26:48 +08002341 wsi = context->lws_lookup[context->fds[n].fd];
2342 if (!wsi)
2343 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00002344
Andy Greendfb23042013-01-17 12:26:48 +08002345 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
2346 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00002347
Andy Greendfb23042013-01-17 12:26:48 +08002348 /*
2349 * never broadcast to non-established connections
2350 */
2351 if (wsi->state != WSI_STATE_ESTABLISHED)
2352 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00002353
Andy Greendfb23042013-01-17 12:26:48 +08002354 /* only broadcast to guys using
2355 * requested protocol
2356 */
2357 if (wsi->protocol != protocol)
2358 continue;
Andy Green0d338332011-02-12 11:57:43 +00002359
Andy Greendfb23042013-01-17 12:26:48 +08002360 wsi->protocol->callback(context, wsi,
2361 LWS_CALLBACK_BROADCAST,
2362 wsi->user_space,
2363 buf, len);
Andy Greenb45993c2010-12-18 15:13:50 +00002364 }
2365
2366 return 0;
2367 }
2368
Andy Green0ca6a172010-12-19 20:50:01 +00002369 /*
2370 * We're being called from a different process context than the server
2371 * loop. Instead of broadcasting directly, we send our
2372 * payload on a socket to do the IPC; the server process will serialize
2373 * the broadcast action in its main poll() loop.
2374 *
2375 * There's one broadcast socket listening for each protocol supported
2376 * set up when the websocket server initializes
2377 */
2378
Andy Green6964bb52011-01-23 16:50:33 +00002379 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
Andy Greenb45993c2010-12-18 15:13:50 +00002380
2381 return n;
2382}
Andy Green82c3d542011-03-07 21:16:31 +00002383
2384int
2385libwebsocket_is_final_fragment(struct libwebsocket *wsi)
2386{
2387 return wsi->final;
2388}
Alex Bligh49146db2011-11-07 17:19:25 +08002389
David Galeanoe2cf9922013-01-09 18:06:55 +08002390unsigned char
2391libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
2392{
2393 return wsi->rsv;
2394}
2395
Alex Bligh49146db2011-11-07 17:19:25 +08002396void *
2397libwebsocket_ensure_user_space(struct libwebsocket *wsi)
2398{
2399 /* allocate the per-connection user memory (if any) */
2400
2401 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
2402 wsi->user_space = malloc(
2403 wsi->protocol->per_session_data_size);
2404 if (wsi->user_space == NULL) {
Andy Green43db0452013-01-10 19:50:35 +08002405 lwsl_err("Out of memory for conn user space\n");
Alex Bligh49146db2011-11-07 17:19:25 +08002406 return NULL;
2407 }
Andy Green6ee372f2012-04-09 15:09:01 +08002408 memset(wsi->user_space, 0,
2409 wsi->protocol->per_session_data_size);
Alex Bligh49146db2011-11-07 17:19:25 +08002410 }
2411 return wsi->user_space;
2412}
Andy Green43db0452013-01-10 19:50:35 +08002413
Andy Greende8f27a2013-01-12 09:17:42 +08002414
2415static void lwsl_emit_stderr(const char *line)
2416{
2417 fprintf(stderr, "%s", line);
2418}
2419
Andy Green43db0452013-01-10 19:50:35 +08002420void _lws_log(int filter, const char *format, ...)
2421{
Andy Greende8f27a2013-01-12 09:17:42 +08002422 char buf[256];
Andy Green43db0452013-01-10 19:50:35 +08002423 va_list ap;
2424 int n;
Andy Greende8f27a2013-01-12 09:17:42 +08002425 int pos = 0;
Andy Green8a265092013-01-12 09:25:07 +08002426 struct timeval tv;
Andy Green43db0452013-01-10 19:50:35 +08002427
2428 if (!(log_level & filter))
2429 return;
2430
Andy Green8a265092013-01-12 09:25:07 +08002431 gettimeofday(&tv, NULL);
2432
Andy Green43db0452013-01-10 19:50:35 +08002433 for (n = 0; n < LLL_COUNT; n++)
2434 if (filter == (1 << n)) {
Andy Greeneff73742013-01-17 15:02:02 +08002435 pos = sprintf(buf, "[%ld:%04d] %s: ", tv.tv_sec,
2436 (int)(tv.tv_usec / 100), log_level_names[n]);
Andy Green43db0452013-01-10 19:50:35 +08002437 break;
2438 }
2439
2440 va_start(ap, format);
Andy Greende8f27a2013-01-12 09:17:42 +08002441 vsnprintf(buf + pos, (sizeof buf) - pos, format, ap);
2442 buf[(sizeof buf) - 1] = '\0';
2443 va_end(ap);
2444
2445 lwsl_emit(buf);
Andy Green43db0452013-01-10 19:50:35 +08002446}
2447
2448/**
2449 * lws_set_log_level() - Set the logging bitfield
2450 * @level: OR together the LLL_ debug contexts you want output from
Andy Greende8f27a2013-01-12 09:17:42 +08002451 * @log_emit_function: NULL to leave it as it is, or a user-supplied
2452 * function to perform log string emission instead of
2453 * the default stderr one.
Andy Green43db0452013-01-10 19:50:35 +08002454 *
Andy Greende8f27a2013-01-12 09:17:42 +08002455 * log level defaults to "err" and "warn" contexts enabled only and
2456 * emission on stderr.
Andy Green43db0452013-01-10 19:50:35 +08002457 */
2458
Andy Greende8f27a2013-01-12 09:17:42 +08002459void lws_set_log_level(int level, void (*log_emit_function)(const char *line))
Andy Green43db0452013-01-10 19:50:35 +08002460{
2461 log_level = level;
Andy Greende8f27a2013-01-12 09:17:42 +08002462 if (log_emit_function)
2463 lwsl_emit = log_emit_function;
Andy Green43db0452013-01-10 19:50:35 +08002464}