blob: 40b9a20d5731689e80838fa558edeee58b38c2a6 [file] [log] [blame]
Andy Green05a0a7b2010-10-31 17:51:39 +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 Green32375b72011-02-19 08:32:53 +000023#include <ifaddrs.h>
Andy Greenff95d7a2010-10-28 22:36:01 +010024
Andy Greenbe93fef2011-02-14 20:25:43 +000025/*
26 * In-place str to lower case
27 */
28
29static void
30strtolower(char *s)
31{
32 while (*s) {
33 *s = tolower(*s);
34 s++;
35 }
36}
37
Andy Green0d338332011-02-12 11:57:43 +000038/* file descriptor hash management */
39
40struct libwebsocket *
41wsi_from_fd(struct libwebsocket_context *this, int fd)
42{
43 int h = LWS_FD_HASH(fd);
44 int n = 0;
45
46 for (n = 0; n < this->fd_hashtable[h].length; n++)
47 if (this->fd_hashtable[h].wsi[n]->sock == fd)
48 return this->fd_hashtable[h].wsi[n];
49
50 return NULL;
51}
52
53int
54insert_wsi(struct libwebsocket_context *this, struct libwebsocket *wsi)
55{
56 int h = LWS_FD_HASH(wsi->sock);
57
58 if (this->fd_hashtable[h].length == MAX_CLIENTS - 1) {
59 fprintf(stderr, "hash table overflow\n");
60 return 1;
61 }
62
63 this->fd_hashtable[h].wsi[this->fd_hashtable[h].length++] = wsi;
64
65 return 0;
66}
67
68int
69delete_from_fd(struct libwebsocket_context *this, int fd)
70{
71 int h = LWS_FD_HASH(fd);
72 int n = 0;
73
74 for (n = 0; n < this->fd_hashtable[h].length; n++)
75 if (this->fd_hashtable[h].wsi[n]->sock == fd) {
76 while (n < this->fd_hashtable[h].length) {
77 this->fd_hashtable[h].wsi[n] =
78 this->fd_hashtable[h].wsi[n + 1];
79 n++;
80 }
81 this->fd_hashtable[h].length--;
82
83 return 0;
84 }
85
86 fprintf(stderr, "Failed to find fd %d requested for "
87 "delete in hashtable\n", fd);
88 return 1;
89}
90
Andy Green1f9bf522011-02-14 21:14:37 +000091#ifdef LWS_OPENSSL_SUPPORT
92static void
93libwebsockets_decode_ssl_error(void)
94{
95 char buf[256];
96 u_long err;
97
98 while ((err = ERR_get_error()) != 0) {
99 ERR_error_string_n(err, buf, sizeof(buf));
100 fprintf(stderr, "*** %s\n", buf);
101 }
102}
103#endif
Andy Green0d338332011-02-12 11:57:43 +0000104
Andy Green32375b72011-02-19 08:32:53 +0000105
106static int
107interface_to_sa(const char* ifname, struct sockaddr_in *addr, size_t addrlen)
108{
109 int rc = -1;
110 struct ifaddrs *ifr;
111 struct ifaddrs *ifc;
112 struct sockaddr_in *sin;
113
114 getifaddrs(&ifr);
115 for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
116 if (strcmp(ifc->ifa_name, ifname))
117 continue;
118 if (ifc->ifa_addr == NULL)
119 continue;
120 sin = (struct sockaddr_in *)ifc->ifa_addr;
121 if (sin->sin_family != AF_INET)
122 continue;
123 memcpy(addr, sin, addrlen);
124 rc = 0;
125 }
126
127 freeifaddrs(ifr);
128
129 return rc;
130}
131
Andy Green8f037e42010-12-19 22:13:26 +0000132void
Andy Green4b6fbe12011-02-14 08:03:48 +0000133libwebsocket_close_and_free_session(struct libwebsocket_context *this,
134 struct libwebsocket *wsi)
Andy Green251f6fa2010-11-03 11:13:06 +0000135{
Andy Greenb45993c2010-12-18 15:13:50 +0000136 int n;
Andy Green62c54d22011-02-14 09:14:25 +0000137 int old_state;
Andy Green5e1fa172011-02-10 09:07:05 +0000138 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
139 LWS_SEND_BUFFER_POST_PADDING];
Andy Greenb45993c2010-12-18 15:13:50 +0000140
Andy Green4b6fbe12011-02-14 08:03:48 +0000141 if (!wsi)
Andy Greenb45993c2010-12-18 15:13:50 +0000142 return;
143
Andy Green62c54d22011-02-14 09:14:25 +0000144 old_state = wsi->state;
Andy Green251f6fa2010-11-03 11:13:06 +0000145
Andy Green62c54d22011-02-14 09:14:25 +0000146 if (old_state == WSI_STATE_DEAD_SOCKET)
Andy Green5e1fa172011-02-10 09:07:05 +0000147 return;
148
Andy Green4b6fbe12011-02-14 08:03:48 +0000149 /* remove this fd from wsi mapping hashtable */
150
151 delete_from_fd(this, wsi->sock);
152
153 /* delete it from the internal poll list if still present */
154
155 for (n = 0; n < this->fds_count; n++) {
156 if (this->fds[n].fd != wsi->sock)
157 continue;
158 while (n < this->fds_count - 1) {
159 this->fds[n] = this->fds[n + 1];
160 n++;
161 }
162 this->fds_count--;
163 /* we only have to deal with one */
164 n = this->fds_count;
165 }
166
167 /* remove also from external POLL support via protocol 0 */
168
Andy Green62c54d22011-02-14 09:14:25 +0000169 this->protocols[0].callback(this, wsi,
Andy Green4b6fbe12011-02-14 08:03:48 +0000170 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
171
Andy Green5e1fa172011-02-10 09:07:05 +0000172 /*
173 * signal we are closing, libsocket_write will
174 * add any necessary version-specific stuff. If the write fails,
175 * no worries we are closing anyway. If we didn't initiate this
176 * close, then our state has been changed to
Andy Green4b6fbe12011-02-14 08:03:48 +0000177 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this
Andy Green5e1fa172011-02-10 09:07:05 +0000178 */
179
Andy Green62c54d22011-02-14 09:14:25 +0000180 if (old_state == WSI_STATE_ESTABLISHED)
Andy Green5e1fa172011-02-10 09:07:05 +0000181 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
182 LWS_WRITE_CLOSE);
183
Andy Green251f6fa2010-11-03 11:13:06 +0000184 wsi->state = WSI_STATE_DEAD_SOCKET;
185
Andy Green4b6fbe12011-02-14 08:03:48 +0000186 /* tell the user it's all over for this guy */
187
Andy Green62c54d22011-02-14 09:14:25 +0000188 if (wsi->protocol->callback && old_state == WSI_STATE_ESTABLISHED)
189 wsi->protocol->callback(this, wsi, LWS_CALLBACK_CLOSED,
Andy Greene77ddd82010-11-13 10:03:47 +0000190 wsi->user_space, NULL, 0);
Andy Green251f6fa2010-11-03 11:13:06 +0000191
Andy Green4b6fbe12011-02-14 08:03:48 +0000192 /* free up his allocations */
193
Andy Green251f6fa2010-11-03 11:13:06 +0000194 for (n = 0; n < WSI_TOKEN_COUNT; n++)
195 if (wsi->utf8_token[n].token)
196 free(wsi->utf8_token[n].token);
197
Andy Green0ca6a172010-12-19 20:50:01 +0000198/* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
Andy Green251f6fa2010-11-03 11:13:06 +0000199
Andy Green3faa9c72010-11-08 17:03:03 +0000200#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +0000201 if (wsi->ssl) {
Andy Green3faa9c72010-11-08 17:03:03 +0000202 n = SSL_get_fd(wsi->ssl);
203 SSL_shutdown(wsi->ssl);
204 close(n);
205 SSL_free(wsi->ssl);
206 } else {
207#endif
208 shutdown(wsi->sock, SHUT_RDWR);
209 close(wsi->sock);
210#ifdef LWS_OPENSSL_SUPPORT
211 }
212#endif
Andy Green4f3943a2010-11-12 10:44:16 +0000213 if (wsi->user_space)
214 free(wsi->user_space);
215
Andy Green251f6fa2010-11-03 11:13:06 +0000216 free(wsi);
217}
218
Andy Green07034092011-02-13 08:37:12 +0000219/**
Andy Greenf7ee5492011-02-13 09:04:21 +0000220 * libwebsockets_hangup_on_client() - Server calls to terminate client
221 * connection
222 * @this: libwebsockets context
223 * @fd: Connection socket descriptor
224 */
225
226void
227libwebsockets_hangup_on_client(struct libwebsocket_context *this, int fd)
228{
229 struct libwebsocket *wsi = wsi_from_fd(this, fd);
Andy Greende6ab322011-02-13 09:15:10 +0000230 int n;
Andy Greenf7ee5492011-02-13 09:04:21 +0000231
232 if (wsi == NULL)
233 return;
234
Andy Greende6ab322011-02-13 09:15:10 +0000235 delete_from_fd(this, fd);
236
237 for (n = 0; n < this->fds_count - 1; n++)
238 if (this->fds[n].fd == fd) {
239 while (n < this->fds_count - 1) {
240 this->fds[n] = this->fds[n + 1];
241 n++;
242 }
243 n = this->fds_count;
244 this->fds_count--;
245 }
246
Andy Green4b6fbe12011-02-14 08:03:48 +0000247 libwebsocket_close_and_free_session(this, wsi);
Andy Greenf7ee5492011-02-13 09:04:21 +0000248}
249
250
251/**
Andy Green07034092011-02-13 08:37:12 +0000252 * libwebsockets_get_peer_addresses() - Get client address information
253 * @fd: Connection socket descriptor
254 * @name: Buffer to take client address name
255 * @name_len: Length of client address name buffer
256 * @rip: Buffer to take client address IP qotted quad
257 * @rip_len: Length of client address IP buffer
258 *
259 * This function fills in @name and @rip with the name and IP of
260 * the client connected with socket descriptor @fd. Names may be
261 * truncated if there is not enough room. If either cannot be
262 * determined, they will be returned as valid zero-length strings.
263 */
264
265void
266libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
267 char *rip, int rip_len)
268{
269 unsigned int len;
270 struct sockaddr_in sin;
271 struct hostent *host;
272 struct hostent *host1;
273 char ip[128];
274 char *p;
275 int n;
276
277 rip[0] = '\0';
278 name[0] = '\0';
279
280 len = sizeof sin;
281 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
282 perror("getpeername");
283 return;
284 }
285
286 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
287 AF_INET);
288 if (host == NULL) {
289 perror("gethostbyaddr");
290 return;
291 }
292
293 strncpy(name, host->h_name, name_len);
294 name[name_len - 1] = '\0';
295
296 host1 = gethostbyname(host->h_name);
297 if (host1 == NULL)
298 return;
299 p = (char *)host1;
300 n = 0;
301 while (p != NULL) {
302 p = host1->h_addr_list[n++];
303 if (p == NULL)
304 continue;
305 if (host1->h_addrtype != AF_INET)
306 continue;
307
308 sprintf(ip, "%d.%d.%d.%d",
309 p[0], p[1], p[2], p[3]);
310 p = NULL;
311 strncpy(rip, ip, rip_len);
312 rip[rip_len - 1] = '\0';
313 }
314}
Andy Green9f990342011-02-12 11:57:45 +0000315
316/**
317 * libwebsocket_service_fd() - Service polled socket with something waiting
318 * @this: Websocket context
319 * @pollfd: The pollfd entry describing the socket fd and which events
320 * happened.
321 *
322 * This function closes any active connections and then frees the
323 * context. After calling this, any further use of the context is
324 * undefined.
325 */
326
327int
Andy Green0d338332011-02-12 11:57:43 +0000328libwebsocket_service_fd(struct libwebsocket_context *this,
329 struct pollfd *pollfd)
Andy Greenb45993c2010-12-18 15:13:50 +0000330{
331 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
332 LWS_SEND_BUFFER_POST_PADDING];
Andy Greena71eafc2011-02-14 17:59:43 +0000333 struct libwebsocket *wsi;
Andy Green0d338332011-02-12 11:57:43 +0000334 struct libwebsocket *new_wsi;
Andy Greenb45993c2010-12-18 15:13:50 +0000335 int n;
Andy Green0d338332011-02-12 11:57:43 +0000336 int m;
Andy Greenb45993c2010-12-18 15:13:50 +0000337 size_t len;
Andy Green0d338332011-02-12 11:57:43 +0000338 int accept_fd;
339 unsigned int clilen;
340 struct sockaddr_in cli_addr;
Andy Greena71eafc2011-02-14 17:59:43 +0000341 struct timeval tv;
Andy Greenbe93fef2011-02-14 20:25:43 +0000342 static const char magic_websocket_guid[] =
343 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
344 static const char magic_websocket_04_masking_guid[] =
345 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
346 char hash[20];
347 char pkt[1024];
348 char *p = &pkt[0];
349 const char *pc;
350 int okay = 0;
351#ifdef LWS_OPENSSL_SUPPORT
352 char ssl_err_buf[512];
353#endif
Andy Greena71eafc2011-02-14 17:59:43 +0000354 /*
355 * you can call us with pollfd = NULL to just allow the once-per-second
356 * global timeout checks; if less than a second since the last check
357 * it returns immediately then.
358 */
359
360 gettimeofday(&tv, NULL);
361
362 if (this->last_timeout_check_s != tv.tv_sec) {
363 this->last_timeout_check_s = tv.tv_sec;
364
365 /* global timeout check once per second */
366
367 for (n = 0; n < this->fds_count; n++) {
368 wsi = wsi_from_fd(this, this->fds[n].fd);
369 if (!wsi->pending_timeout)
370 continue;
371
372 /*
373 * if we went beyond the allowed time, kill the
374 * connection
375 */
376
377 if (tv.tv_sec > wsi->pending_timeout_limit)
378 libwebsocket_close_and_free_session(this, wsi);
379 }
380 }
381
382 /* just here for timeout management? */
383
384 if (pollfd == NULL)
385 return 0;
386
387 /* no, here to service a socket descriptor */
388
389 wsi = wsi_from_fd(this, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +0000390
Andy Green0d338332011-02-12 11:57:43 +0000391 if (wsi == NULL)
392 return 1;
Andy Green8f037e42010-12-19 22:13:26 +0000393
Andy Green0d338332011-02-12 11:57:43 +0000394 switch (wsi->mode) {
395 case LWS_CONNMODE_SERVER_LISTENER:
396
397 /* pollin means a client has connected to us then */
398
399 if (!pollfd->revents & POLLIN)
400 break;
401
402 /* listen socket got an unencrypted connection... */
403
404 clilen = sizeof(cli_addr);
405 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
406 &clilen);
407 if (accept_fd < 0) {
408 fprintf(stderr, "ERROR on accept");
409 break;
410 }
411
412 if (this->fds_count >= MAX_CLIENTS) {
Andy Green3221f922011-02-12 13:14:11 +0000413 fprintf(stderr, "too busy to accept new client\n");
Andy Green0d338332011-02-12 11:57:43 +0000414 close(accept_fd);
415 break;
416 }
417
Andy Green07034092011-02-13 08:37:12 +0000418 /*
419 * look at who we connected to and give user code a chance
420 * to reject based on client IP. There's no protocol selected
421 * yet so we issue this to protocols[0]
422 */
423
Andy Green62c54d22011-02-14 09:14:25 +0000424 if ((this->protocols[0].callback)(this, wsi,
Andy Green07034092011-02-13 08:37:12 +0000425 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
426 (void*)(long)accept_fd, NULL, 0)) {
427 fprintf(stderr, "Callback denied network connection\n");
428 close(accept_fd);
429 break;
430 }
431
Andy Green0d338332011-02-12 11:57:43 +0000432 /* accepting connection to main listener */
433
434 new_wsi = malloc(sizeof(struct libwebsocket));
435 if (new_wsi == NULL) {
436 fprintf(stderr, "Out of memory for new connection\n");
437 break;
438 }
439
440 memset(new_wsi, 0, sizeof (struct libwebsocket));
441 new_wsi->sock = accept_fd;
Andy Greena71eafc2011-02-14 17:59:43 +0000442 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
Andy Green0d338332011-02-12 11:57:43 +0000443
444#ifdef LWS_OPENSSL_SUPPORT
445 new_wsi->ssl = NULL;
Andy Green0d338332011-02-12 11:57:43 +0000446
447 if (this->use_ssl) {
448
449 new_wsi->ssl = SSL_new(this->ssl_ctx);
450 if (new_wsi->ssl == NULL) {
451 fprintf(stderr, "SSL_new failed: %s\n",
452 ERR_error_string(SSL_get_error(
453 new_wsi->ssl, 0), NULL));
Andy Green1f9bf522011-02-14 21:14:37 +0000454 libwebsockets_decode_ssl_error();
Andy Green0d338332011-02-12 11:57:43 +0000455 free(new_wsi);
456 break;
457 }
458
459 SSL_set_fd(new_wsi->ssl, accept_fd);
460
461 n = SSL_accept(new_wsi->ssl);
462 if (n != 1) {
463 /*
464 * browsers seem to probe with various
465 * ssl params which fail then retry
466 * and succeed
467 */
468 debug("SSL_accept failed skt %u: %s\n",
469 pollfd->fd,
470 ERR_error_string(SSL_get_error(
471 new_wsi->ssl, n), NULL));
472 SSL_free(
473 new_wsi->ssl);
474 free(new_wsi);
475 break;
476 }
Andy Greenc6bf2c22011-02-20 11:10:47 +0000477
Andy Green0d338332011-02-12 11:57:43 +0000478 debug("accepted new SSL conn "
479 "port %u on fd=%d SSL ver %s\n",
480 ntohs(cli_addr.sin_port), accept_fd,
481 SSL_get_version(new_wsi->ssl));
482
483 } else
484#endif
485 debug("accepted new conn port %u on fd=%d\n",
486 ntohs(cli_addr.sin_port), accept_fd);
487
488 /* intialize the instance struct */
489
490 new_wsi->state = WSI_STATE_HTTP;
491 new_wsi->name_buffer_pos = 0;
492 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
493
494 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
495 new_wsi->utf8_token[n].token = NULL;
496 new_wsi->utf8_token[n].token_len = 0;
497 }
498
499 /*
500 * these can only be set once the protocol is known
501 * we set an unestablished connection's protocol pointer
502 * to the start of the supported list, so it can look
503 * for matching ones during the handshake
504 */
505 new_wsi->protocol = this->protocols;
506 new_wsi->user_space = NULL;
507
508 /*
509 * Default protocol is 76 / 00
510 * After 76, there's a header specified to inform which
511 * draft the client wants, when that's seen we modify
512 * the individual connection's spec revision accordingly
513 */
514 new_wsi->ietf_spec_revision = 0;
515
516 insert_wsi(this, new_wsi);
517
Andy Green0d338332011-02-12 11:57:43 +0000518 /*
519 * make sure NO events are seen yet on this new socket
520 * (otherwise we inherit old fds[client].revents from
521 * previous socket there and die mysteriously! )
522 */
523 this->fds[this->fds_count].revents = 0;
524
525 this->fds[this->fds_count].events = POLLIN;
526 this->fds[this->fds_count++].fd = accept_fd;
527
Andy Green3221f922011-02-12 13:14:11 +0000528 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +0000529 this->protocols[0].callback(this, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +0000530 LWS_CALLBACK_ADD_POLL_FD,
531 (void *)(long)accept_fd, NULL, POLLIN);
532
Andy Green0d338332011-02-12 11:57:43 +0000533 break;
534
535 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
536
537 /* as we are listening, POLLIN means accept() is needed */
538
539 if (!pollfd->revents & POLLIN)
540 break;
541
542 /* listen socket got an unencrypted connection... */
543
544 clilen = sizeof(cli_addr);
545 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
546 &clilen);
547 if (accept_fd < 0) {
548 fprintf(stderr, "ERROR on accept");
549 break;
550 }
551
552 if (this->fds_count >= MAX_CLIENTS) {
Andy Green3221f922011-02-12 13:14:11 +0000553 fprintf(stderr, "too busy to accept new broadcast "
554 "proxy client\n");
Andy Green0d338332011-02-12 11:57:43 +0000555 close(accept_fd);
556 break;
557 }
558
559 /* create a dummy wsi for the connection and add it */
560
561 new_wsi = malloc(sizeof(struct libwebsocket));
562 memset(new_wsi, 0, sizeof (struct libwebsocket));
563 new_wsi->sock = accept_fd;
564 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
565 new_wsi->state = WSI_STATE_ESTABLISHED;
566 /* note which protocol we are proxying */
567 new_wsi->protocol_index_for_broadcast_proxy =
568 wsi->protocol_index_for_broadcast_proxy;
569 insert_wsi(this, new_wsi);
570
571 /* add connected socket to internal poll array */
572
573 this->fds[this->fds_count].revents = 0;
574 this->fds[this->fds_count].events = POLLIN;
575 this->fds[this->fds_count++].fd = accept_fd;
576
Andy Green3221f922011-02-12 13:14:11 +0000577 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +0000578 this->protocols[0].callback(this, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +0000579 LWS_CALLBACK_ADD_POLL_FD,
580 (void *)(long)accept_fd, NULL, POLLIN);
581
Andy Green0d338332011-02-12 11:57:43 +0000582 break;
583
584 case LWS_CONNMODE_BROADCAST_PROXY:
Andy Green8f037e42010-12-19 22:13:26 +0000585
Andy Greenb45993c2010-12-18 15:13:50 +0000586 /* handle session socket closed */
Andy Green8f037e42010-12-19 22:13:26 +0000587
Andy Green0d338332011-02-12 11:57:43 +0000588 if (pollfd->revents & (POLLERR | POLLHUP)) {
Andy Green8f037e42010-12-19 22:13:26 +0000589
Andy Green0d338332011-02-12 11:57:43 +0000590 debug("Session Socket %p (fd=%d) dead\n",
Timothy J Fontaineb86d64e2011-02-14 17:55:27 +0000591 (void *)wsi, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +0000592
Andy Green4b6fbe12011-02-14 08:03:48 +0000593 libwebsocket_close_and_free_session(this, wsi);
594 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +0000595 }
Andy Green8f037e42010-12-19 22:13:26 +0000596
Andy Green90c7cbc2011-01-27 06:26:52 +0000597 /* the guy requested a callback when it was OK to write */
598
Andy Green0d338332011-02-12 11:57:43 +0000599 if (pollfd->revents & POLLOUT) {
Andy Green90c7cbc2011-01-27 06:26:52 +0000600
Andy Green0d338332011-02-12 11:57:43 +0000601 /* one shot */
Andy Green90c7cbc2011-01-27 06:26:52 +0000602
Andy Green0d338332011-02-12 11:57:43 +0000603 pollfd->events &= ~POLLOUT;
604
Andy Green3221f922011-02-12 13:14:11 +0000605 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +0000606 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +0000607 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
608 (void *)(long)wsi->sock, NULL, POLLOUT);
609
Andy Green62c54d22011-02-14 09:14:25 +0000610 wsi->protocol->callback(this, wsi,
Andy Green90c7cbc2011-01-27 06:26:52 +0000611 LWS_CALLBACK_CLIENT_WRITEABLE,
Andy Green0d338332011-02-12 11:57:43 +0000612 wsi->user_space,
Andy Green90c7cbc2011-01-27 06:26:52 +0000613 NULL, 0);
614 }
615
Andy Greenb45993c2010-12-18 15:13:50 +0000616 /* any incoming data ready? */
617
Andy Green0d338332011-02-12 11:57:43 +0000618 if (!(pollfd->revents & POLLIN))
619 break;
Andy Greenb45993c2010-12-18 15:13:50 +0000620
Andy Green0d338332011-02-12 11:57:43 +0000621 /* get the issued broadcast payload from the socket */
Andy Greenb45993c2010-12-18 15:13:50 +0000622
Andy Green0d338332011-02-12 11:57:43 +0000623 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
624 MAX_BROADCAST_PAYLOAD);
625 if (len < 0) {
626 fprintf(stderr, "Error reading broadcast payload\n");
Andy Green4b6fbe12011-02-14 08:03:48 +0000627 break;
Andy Green0d338332011-02-12 11:57:43 +0000628 }
Andy Greenb45993c2010-12-18 15:13:50 +0000629
Andy Green0d338332011-02-12 11:57:43 +0000630 /* broadcast it to all guys with this protocol index */
Andy Green8f037e42010-12-19 22:13:26 +0000631
Andy Green0d338332011-02-12 11:57:43 +0000632 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Green8f037e42010-12-19 22:13:26 +0000633
Andy Green0d338332011-02-12 11:57:43 +0000634 for (m = 0; m < this->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +0000635
Andy Green0d338332011-02-12 11:57:43 +0000636 new_wsi = this->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +0000637
Andy Green0d338332011-02-12 11:57:43 +0000638 /* only to clients we are serving to */
Andy Greenb45993c2010-12-18 15:13:50 +0000639
Andy Green0d338332011-02-12 11:57:43 +0000640 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
Andy Greenb45993c2010-12-18 15:13:50 +0000641 continue;
642
643 /*
644 * never broadcast to non-established
645 * connection
646 */
647
Andy Green0d338332011-02-12 11:57:43 +0000648 if (new_wsi->state != WSI_STATE_ESTABLISHED)
Andy Green4739e5c2011-01-22 12:51:57 +0000649 continue;
650
Andy Greenb45993c2010-12-18 15:13:50 +0000651 /*
652 * only broadcast to connections using
653 * the requested protocol
654 */
655
Andy Green0d338332011-02-12 11:57:43 +0000656 if (new_wsi->protocol->protocol_index !=
657 wsi->protocol_index_for_broadcast_proxy)
Andy Greenb45993c2010-12-18 15:13:50 +0000658 continue;
659
Andy Green8f037e42010-12-19 22:13:26 +0000660 /* broadcast it to this connection */
661
Andy Green62c54d22011-02-14 09:14:25 +0000662 new_wsi->protocol->callback(this, new_wsi,
Andy Green8f037e42010-12-19 22:13:26 +0000663 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +0000664 new_wsi->user_space,
Andy Green0ca6a172010-12-19 20:50:01 +0000665 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
Andy Greenb45993c2010-12-18 15:13:50 +0000666 }
Andy Green0d338332011-02-12 11:57:43 +0000667 }
668 break;
Andy Greenb45993c2010-12-18 15:13:50 +0000669
Andy Greenbe93fef2011-02-14 20:25:43 +0000670 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
671
672 /* handle proxy hung up on us */
673
674 if (pollfd->revents & (POLLERR | POLLHUP)) {
675
676 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
677 (void *)wsi, pollfd->fd);
678
679 libwebsocket_close_and_free_session(this, wsi);
680 return 1;
681 }
682
683 n = recv(wsi->sock, pkt, sizeof pkt, 0);
684 if (n < 0) {
685 libwebsocket_close_and_free_session(this, wsi);
686 fprintf(stderr, "ERROR reading from proxy socket\n");
687 return 1;
688 }
689
690 pkt[13] = '\0';
691 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
692 libwebsocket_close_and_free_session(this, wsi);
693 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
694 return 1;
695 }
696
697 /* clear his proxy connection timeout */
698
699 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
700
701 /* fallthru */
702
703 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
704
705 #ifdef LWS_OPENSSL_SUPPORT
706 if (wsi->use_ssl) {
707
708 wsi->ssl = SSL_new(this->ssl_client_ctx);
709 wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
710 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
711
712 if (SSL_connect(wsi->ssl) <= 0) {
713 fprintf(stderr, "SSL connect error %s\n",
714 ERR_error_string(ERR_get_error(), ssl_err_buf));
715 libwebsocket_close_and_free_session(this, wsi);
716 return 1;
717 }
718
719 n = SSL_get_verify_result(wsi->ssl);
720 if (n != X509_V_OK) {
721 if (n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
722 wsi->use_ssl != 2) {
723
724 fprintf(stderr, "server's cert didn't "
725 "look good %d\n", n);
726 libwebsocket_close_and_free_session(this, wsi);
727 return 1;
728 }
729 }
730 } else {
731 wsi->ssl = NULL;
732 #endif
733
734
735 #ifdef LWS_OPENSSL_SUPPORT
736 }
737 #endif
738
739 /*
740 * create the random key
741 */
742
743 n = read(this->fd_random, hash, 16);
744 if (n != 16) {
745 fprintf(stderr, "Unable to read from random dev %s\n",
746 SYSTEM_RANDOM_FILEPATH);
747 free(wsi->c_path);
748 free(wsi->c_host);
749 free(wsi->c_origin);
750 if (wsi->c_protocol)
751 free(wsi->c_protocol);
752 libwebsocket_close_and_free_session(this, wsi);
753 return 1;
754 }
755
756 lws_b64_encode_string(hash, 16, wsi->key_b64,
757 sizeof wsi->key_b64);
758
759 /*
760 * 04 example client handshake
761 *
762 * GET /chat HTTP/1.1
763 * Host: server.example.com
764 * Upgrade: websocket
765 * Connection: Upgrade
766 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
767 * Sec-WebSocket-Origin: http://example.com
768 * Sec-WebSocket-Protocol: chat, superchat
769 * Sec-WebSocket-Version: 4
770 */
771
772 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
773 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
774 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
775 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
776 "Sec-WebSocket-Key: ");
777 strcpy(p, wsi->key_b64);
778 p += strlen(wsi->key_b64);
779 p += sprintf(p, "\x0d\x0aSec-WebSocket-Origin: %s\x0d\x0a",
780 wsi->c_origin);
781 if (wsi->c_protocol != NULL)
782 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
783 wsi->c_protocol);
784 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a\x0d\x0a",
785 wsi->ietf_spec_revision);
786
787 /* done with these now */
788
789 free(wsi->c_path);
790 free(wsi->c_host);
791 free(wsi->c_origin);
792
793 /* prepare the expected server accept response */
794
795 strcpy((char *)buf, wsi->key_b64);
796 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
797
798 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
799
800 lws_b64_encode_string(hash, 20,
801 wsi->initial_handshake_hash_base64,
802 sizeof wsi->initial_handshake_hash_base64);
803
804 /* send our request to the server */
805
806 #ifdef LWS_OPENSSL_SUPPORT
807 if (wsi->use_ssl)
808 n = SSL_write(wsi->ssl, pkt, p - pkt);
809 else
810 #endif
811 n = send(wsi->sock, pkt, p - pkt, 0);
812
813 if (n < 0) {
814 fprintf(stderr, "ERROR writing to client socket\n");
815 libwebsocket_close_and_free_session(this, wsi);
816 return 1;
817 }
818
819 wsi->parser_state = WSI_TOKEN_NAME_PART;
820 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
821 libwebsocket_set_timeout(wsi,
822 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
823
824 break;
825
826 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
827
828 /* handle server hung up on us */
829
830 if (pollfd->revents & (POLLERR | POLLHUP)) {
831
832 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
833 (void *)wsi, pollfd->fd);
834
835 goto bail3;
836 }
837
838
839 /* interpret the server response */
840
841 /*
842 * HTTP/1.1 101 Switching Protocols
843 * Upgrade: websocket
844 * Connection: Upgrade
845 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
846 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
847 * Sec-WebSocket-Protocol: chat
848 */
849
850 #ifdef LWS_OPENSSL_SUPPORT
851 if (wsi->use_ssl)
852 len = SSL_read(wsi->ssl, pkt, sizeof pkt);
853 else
854 #endif
855 len = recv(wsi->sock, pkt, sizeof pkt, 0);
856
857 if (len < 0) {
858 fprintf(stderr,
859 "libwebsocket_client_handshake read error\n");
860 goto bail3;
861 }
862
863 p = pkt;
864 for (n = 0; n < len; n++)
865 libwebsocket_parse(wsi, *p++);
866
867 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
868 fprintf(stderr, "libwebsocket_client_handshake "
869 "server response ailed parsing\n");
870 goto bail3;
871 }
872
873 /*
874 * well, what the server sent looked reasonable for syntax.
875 * Now let's confirm it sent all the necessary headers
876 */
877
878 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
879 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
880 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
881 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
882 !wsi->utf8_token[WSI_TOKEN_NONCE].token_len ||
883 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
884 wsi->c_protocol != NULL)) {
885 fprintf(stderr, "libwebsocket_client_handshake "
886 "missing required header(s)\n");
887 pkt[len] = '\0';
888 fprintf(stderr, "%s", pkt);
889 goto bail3;
890 }
891
892 /*
893 * Everything seems to be there, now take a closer look at what
894 * is in each header
895 */
896
897 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
898 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
899 "101 switching protocols")) {
900 fprintf(stderr, "libwebsocket_client_handshake "
901 "server sent bad HTTP response '%s'\n",
902 wsi->utf8_token[WSI_TOKEN_HTTP].token);
903 goto bail3;
904 }
905
906 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
907 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
908 "websocket")) {
909 fprintf(stderr, "libwebsocket_client_handshake server "
910 "sent bad Upgrade header '%s'\n",
911 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
912 goto bail3;
913 }
914
915 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
916 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
917 "upgrade")) {
918 fprintf(stderr, "libwebsocket_client_handshake server "
919 "sent bad Connection hdr '%s'\n",
920 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
921 goto bail3;
922 }
923
924
925 pc = wsi->c_protocol;
926
927 /*
928 * confirm the protocol the server wants to talk was in the list
929 * of protocols we offered
930 */
931
932 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
933
934 /*
935 * no protocol name to work from,
936 * default to first protocol
937 */
938 wsi->protocol = &this->protocols[0];
939
940 free(wsi->c_protocol);
941
942 goto check_accept;
943 }
944
945 while (*pc && !okay) {
946 if ((!strncmp(pc,
947 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
948 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
949 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
950 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
951 okay = 1;
952 continue;
953 }
954 while (*pc && *pc != ',')
955 pc++;
956 while (*pc && *pc != ' ')
957 pc++;
958 }
959
960 /* done with him now */
961
962 if (wsi->c_protocol)
963 free(wsi->c_protocol);
964
965
966 if (!okay) {
967 fprintf(stderr, "libwebsocket_client_handshake server "
968 "sent bad protocol '%s'\n",
969 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
970 goto bail2;
971 }
972
973 /*
974 * identify the selected protocol struct and set it
975 */
976 n = 0;
977 wsi->protocol = NULL;
978 while (this->protocols[n].callback) {
979 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
980 this->protocols[n].name) == 0)
981 wsi->protocol = &this->protocols[n];
982 n++;
983 }
984
985 if (wsi->protocol == NULL) {
986 fprintf(stderr, "libwebsocket_client_handshake server "
987 "requested protocol '%s', which we "
988 "said we supported but we don't!\n",
989 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
990 goto bail2;
991 }
992
993 check_accept:
994 /*
995 * Confirm his accept token is the one we precomputed
996 */
997
998 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
999 wsi->initial_handshake_hash_base64)) {
1000 fprintf(stderr, "libwebsocket_client_handshake server "
1001 "sent bad ACCEPT '%s' vs computed '%s'\n",
1002 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1003 wsi->initial_handshake_hash_base64);
1004 goto bail2;
1005 }
1006
1007 /*
1008 * Calculate the masking key to use when sending data to server
1009 */
1010
1011 strcpy((char *)buf, wsi->key_b64);
1012 p = (char *)buf + strlen(wsi->key_b64);
1013 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1014 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1015 strcpy(p, magic_websocket_04_masking_guid);
1016 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1017
1018 /* allocate the per-connection user memory (if any) */
1019
1020 if (wsi->protocol->per_session_data_size) {
1021 wsi->user_space = malloc(
1022 wsi->protocol->per_session_data_size);
1023 if (wsi->user_space == NULL) {
1024 fprintf(stderr, "Out of memory for "
1025 "conn user space\n");
1026 goto bail2;
1027 }
1028 } else
1029 wsi->user_space = NULL;
1030
1031 /* clear his proxy connection timeout */
1032
1033 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1034
1035 /* mark him as being alive */
1036
1037 wsi->state = WSI_STATE_ESTABLISHED;
1038 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1039
1040 fprintf(stderr, "handshake OK for protocol %s\n",
1041 wsi->protocol->name);
1042
1043 /* call him back to inform him he is up */
1044
1045 wsi->protocol->callback(this, wsi,
1046 LWS_CALLBACK_CLIENT_ESTABLISHED,
1047 wsi->user_space,
1048 NULL, 0);
1049
1050 break;
1051
1052bail3:
1053 if (wsi->c_protocol)
1054 free(wsi->c_protocol);
1055
1056bail2:
1057 libwebsocket_close_and_free_session(this, wsi);
1058 return 1;
1059
1060
Andy Green0d338332011-02-12 11:57:43 +00001061 case LWS_CONNMODE_WS_SERVING:
1062 case LWS_CONNMODE_WS_CLIENT:
1063
1064 /* handle session socket closed */
1065
1066 if (pollfd->revents & (POLLERR | POLLHUP)) {
1067
Andy Green62c54d22011-02-14 09:14:25 +00001068 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
Andy Green0d338332011-02-12 11:57:43 +00001069 (void *)wsi, pollfd->fd);
1070
Andy Green4b6fbe12011-02-14 08:03:48 +00001071 libwebsocket_close_and_free_session(this, wsi);
1072 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001073 }
1074
Andy Green0d338332011-02-12 11:57:43 +00001075 /* the guy requested a callback when it was OK to write */
1076
1077 if (pollfd->revents & POLLOUT) {
1078
1079 pollfd->events &= ~POLLOUT;
1080
Andy Green3221f922011-02-12 13:14:11 +00001081 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001082 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001083 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1084 (void *)(long)wsi->sock, NULL, POLLOUT);
1085
Andy Green62c54d22011-02-14 09:14:25 +00001086 wsi->protocol->callback(this, wsi,
Andy Green0d338332011-02-12 11:57:43 +00001087 LWS_CALLBACK_CLIENT_WRITEABLE,
1088 wsi->user_space,
1089 NULL, 0);
1090 }
1091
1092 /* any incoming data ready? */
1093
1094 if (!(pollfd->revents & POLLIN))
1095 break;
1096
Andy Greenb45993c2010-12-18 15:13:50 +00001097#ifdef LWS_OPENSSL_SUPPORT
Andy Green0d338332011-02-12 11:57:43 +00001098 if (wsi->ssl)
1099 n = SSL_read(wsi->ssl, buf, sizeof buf);
Andy Greenb45993c2010-12-18 15:13:50 +00001100 else
1101#endif
Andy Green0d338332011-02-12 11:57:43 +00001102 n = recv(pollfd->fd, buf, sizeof buf, 0);
Andy Greenb45993c2010-12-18 15:13:50 +00001103
1104 if (n < 0) {
1105 fprintf(stderr, "Socket read returned %d\n", n);
Andy Green4b6fbe12011-02-14 08:03:48 +00001106 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001107 }
1108 if (!n) {
Andy Green4b6fbe12011-02-14 08:03:48 +00001109 libwebsocket_close_and_free_session(this, wsi);
1110 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001111 }
1112
Andy Greenb45993c2010-12-18 15:13:50 +00001113 /* service incoming data */
1114
Andy Green4b6fbe12011-02-14 08:03:48 +00001115 n = libwebsocket_read(this, wsi, buf, n);
Andy Green6964bb52011-01-23 16:50:33 +00001116 if (n >= 0)
Andy Green4b6fbe12011-02-14 08:03:48 +00001117 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001118
Andy Green4b6fbe12011-02-14 08:03:48 +00001119 /* we closed wsi */
Andy Green0d338332011-02-12 11:57:43 +00001120
Andy Green4b6fbe12011-02-14 08:03:48 +00001121 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001122 }
1123
1124 return 0;
1125}
1126
Andy Green0d338332011-02-12 11:57:43 +00001127
Andy Green6964bb52011-01-23 16:50:33 +00001128/**
1129 * libwebsocket_context_destroy() - Destroy the websocket context
1130 * @this: Websocket context
1131 *
1132 * This function closes any active connections and then frees the
1133 * context. After calling this, any further use of the context is
1134 * undefined.
1135 */
1136void
1137libwebsocket_context_destroy(struct libwebsocket_context *this)
1138{
Andy Green0d338332011-02-12 11:57:43 +00001139 int n;
1140 int m;
1141 struct libwebsocket *wsi;
Andy Green6964bb52011-01-23 16:50:33 +00001142
Andy Green4b6fbe12011-02-14 08:03:48 +00001143 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
Andy Green0d338332011-02-12 11:57:43 +00001144 for (m = 0; m < this->fd_hashtable[n].length; m++) {
Andy Green0d338332011-02-12 11:57:43 +00001145 wsi = this->fd_hashtable[n].wsi[m];
Andy Green4b6fbe12011-02-14 08:03:48 +00001146 libwebsocket_close_and_free_session(this, wsi);
Andy Greenf3d3b402011-02-09 07:16:34 +00001147 }
Andy Green6964bb52011-01-23 16:50:33 +00001148
Andy Green44eee682011-02-10 09:32:24 +00001149 close(this->fd_random);
1150
Andy Green6964bb52011-01-23 16:50:33 +00001151#ifdef LWS_OPENSSL_SUPPORT
Andy Green44eee682011-02-10 09:32:24 +00001152 if (this->ssl_ctx)
Andy Green90c7cbc2011-01-27 06:26:52 +00001153 SSL_CTX_free(this->ssl_ctx);
Andy Green44eee682011-02-10 09:32:24 +00001154 if (this->ssl_client_ctx)
Andy Green5e1fa172011-02-10 09:07:05 +00001155 SSL_CTX_free(this->ssl_client_ctx);
Andy Green6964bb52011-01-23 16:50:33 +00001156#endif
1157
Andy Green44eee682011-02-10 09:32:24 +00001158 free(this);
Andy Green6964bb52011-01-23 16:50:33 +00001159}
1160
1161/**
1162 * libwebsocket_service() - Service any pending websocket activity
1163 * @this: Websocket context
1164 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1165 * service otherwise block and service immediately, returning
1166 * after the timeout if nothing needed service.
1167 *
1168 * This function deals with any pending websocket traffic, for three
1169 * kinds of event. It handles these events on both server and client
1170 * types of connection the same.
1171 *
1172 * 1) Accept new connections to our context's server
1173 *
1174 * 2) Perform pending broadcast writes initiated from other forked
1175 * processes (effectively serializing asynchronous broadcasts)
1176 *
1177 * 3) Call the receive callback for incoming frame data received by
1178 * server or client connections.
1179 *
1180 * You need to call this service function periodically to all the above
1181 * functions to happen; if your application is single-threaded you can
1182 * just call it in your main event loop.
1183 *
1184 * Alternatively you can fork a new process that asynchronously handles
1185 * calling this service in a loop. In that case you are happy if this
1186 * call blocks your thread until it needs to take care of something and
1187 * would call it with a large nonzero timeout. Your loop then takes no
1188 * CPU while there is nothing happening.
1189 *
1190 * If you are calling it in a single-threaded app, you don't want it to
1191 * wait around blocking other things in your loop from happening, so you
1192 * would call it with a timeout_ms of 0, so it returns immediately if
1193 * nothing is pending, or as soon as it services whatever was pending.
1194 */
1195
Andy Greenb45993c2010-12-18 15:13:50 +00001196
Andy Greene92cd172011-01-19 13:11:55 +00001197int
1198libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
1199{
1200 int n;
Andy Greene92cd172011-01-19 13:11:55 +00001201
1202 /* stay dead once we are dead */
1203
1204 if (this == NULL)
1205 return 1;
1206
Andy Green0d338332011-02-12 11:57:43 +00001207 /* wait for something to need service */
Andy Green4739e5c2011-01-22 12:51:57 +00001208
Andy Green0d338332011-02-12 11:57:43 +00001209 n = poll(this->fds, this->fds_count, timeout_ms);
Andy Green3221f922011-02-12 13:14:11 +00001210 if (n == 0) /* poll timeout */
1211 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00001212
Andy Green62c54d22011-02-14 09:14:25 +00001213 if (n < 0) {
Andy Green5e1fa172011-02-10 09:07:05 +00001214 /*
Andy Greene92cd172011-01-19 13:11:55 +00001215 fprintf(stderr, "Listen Socket dead\n");
Andy Green5e1fa172011-02-10 09:07:05 +00001216 */
Andy Green0d338332011-02-12 11:57:43 +00001217 return 1;
Andy Greene92cd172011-01-19 13:11:55 +00001218 }
Andy Greene92cd172011-01-19 13:11:55 +00001219
1220 /* handle accept on listening socket? */
1221
Andy Green0d338332011-02-12 11:57:43 +00001222 for (n = 0; n < this->fds_count; n++)
1223 if (this->fds[n].revents)
1224 libwebsocket_service_fd(this, &this->fds[n]);
Andy Greene92cd172011-01-19 13:11:55 +00001225
1226 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00001227}
1228
Andy Green90c7cbc2011-01-27 06:26:52 +00001229/**
1230 * libwebsocket_callback_on_writable() - Request a callback when this socket
1231 * becomes able to be written to without
1232 * blocking
Andy Green32375b72011-02-19 08:32:53 +00001233 *
1234 * @this: libwebsockets context
Andy Green90c7cbc2011-01-27 06:26:52 +00001235 * @wsi: Websocket connection instance to get callback for
1236 */
1237
1238int
Andy Green62c54d22011-02-14 09:14:25 +00001239libwebsocket_callback_on_writable(struct libwebsocket_context *this,
1240 struct libwebsocket *wsi)
Andy Green90c7cbc2011-01-27 06:26:52 +00001241{
Andy Green90c7cbc2011-01-27 06:26:52 +00001242 int n;
1243
Andy Green0d338332011-02-12 11:57:43 +00001244 for (n = 0; n < this->fds_count; n++)
1245 if (this->fds[n].fd == wsi->sock) {
Andy Green90c7cbc2011-01-27 06:26:52 +00001246 this->fds[n].events |= POLLOUT;
Andy Green3221f922011-02-12 13:14:11 +00001247 n = this->fds_count;
Andy Green90c7cbc2011-01-27 06:26:52 +00001248 }
1249
Andy Green3221f922011-02-12 13:14:11 +00001250 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001251 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001252 LWS_CALLBACK_SET_MODE_POLL_FD,
1253 (void *)(long)wsi->sock, NULL, POLLOUT);
1254
Andy Green90c7cbc2011-01-27 06:26:52 +00001255 return 1;
1256}
1257
1258/**
1259 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1260 * all connections using the given protocol when it
1261 * becomes possible to write to each socket without
1262 * blocking in turn.
1263 *
1264 * @protocol: Protocol whose connections will get callbacks
1265 */
1266
1267int
1268libwebsocket_callback_on_writable_all_protocol(
1269 const struct libwebsocket_protocols *protocol)
1270{
1271 struct libwebsocket_context *this = protocol->owning_server;
1272 int n;
Andy Green0d338332011-02-12 11:57:43 +00001273 int m;
1274 struct libwebsocket *wsi;
Andy Green90c7cbc2011-01-27 06:26:52 +00001275
Andy Green0d338332011-02-12 11:57:43 +00001276 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1277
1278 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1279
1280 wsi = this->fd_hashtable[n].wsi[m];
1281
1282 if (wsi->protocol == protocol)
Andy Green62c54d22011-02-14 09:14:25 +00001283 libwebsocket_callback_on_writable(this, wsi);
Andy Green0d338332011-02-12 11:57:43 +00001284 }
1285 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001286
1287 return 0;
1288}
1289
Andy Greenbe93fef2011-02-14 20:25:43 +00001290/**
1291 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1292 *
1293 * You will not need this unless you are doing something special
1294 *
1295 * @wsi: Websocket connection instance
1296 * @reason: timeout reason
1297 * @secs: how many seconds
1298 */
1299
1300void
1301libwebsocket_set_timeout(struct libwebsocket *wsi,
1302 enum pending_timeout reason, int secs)
1303{
1304 struct timeval tv;
1305
1306 gettimeofday(&tv, NULL);
1307
1308 wsi->pending_timeout_limit = tv.tv_sec + secs;
1309 wsi->pending_timeout = reason;
1310}
1311
Andy Greena6cbece2011-01-27 20:06:03 +00001312
1313/**
1314 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1315 *
1316 * You will not need this unless you are doing something special
1317 *
1318 * @wsi: Websocket connection instance
1319 */
1320
1321int
1322libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1323{
1324 return wsi->sock;
1325}
1326
Andy Green90c7cbc2011-01-27 06:26:52 +00001327/**
1328 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1329 * receieved packets.
1330 *
1331 * If the output side of a server process becomes choked, this allows flow
1332 * control for the input side.
1333 *
1334 * @wsi: Websocket connection instance to get callback for
1335 * @enable: 0 = disable read servicing for this connection, 1 = enable
1336 */
1337
1338int
1339libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1340{
1341 struct libwebsocket_context *this = wsi->protocol->owning_server;
1342 int n;
1343
Andy Green0d338332011-02-12 11:57:43 +00001344 for (n = 0; n < this->fds_count; n++)
1345 if (this->fds[n].fd == wsi->sock) {
Andy Green90c7cbc2011-01-27 06:26:52 +00001346 if (enable)
1347 this->fds[n].events |= POLLIN;
1348 else
1349 this->fds[n].events &= ~POLLIN;
1350
1351 return 0;
1352 }
1353
Andy Green3221f922011-02-12 13:14:11 +00001354 if (enable)
1355 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001356 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001357 LWS_CALLBACK_SET_MODE_POLL_FD,
1358 (void *)(long)wsi->sock, NULL, POLLIN);
1359 else
1360 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001361 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001362 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1363 (void *)(long)wsi->sock, NULL, POLLIN);
1364
1365
Andy Green90c7cbc2011-01-27 06:26:52 +00001366 fprintf(stderr, "libwebsocket_callback_on_writable "
1367 "unable to find socket\n");
1368 return 1;
1369}
1370
Andy Green2ac5a6f2011-01-28 10:00:18 +00001371/**
1372 * libwebsocket_canonical_hostname() - returns this host's hostname
1373 *
1374 * This is typically used by client code to fill in the host parameter
1375 * when making a client connection. You can only call it after the context
1376 * has been created.
1377 *
1378 * @this: Websocket context
1379 */
1380
1381
1382extern const char *
1383libwebsocket_canonical_hostname(struct libwebsocket_context *this)
1384{
1385 return (const char *)this->canonical_hostname;
1386}
1387
1388
Andy Green90c7cbc2011-01-27 06:26:52 +00001389static void sigpipe_handler(int x)
1390{
1391}
1392
Andy Greenb45993c2010-12-18 15:13:50 +00001393
Andy Greenab990e42010-10-31 12:42:52 +00001394/**
Andy Green4739e5c2011-01-22 12:51:57 +00001395 * libwebsocket_create_context() - Create the websocket handler
1396 * @port: Port to listen on... you can use 0 to suppress listening on
Andy Green6964bb52011-01-23 16:50:33 +00001397 * any port, that's what you want if you are not running a
1398 * websocket server at all but just using it as a client
Andy Green32375b72011-02-19 08:32:53 +00001399 * @interface: NULL to bind the listen socket to all interfaces, or the
1400 * interface name, eg, "eth2"
Andy Green4f3943a2010-11-12 10:44:16 +00001401 * @protocols: Array of structures listing supported protocols and a protocol-
Andy Green8f037e42010-12-19 22:13:26 +00001402 * specific callback for each one. The list is ended with an
1403 * entry that has a NULL callback pointer.
Andy Green6964bb52011-01-23 16:50:33 +00001404 * It's not const because we write the owning_server member
Andy Green3faa9c72010-11-08 17:03:03 +00001405 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
Andy Green8f037e42010-12-19 22:13:26 +00001406 * to listen using SSL, set to the filepath to fetch the
1407 * server cert from, otherwise NULL for unencrypted
Andy Green3faa9c72010-11-08 17:03:03 +00001408 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
Andy Green8f037e42010-12-19 22:13:26 +00001409 * else ignored
Andy Green3faa9c72010-11-08 17:03:03 +00001410 * @gid: group id to change to after setting listen socket, or -1.
1411 * @uid: user id to change to after setting listen socket, or -1.
Andy Greenbfb051f2011-02-09 08:49:14 +00001412 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
Andy Green05464c62010-11-12 10:44:18 +00001413 *
Andy Green8f037e42010-12-19 22:13:26 +00001414 * This function creates the listening socket and takes care
1415 * of all initialization in one step.
1416 *
Andy Greene92cd172011-01-19 13:11:55 +00001417 * After initialization, it returns a struct libwebsocket_context * that
1418 * represents this server. After calling, user code needs to take care
1419 * of calling libwebsocket_service() with the context pointer to get the
1420 * server's sockets serviced. This can be done in the same process context
1421 * or a forked process, or another thread,
Andy Green05464c62010-11-12 10:44:18 +00001422 *
Andy Green8f037e42010-12-19 22:13:26 +00001423 * The protocol callback functions are called for a handful of events
1424 * including http requests coming in, websocket connections becoming
1425 * established, and data arriving; it's also called periodically to allow
1426 * async transmission.
1427 *
1428 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1429 * at that time websocket protocol has not been negotiated. Other
1430 * protocols after the first one never see any HTTP callack activity.
1431 *
1432 * The server created is a simple http server by default; part of the
1433 * websocket standard is upgrading this http connection to a websocket one.
1434 *
1435 * This allows the same server to provide files like scripts and favicon /
1436 * images or whatever over http and dynamic data over websockets all in
1437 * one place; they're all handled in the user callback.
Andy Greenab990e42010-10-31 12:42:52 +00001438 */
Andy Green4ea60062010-10-30 12:15:07 +01001439
Andy Greene92cd172011-01-19 13:11:55 +00001440struct libwebsocket_context *
Andy Green32375b72011-02-19 08:32:53 +00001441libwebsocket_create_context(int port, const char *interface,
Andy Greenb45993c2010-12-18 15:13:50 +00001442 struct libwebsocket_protocols *protocols,
Andy Green8f037e42010-12-19 22:13:26 +00001443 const char *ssl_cert_filepath,
1444 const char *ssl_private_key_filepath,
Andy Green8014b292011-01-30 20:57:25 +00001445 int gid, int uid, unsigned int options)
Andy Greenff95d7a2010-10-28 22:36:01 +01001446{
1447 int n;
Andy Green4739e5c2011-01-22 12:51:57 +00001448 int sockfd = 0;
Andy Green251f6fa2010-11-03 11:13:06 +00001449 int fd;
Andy Greenff95d7a2010-10-28 22:36:01 +01001450 struct sockaddr_in serv_addr, cli_addr;
Andy Green251f6fa2010-11-03 11:13:06 +00001451 int opt = 1;
Andy Green8f037e42010-12-19 22:13:26 +00001452 struct libwebsocket_context *this = NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001453 unsigned int slen;
Andy Green9659f372011-01-27 22:01:43 +00001454 char *p;
Andy Green2ac5a6f2011-01-28 10:00:18 +00001455 char hostname[1024];
Andy Green42f69142011-01-30 08:10:02 +00001456 struct hostent *he;
Andy Green0d338332011-02-12 11:57:43 +00001457 struct libwebsocket *wsi;
Andy Greenff95d7a2010-10-28 22:36:01 +01001458
Andy Green3faa9c72010-11-08 17:03:03 +00001459#ifdef LWS_OPENSSL_SUPPORT
Andy Greenf2f54d52010-11-15 22:08:00 +00001460 SSL_METHOD *method;
Andy Green3faa9c72010-11-08 17:03:03 +00001461 char ssl_err_buf[512];
Andy Green3faa9c72010-11-08 17:03:03 +00001462#endif
1463
Andy Green90c7cbc2011-01-27 06:26:52 +00001464 this = malloc(sizeof(struct libwebsocket_context));
1465 if (!this) {
1466 fprintf(stderr, "No memory for websocket context\n");
1467 return NULL;
1468 }
1469 this->protocols = protocols;
1470 this->listen_port = port;
Andy Green9659f372011-01-27 22:01:43 +00001471 this->http_proxy_port = 0;
1472 this->http_proxy_address[0] = '\0';
Andy Green8014b292011-01-30 20:57:25 +00001473 this->options = options;
Andy Green0d338332011-02-12 11:57:43 +00001474 this->fds_count = 0;
Andy Green9659f372011-01-27 22:01:43 +00001475
Andy Green44eee682011-02-10 09:32:24 +00001476 this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1477 if (this->fd_random < 0) {
1478 fprintf(stderr, "Unable to open random device %s %d\n",
1479 SYSTEM_RANDOM_FILEPATH, this->fd_random);
1480 return NULL;
1481 }
1482
Andy Green2ac5a6f2011-01-28 10:00:18 +00001483 /* find canonical hostname */
1484
1485 hostname[(sizeof hostname) - 1] = '\0';
1486 gethostname(hostname, (sizeof hostname) - 1);
1487 he = gethostbyname(hostname);
Darin Willitsc19456f2011-02-14 17:52:39 +00001488 if (he) {
1489 strncpy(this->canonical_hostname, he->h_name,
Andy Green2ac5a6f2011-01-28 10:00:18 +00001490 sizeof this->canonical_hostname - 1);
Darin Willitsc19456f2011-02-14 17:52:39 +00001491 this->canonical_hostname[sizeof this->canonical_hostname - 1] =
1492 '\0';
1493 } else
1494 strncpy(this->canonical_hostname, hostname,
1495 sizeof this->canonical_hostname - 1);
Andy Green2ac5a6f2011-01-28 10:00:18 +00001496
Andy Green9659f372011-01-27 22:01:43 +00001497 /* split the proxy ads:port if given */
1498
1499 p = getenv("http_proxy");
1500 if (p) {
1501 strncpy(this->http_proxy_address, p,
1502 sizeof this->http_proxy_address - 1);
1503 this->http_proxy_address[
1504 sizeof this->http_proxy_address - 1] = '\0';
1505
1506 p = strchr(this->http_proxy_address, ':');
1507 if (p == NULL) {
1508 fprintf(stderr, "http_proxy needs to be ads:port\n");
1509 return NULL;
1510 }
1511 *p = '\0';
1512 this->http_proxy_port = atoi(p + 1);
1513
1514 fprintf(stderr, "Using proxy %s:%u\n",
1515 this->http_proxy_address,
1516 this->http_proxy_port);
1517 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001518
1519 if (port) {
1520
Andy Green3faa9c72010-11-08 17:03:03 +00001521#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +00001522 this->use_ssl = ssl_cert_filepath != NULL &&
1523 ssl_private_key_filepath != NULL;
1524 if (this->use_ssl)
1525 fprintf(stderr, " Compiled with SSL support, "
1526 "using it\n");
1527 else
1528 fprintf(stderr, " Compiled with SSL support, "
1529 "not using it\n");
Andy Green3faa9c72010-11-08 17:03:03 +00001530
Andy Green90c7cbc2011-01-27 06:26:52 +00001531#else
1532 if (ssl_cert_filepath != NULL &&
1533 ssl_private_key_filepath != NULL) {
1534 fprintf(stderr, " Not compiled for OpenSSl support!\n");
Andy Greene92cd172011-01-19 13:11:55 +00001535 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00001536 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001537 fprintf(stderr, " Compiled without SSL support, "
1538 "serving unencrypted\n");
1539#endif
1540 }
1541
1542 /* ignore SIGPIPE */
1543
1544 signal(SIGPIPE, sigpipe_handler);
1545
1546
1547#ifdef LWS_OPENSSL_SUPPORT
1548
1549 /* basic openssl init */
1550
1551 SSL_library_init();
1552
1553 OpenSSL_add_all_algorithms();
1554 SSL_load_error_strings();
1555
1556 /*
1557 * Firefox insists on SSLv23 not SSLv3
1558 * Konq disables SSLv2 by default now, SSLv23 works
1559 */
1560
1561 method = (SSL_METHOD *)SSLv23_server_method();
1562 if (!method) {
1563 fprintf(stderr, "problem creating ssl method: %s\n",
1564 ERR_error_string(ERR_get_error(), ssl_err_buf));
1565 return NULL;
1566 }
1567 this->ssl_ctx = SSL_CTX_new(method); /* create context */
1568 if (!this->ssl_ctx) {
1569 fprintf(stderr, "problem creating ssl context: %s\n",
1570 ERR_error_string(ERR_get_error(), ssl_err_buf));
1571 return NULL;
1572 }
1573
1574 /* client context */
1575
1576 method = (SSL_METHOD *)SSLv23_client_method();
1577 if (!method) {
1578 fprintf(stderr, "problem creating ssl method: %s\n",
1579 ERR_error_string(ERR_get_error(), ssl_err_buf));
1580 return NULL;
1581 }
1582 this->ssl_client_ctx = SSL_CTX_new(method); /* create context */
1583 if (!this->ssl_client_ctx) {
1584 fprintf(stderr, "problem creating ssl context: %s\n",
1585 ERR_error_string(ERR_get_error(), ssl_err_buf));
1586 return NULL;
1587 }
1588
1589
1590 /* openssl init for cert verification (used with client sockets) */
1591
1592 if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
1593 LWS_OPENSSL_CLIENT_CERTS)) {
1594 fprintf(stderr, "Unable to load SSL Client certs from %s "
1595 "(set by --with-client-cert-dir= in configure) -- "
1596 " client ssl isn't going to work",
1597 LWS_OPENSSL_CLIENT_CERTS);
1598 }
1599
Andy Green0894bda2011-02-19 09:09:11 +00001600 /*
1601 * callback allowing user code to load extra verification certs
1602 * helping the client to verify server identity
1603 */
1604
Andy Greenc6bf2c22011-02-20 11:10:47 +00001605 this->protocols[0].callback(this, NULL,
Andy Green0894bda2011-02-19 09:09:11 +00001606 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1607 this->ssl_client_ctx, NULL, 0);
1608
Andy Greenc6bf2c22011-02-20 11:10:47 +00001609 /* as a server, are we requiring clients to identify themselves? */
1610
1611 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1612
1613 /* absolutely require the client cert */
1614
1615 SSL_CTX_set_verify(this->ssl_ctx,
1616 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
1617
1618 /*
1619 * give user code a chance to load certs into the server
1620 * allowing it to verify incoming client certs
1621 */
1622
1623 this->protocols[0].callback(this, NULL,
1624 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1625 this->ssl_ctx, NULL, 0);
1626 }
1627
Andy Green0894bda2011-02-19 09:09:11 +00001628
Andy Green90c7cbc2011-01-27 06:26:52 +00001629 if (this->use_ssl) {
1630
1631 /* openssl init for server sockets */
1632
Andy Green3faa9c72010-11-08 17:03:03 +00001633 /* set the local certificate from CertFile */
Andy Green90c7cbc2011-01-27 06:26:52 +00001634 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
Andy Green3faa9c72010-11-08 17:03:03 +00001635 ssl_cert_filepath, SSL_FILETYPE_PEM);
1636 if (n != 1) {
1637 fprintf(stderr, "problem getting cert '%s': %s\n",
1638 ssl_cert_filepath,
1639 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00001640 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00001641 }
1642 /* set the private key from KeyFile */
Andy Green90c7cbc2011-01-27 06:26:52 +00001643 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
Andy Green018d8eb2010-11-08 21:04:23 +00001644 ssl_private_key_filepath,
Andy Green4739e5c2011-01-22 12:51:57 +00001645 SSL_FILETYPE_PEM) != 1) {
Andy Green018d8eb2010-11-08 21:04:23 +00001646 fprintf(stderr, "ssl problem getting key '%s': %s\n",
1647 ssl_private_key_filepath,
1648 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00001649 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00001650 }
1651 /* verify private key */
Andy Green90c7cbc2011-01-27 06:26:52 +00001652 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
Andy Green018d8eb2010-11-08 21:04:23 +00001653 fprintf(stderr, "Private SSL key doesn't match cert\n");
Andy Greene92cd172011-01-19 13:11:55 +00001654 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00001655 }
1656
1657 /* SSL is happy and has a cert it's content with */
1658 }
1659#endif
Andy Greenb45993c2010-12-18 15:13:50 +00001660
Andy Greendf736162011-01-18 15:39:02 +00001661 /* selftest */
1662
1663 if (lws_b64_selftest())
Andy Greene92cd172011-01-19 13:11:55 +00001664 return NULL;
Andy Greendf736162011-01-18 15:39:02 +00001665
Andy Green0d338332011-02-12 11:57:43 +00001666 /* fd hashtable init */
1667
1668 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1669 this->fd_hashtable[n].length = 0;
1670
Andy Greenb45993c2010-12-18 15:13:50 +00001671 /* set up our external listening socket we serve on */
Andy Green8f037e42010-12-19 22:13:26 +00001672
Andy Green4739e5c2011-01-22 12:51:57 +00001673 if (port) {
Andy Green8f037e42010-12-19 22:13:26 +00001674
Andy Green4739e5c2011-01-22 12:51:57 +00001675 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1676 if (sockfd < 0) {
1677 fprintf(stderr, "ERROR opening socket");
1678 return NULL;
1679 }
Andy Green775c0dd2010-10-29 14:15:22 +01001680
Andy Green4739e5c2011-01-22 12:51:57 +00001681 /* allow us to restart even if old sockets in TIME_WAIT */
1682 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
Andy Greene77ddd82010-11-13 10:03:47 +00001683
Andy Green4739e5c2011-01-22 12:51:57 +00001684 bzero((char *) &serv_addr, sizeof(serv_addr));
1685 serv_addr.sin_family = AF_INET;
Andy Green32375b72011-02-19 08:32:53 +00001686 if (interface == NULL)
1687 serv_addr.sin_addr.s_addr = INADDR_ANY;
1688 else
1689 interface_to_sa(interface, &serv_addr,
1690 sizeof(serv_addr));
Andy Green4739e5c2011-01-22 12:51:57 +00001691 serv_addr.sin_port = htons(port);
1692
1693 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1694 sizeof(serv_addr));
1695 if (n < 0) {
1696 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Green8f037e42010-12-19 22:13:26 +00001697 port, n, errno);
Andy Green4739e5c2011-01-22 12:51:57 +00001698 return NULL;
1699 }
Andy Green0d338332011-02-12 11:57:43 +00001700
1701 wsi = malloc(sizeof(struct libwebsocket));
1702 memset(wsi, 0, sizeof (struct libwebsocket));
1703 wsi->sock = sockfd;
1704 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1705 insert_wsi(this, wsi);
1706
1707 listen(sockfd, 5);
1708 fprintf(stderr, " Listening on port %d\n", port);
1709
1710 /* list in the internal poll array */
1711
1712 this->fds[this->fds_count].fd = sockfd;
1713 this->fds[this->fds_count++].events = POLLIN;
Andy Green3221f922011-02-12 13:14:11 +00001714
1715 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001716 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001717 LWS_CALLBACK_ADD_POLL_FD,
1718 (void *)(long)sockfd, NULL, POLLIN);
1719
Andy Green8f037e42010-12-19 22:13:26 +00001720 }
Andy Greenb45993c2010-12-18 15:13:50 +00001721
Andy Greene77ddd82010-11-13 10:03:47 +00001722 /* drop any root privs for this process */
Andy Green3faa9c72010-11-08 17:03:03 +00001723
1724 if (gid != -1)
1725 if (setgid(gid))
1726 fprintf(stderr, "setgid: %s\n", strerror(errno));
1727 if (uid != -1)
1728 if (setuid(uid))
1729 fprintf(stderr, "setuid: %s\n", strerror(errno));
1730
Andy Greenb45993c2010-12-18 15:13:50 +00001731
1732 /* set up our internal broadcast trigger sockets per-protocol */
1733
Andy Green0d338332011-02-12 11:57:43 +00001734 for (this->count_protocols = 0;
1735 protocols[this->count_protocols].callback;
Andy Greenb45993c2010-12-18 15:13:50 +00001736 this->count_protocols++) {
1737 protocols[this->count_protocols].owning_server = this;
1738 protocols[this->count_protocols].protocol_index =
1739 this->count_protocols;
1740
1741 fd = socket(AF_INET, SOCK_STREAM, 0);
1742 if (fd < 0) {
1743 fprintf(stderr, "ERROR opening socket");
Andy Greene92cd172011-01-19 13:11:55 +00001744 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001745 }
Andy Green8f037e42010-12-19 22:13:26 +00001746
Andy Greenb45993c2010-12-18 15:13:50 +00001747 /* allow us to restart even if old sockets in TIME_WAIT */
1748 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1749
1750 bzero((char *) &serv_addr, sizeof(serv_addr));
1751 serv_addr.sin_family = AF_INET;
1752 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1753 serv_addr.sin_port = 0; /* pick the port for us */
1754
1755 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1756 if (n < 0) {
Andy Green8f037e42010-12-19 22:13:26 +00001757 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Greenb45993c2010-12-18 15:13:50 +00001758 port, n, errno);
Andy Greene92cd172011-01-19 13:11:55 +00001759 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001760 }
1761
1762 slen = sizeof cli_addr;
1763 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1764 if (n < 0) {
1765 fprintf(stderr, "getsockname failed\n");
Andy Greene92cd172011-01-19 13:11:55 +00001766 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001767 }
1768 protocols[this->count_protocols].broadcast_socket_port =
1769 ntohs(cli_addr.sin_port);
1770 listen(fd, 5);
1771
1772 debug(" Protocol %s broadcast socket %d\n",
1773 protocols[this->count_protocols].name,
1774 ntohs(cli_addr.sin_port));
1775
Andy Green0d338332011-02-12 11:57:43 +00001776 /* dummy wsi per broadcast proxy socket */
1777
1778 wsi = malloc(sizeof(struct libwebsocket));
1779 memset(wsi, 0, sizeof (struct libwebsocket));
1780 wsi->sock = fd;
1781 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1782 /* note which protocol we are proxying */
1783 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1784 insert_wsi(this, wsi);
1785
1786 /* list in internal poll array */
1787
Andy Greenb45993c2010-12-18 15:13:50 +00001788 this->fds[this->fds_count].fd = fd;
1789 this->fds[this->fds_count].events = POLLIN;
Andy Green3221f922011-02-12 13:14:11 +00001790 this->fds[this->fds_count].revents = 0;
Andy Greenb45993c2010-12-18 15:13:50 +00001791 this->fds_count++;
Andy Green3221f922011-02-12 13:14:11 +00001792
1793 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001794 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001795 LWS_CALLBACK_ADD_POLL_FD,
1796 (void *)(long)fd, NULL, POLLIN);
Andy Greenb45993c2010-12-18 15:13:50 +00001797 }
1798
Andy Greene92cd172011-01-19 13:11:55 +00001799 return this;
1800}
Andy Greenb45993c2010-12-18 15:13:50 +00001801
Andy Green4739e5c2011-01-22 12:51:57 +00001802
Andy Greened11a022011-01-20 10:23:50 +00001803#ifndef LWS_NO_FORK
1804
Andy Greene92cd172011-01-19 13:11:55 +00001805/**
1806 * libwebsockets_fork_service_loop() - Optional helper function forks off
1807 * a process for the websocket server loop.
Andy Green6964bb52011-01-23 16:50:33 +00001808 * You don't have to use this but if not, you
1809 * have to make sure you are calling
1810 * libwebsocket_service periodically to service
1811 * the websocket traffic
Andy Greene92cd172011-01-19 13:11:55 +00001812 * @this: server context returned by creation function
1813 */
Andy Greenb45993c2010-12-18 15:13:50 +00001814
Andy Greene92cd172011-01-19 13:11:55 +00001815int
1816libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1817{
Andy Greene92cd172011-01-19 13:11:55 +00001818 int fd;
1819 struct sockaddr_in cli_addr;
1820 int n;
Andy Green3221f922011-02-12 13:14:11 +00001821 int p;
Andy Greenb45993c2010-12-18 15:13:50 +00001822
Andy Greened11a022011-01-20 10:23:50 +00001823 n = fork();
1824 if (n < 0)
1825 return n;
1826
1827 if (!n) {
1828
1829 /* main process context */
1830
Andy Green3221f922011-02-12 13:14:11 +00001831 /*
1832 * set up the proxy sockets to allow broadcast from
1833 * service process context
1834 */
1835
1836 for (p = 0; p < this->count_protocols; p++) {
Andy Greened11a022011-01-20 10:23:50 +00001837 fd = socket(AF_INET, SOCK_STREAM, 0);
1838 if (fd < 0) {
1839 fprintf(stderr, "Unable to create socket\n");
1840 return -1;
1841 }
1842 cli_addr.sin_family = AF_INET;
1843 cli_addr.sin_port = htons(
Andy Green3221f922011-02-12 13:14:11 +00001844 this->protocols[p].broadcast_socket_port);
Andy Greened11a022011-01-20 10:23:50 +00001845 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1846 n = connect(fd, (struct sockaddr *)&cli_addr,
1847 sizeof cli_addr);
1848 if (n < 0) {
1849 fprintf(stderr, "Unable to connect to "
1850 "broadcast socket %d, %s\n",
Andy Green3221f922011-02-12 13:14:11 +00001851 n, strerror(errno));
Andy Greened11a022011-01-20 10:23:50 +00001852 return -1;
1853 }
1854
Andy Green3221f922011-02-12 13:14:11 +00001855 this->protocols[p].broadcast_socket_user_fd = fd;
Andy Greened11a022011-01-20 10:23:50 +00001856 }
1857
Andy Greene92cd172011-01-19 13:11:55 +00001858 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00001859 }
1860
1861 /* we want a SIGHUP when our parent goes down */
1862 prctl(PR_SET_PDEATHSIG, SIGHUP);
1863
1864 /* in this forked process, sit and service websocket connections */
Andy Green8f037e42010-12-19 22:13:26 +00001865
Andy Greene92cd172011-01-19 13:11:55 +00001866 while (1)
1867 if (libwebsocket_service(this, 1000))
1868 return -1;
Andy Green8f037e42010-12-19 22:13:26 +00001869
Andy Green251f6fa2010-11-03 11:13:06 +00001870 return 0;
Andy Greenff95d7a2010-10-28 22:36:01 +01001871}
1872
Andy Greened11a022011-01-20 10:23:50 +00001873#endif
1874
Andy Greenb45993c2010-12-18 15:13:50 +00001875/**
1876 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
Andy Green8f037e42010-12-19 22:13:26 +00001877 * connection.
Andy Greenb45993c2010-12-18 15:13:50 +00001878 * @wsi: pointer to struct websocket you want to know the protocol of
1879 *
Andy Green8f037e42010-12-19 22:13:26 +00001880 *
1881 * This is useful to get the protocol to broadcast back to from inside
Andy Greenb45993c2010-12-18 15:13:50 +00001882 * the callback.
1883 */
Andy Greenab990e42010-10-31 12:42:52 +00001884
Andy Greenb45993c2010-12-18 15:13:50 +00001885const struct libwebsocket_protocols *
1886libwebsockets_get_protocol(struct libwebsocket *wsi)
1887{
1888 return wsi->protocol;
1889}
1890
1891/**
Andy Greene92cd172011-01-19 13:11:55 +00001892 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
Andy Green8f037e42010-12-19 22:13:26 +00001893 * connections of the given protocol.
Andy Greenb45993c2010-12-18 15:13:50 +00001894 * @protocol: pointer to the protocol you will broadcast to all members of
1895 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
Andy Green8f037e42010-12-19 22:13:26 +00001896 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1897 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1898 * case you are calling this function from callback context.
Andy Greenb45993c2010-12-18 15:13:50 +00001899 * @len: length of payload data in buf, starting from buf.
Andy Green8f037e42010-12-19 22:13:26 +00001900 *
1901 * This function allows bulk sending of a packet to every connection using
Andy Greenb45993c2010-12-18 15:13:50 +00001902 * the given protocol. It does not send the data directly; instead it calls
1903 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
1904 * wants to actually send the data for that connection, the callback itself
1905 * should call libwebsocket_write().
1906 *
1907 * libwebsockets_broadcast() can be called from another fork context without
1908 * having to take any care about data visibility between the processes, it'll
1909 * "just work".
1910 */
1911
1912
1913int
Andy Green8f037e42010-12-19 22:13:26 +00001914libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
Andy Greenb45993c2010-12-18 15:13:50 +00001915 unsigned char *buf, size_t len)
1916{
Andy Green8f037e42010-12-19 22:13:26 +00001917 struct libwebsocket_context *this = protocol->owning_server;
Andy Greenb45993c2010-12-18 15:13:50 +00001918 int n;
Andy Green0d338332011-02-12 11:57:43 +00001919 int m;
1920 struct libwebsocket * wsi;
Andy Greenb45993c2010-12-18 15:13:50 +00001921
1922 if (!protocol->broadcast_socket_user_fd) {
1923 /*
Andy Greene92cd172011-01-19 13:11:55 +00001924 * We are either running unforked / flat, or we are being
1925 * called from poll thread context
Andy Greenb45993c2010-12-18 15:13:50 +00001926 * eg, from a callback. In that case don't use sockets for
1927 * broadcast IPC (since we can't open a socket connection to
1928 * a socket listening on our own thread) but directly do the
1929 * send action.
1930 *
1931 * Locking is not needed because we are by definition being
1932 * called in the poll thread context and are serialized.
1933 */
1934
Andy Green0d338332011-02-12 11:57:43 +00001935 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Greenb45993c2010-12-18 15:13:50 +00001936
Andy Green0d338332011-02-12 11:57:43 +00001937 for (m = 0; m < this->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +00001938
Andy Green0d338332011-02-12 11:57:43 +00001939 wsi = this->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +00001940
Andy Green0d338332011-02-12 11:57:43 +00001941 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1942 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00001943
Andy Green0d338332011-02-12 11:57:43 +00001944 /*
1945 * never broadcast to
1946 * non-established connections
1947 */
1948 if (wsi->state != WSI_STATE_ESTABLISHED)
1949 continue;
1950
1951 /* only broadcast to guys using
1952 * requested protocol
1953 */
1954 if (wsi->protocol != protocol)
1955 continue;
1956
Andy Green62c54d22011-02-14 09:14:25 +00001957 wsi->protocol->callback(this, wsi,
Andy Green8f037e42010-12-19 22:13:26 +00001958 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +00001959 wsi->user_space,
Andy Greenb45993c2010-12-18 15:13:50 +00001960 buf, len);
Andy Green0d338332011-02-12 11:57:43 +00001961 }
Andy Greenb45993c2010-12-18 15:13:50 +00001962 }
1963
1964 return 0;
1965 }
1966
Andy Green0ca6a172010-12-19 20:50:01 +00001967 /*
1968 * We're being called from a different process context than the server
1969 * loop. Instead of broadcasting directly, we send our
1970 * payload on a socket to do the IPC; the server process will serialize
1971 * the broadcast action in its main poll() loop.
1972 *
1973 * There's one broadcast socket listening for each protocol supported
1974 * set up when the websocket server initializes
1975 */
1976
Andy Green6964bb52011-01-23 16:50:33 +00001977 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
Andy Greenb45993c2010-12-18 15:13:50 +00001978
1979 return n;
1980}