blob: 0e648179d98be36bcc1c99209fa52ae23ed8002f [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 Greenff95d7a2010-10-28 22:36:01 +010023
Andy Greenbe93fef2011-02-14 20:25:43 +000024/*
25 * In-place str to lower case
26 */
27
28static void
29strtolower(char *s)
30{
31 while (*s) {
32 *s = tolower(*s);
33 s++;
34 }
35}
36
Andy Green0d338332011-02-12 11:57:43 +000037/* file descriptor hash management */
38
39struct libwebsocket *
40wsi_from_fd(struct libwebsocket_context *this, int fd)
41{
42 int h = LWS_FD_HASH(fd);
43 int n = 0;
44
45 for (n = 0; n < this->fd_hashtable[h].length; n++)
46 if (this->fd_hashtable[h].wsi[n]->sock == fd)
47 return this->fd_hashtable[h].wsi[n];
48
49 return NULL;
50}
51
52int
53insert_wsi(struct libwebsocket_context *this, struct libwebsocket *wsi)
54{
55 int h = LWS_FD_HASH(wsi->sock);
56
57 if (this->fd_hashtable[h].length == MAX_CLIENTS - 1) {
58 fprintf(stderr, "hash table overflow\n");
59 return 1;
60 }
61
62 this->fd_hashtable[h].wsi[this->fd_hashtable[h].length++] = wsi;
63
64 return 0;
65}
66
67int
68delete_from_fd(struct libwebsocket_context *this, int fd)
69{
70 int h = LWS_FD_HASH(fd);
71 int n = 0;
72
73 for (n = 0; n < this->fd_hashtable[h].length; n++)
74 if (this->fd_hashtable[h].wsi[n]->sock == fd) {
75 while (n < this->fd_hashtable[h].length) {
76 this->fd_hashtable[h].wsi[n] =
77 this->fd_hashtable[h].wsi[n + 1];
78 n++;
79 }
80 this->fd_hashtable[h].length--;
81
82 return 0;
83 }
84
85 fprintf(stderr, "Failed to find fd %d requested for "
86 "delete in hashtable\n", fd);
87 return 1;
88}
89
90
Andy Green8f037e42010-12-19 22:13:26 +000091void
Andy Green4b6fbe12011-02-14 08:03:48 +000092libwebsocket_close_and_free_session(struct libwebsocket_context *this,
93 struct libwebsocket *wsi)
Andy Green251f6fa2010-11-03 11:13:06 +000094{
Andy Greenb45993c2010-12-18 15:13:50 +000095 int n;
Andy Green62c54d22011-02-14 09:14:25 +000096 int old_state;
Andy Green5e1fa172011-02-10 09:07:05 +000097 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
98 LWS_SEND_BUFFER_POST_PADDING];
Andy Greenb45993c2010-12-18 15:13:50 +000099
Andy Green4b6fbe12011-02-14 08:03:48 +0000100 if (!wsi)
Andy Greenb45993c2010-12-18 15:13:50 +0000101 return;
102
Andy Green62c54d22011-02-14 09:14:25 +0000103 old_state = wsi->state;
Andy Green251f6fa2010-11-03 11:13:06 +0000104
Andy Green62c54d22011-02-14 09:14:25 +0000105 if (old_state == WSI_STATE_DEAD_SOCKET)
Andy Green5e1fa172011-02-10 09:07:05 +0000106 return;
107
Andy Green4b6fbe12011-02-14 08:03:48 +0000108 /* remove this fd from wsi mapping hashtable */
109
110 delete_from_fd(this, wsi->sock);
111
112 /* delete it from the internal poll list if still present */
113
114 for (n = 0; n < this->fds_count; n++) {
115 if (this->fds[n].fd != wsi->sock)
116 continue;
117 while (n < this->fds_count - 1) {
118 this->fds[n] = this->fds[n + 1];
119 n++;
120 }
121 this->fds_count--;
122 /* we only have to deal with one */
123 n = this->fds_count;
124 }
125
126 /* remove also from external POLL support via protocol 0 */
127
Andy Green62c54d22011-02-14 09:14:25 +0000128 this->protocols[0].callback(this, wsi,
Andy Green4b6fbe12011-02-14 08:03:48 +0000129 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
130
Andy Green5e1fa172011-02-10 09:07:05 +0000131 /*
132 * signal we are closing, libsocket_write will
133 * add any necessary version-specific stuff. If the write fails,
134 * no worries we are closing anyway. If we didn't initiate this
135 * close, then our state has been changed to
Andy Green4b6fbe12011-02-14 08:03:48 +0000136 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this
Andy Green5e1fa172011-02-10 09:07:05 +0000137 */
138
Andy Green62c54d22011-02-14 09:14:25 +0000139 if (old_state == WSI_STATE_ESTABLISHED)
Andy Green5e1fa172011-02-10 09:07:05 +0000140 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
141 LWS_WRITE_CLOSE);
142
Andy Green251f6fa2010-11-03 11:13:06 +0000143 wsi->state = WSI_STATE_DEAD_SOCKET;
144
Andy Green4b6fbe12011-02-14 08:03:48 +0000145 /* tell the user it's all over for this guy */
146
Andy Green62c54d22011-02-14 09:14:25 +0000147 if (wsi->protocol->callback && old_state == WSI_STATE_ESTABLISHED)
148 wsi->protocol->callback(this, wsi, LWS_CALLBACK_CLOSED,
Andy Greene77ddd82010-11-13 10:03:47 +0000149 wsi->user_space, NULL, 0);
Andy Green251f6fa2010-11-03 11:13:06 +0000150
Andy Green4b6fbe12011-02-14 08:03:48 +0000151 /* free up his allocations */
152
Andy Green251f6fa2010-11-03 11:13:06 +0000153 for (n = 0; n < WSI_TOKEN_COUNT; n++)
154 if (wsi->utf8_token[n].token)
155 free(wsi->utf8_token[n].token);
156
Andy Green0ca6a172010-12-19 20:50:01 +0000157/* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
Andy Green251f6fa2010-11-03 11:13:06 +0000158
Andy Green3faa9c72010-11-08 17:03:03 +0000159#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +0000160 if (wsi->ssl) {
Andy Green3faa9c72010-11-08 17:03:03 +0000161 n = SSL_get_fd(wsi->ssl);
162 SSL_shutdown(wsi->ssl);
163 close(n);
164 SSL_free(wsi->ssl);
165 } else {
166#endif
167 shutdown(wsi->sock, SHUT_RDWR);
168 close(wsi->sock);
169#ifdef LWS_OPENSSL_SUPPORT
170 }
171#endif
Andy Green4f3943a2010-11-12 10:44:16 +0000172 if (wsi->user_space)
173 free(wsi->user_space);
174
Andy Green251f6fa2010-11-03 11:13:06 +0000175 free(wsi);
176}
177
Andy Green07034092011-02-13 08:37:12 +0000178/**
Andy Greenf7ee5492011-02-13 09:04:21 +0000179 * libwebsockets_hangup_on_client() - Server calls to terminate client
180 * connection
181 * @this: libwebsockets context
182 * @fd: Connection socket descriptor
183 */
184
185void
186libwebsockets_hangup_on_client(struct libwebsocket_context *this, int fd)
187{
188 struct libwebsocket *wsi = wsi_from_fd(this, fd);
Andy Greende6ab322011-02-13 09:15:10 +0000189 int n;
Andy Greenf7ee5492011-02-13 09:04:21 +0000190
191 if (wsi == NULL)
192 return;
193
Andy Greende6ab322011-02-13 09:15:10 +0000194 delete_from_fd(this, fd);
195
196 for (n = 0; n < this->fds_count - 1; n++)
197 if (this->fds[n].fd == fd) {
198 while (n < this->fds_count - 1) {
199 this->fds[n] = this->fds[n + 1];
200 n++;
201 }
202 n = this->fds_count;
203 this->fds_count--;
204 }
205
Andy Green4b6fbe12011-02-14 08:03:48 +0000206 libwebsocket_close_and_free_session(this, wsi);
Andy Greenf7ee5492011-02-13 09:04:21 +0000207}
208
209
210/**
Andy Green07034092011-02-13 08:37:12 +0000211 * libwebsockets_get_peer_addresses() - Get client address information
212 * @fd: Connection socket descriptor
213 * @name: Buffer to take client address name
214 * @name_len: Length of client address name buffer
215 * @rip: Buffer to take client address IP qotted quad
216 * @rip_len: Length of client address IP buffer
217 *
218 * This function fills in @name and @rip with the name and IP of
219 * the client connected with socket descriptor @fd. Names may be
220 * truncated if there is not enough room. If either cannot be
221 * determined, they will be returned as valid zero-length strings.
222 */
223
224void
225libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
226 char *rip, int rip_len)
227{
228 unsigned int len;
229 struct sockaddr_in sin;
230 struct hostent *host;
231 struct hostent *host1;
232 char ip[128];
233 char *p;
234 int n;
235
236 rip[0] = '\0';
237 name[0] = '\0';
238
239 len = sizeof sin;
240 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
241 perror("getpeername");
242 return;
243 }
244
245 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
246 AF_INET);
247 if (host == NULL) {
248 perror("gethostbyaddr");
249 return;
250 }
251
252 strncpy(name, host->h_name, name_len);
253 name[name_len - 1] = '\0';
254
255 host1 = gethostbyname(host->h_name);
256 if (host1 == NULL)
257 return;
258 p = (char *)host1;
259 n = 0;
260 while (p != NULL) {
261 p = host1->h_addr_list[n++];
262 if (p == NULL)
263 continue;
264 if (host1->h_addrtype != AF_INET)
265 continue;
266
267 sprintf(ip, "%d.%d.%d.%d",
268 p[0], p[1], p[2], p[3]);
269 p = NULL;
270 strncpy(rip, ip, rip_len);
271 rip[rip_len - 1] = '\0';
272 }
273}
Andy Green9f990342011-02-12 11:57:45 +0000274
275/**
276 * libwebsocket_service_fd() - Service polled socket with something waiting
277 * @this: Websocket context
278 * @pollfd: The pollfd entry describing the socket fd and which events
279 * happened.
280 *
281 * This function closes any active connections and then frees the
282 * context. After calling this, any further use of the context is
283 * undefined.
284 */
285
286int
Andy Green0d338332011-02-12 11:57:43 +0000287libwebsocket_service_fd(struct libwebsocket_context *this,
288 struct pollfd *pollfd)
Andy Greenb45993c2010-12-18 15:13:50 +0000289{
290 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
291 LWS_SEND_BUFFER_POST_PADDING];
Andy Greena71eafc2011-02-14 17:59:43 +0000292 struct libwebsocket *wsi;
Andy Green0d338332011-02-12 11:57:43 +0000293 struct libwebsocket *new_wsi;
Andy Greenb45993c2010-12-18 15:13:50 +0000294 int n;
Andy Green0d338332011-02-12 11:57:43 +0000295 int m;
Andy Greenb45993c2010-12-18 15:13:50 +0000296 size_t len;
Andy Green0d338332011-02-12 11:57:43 +0000297 int accept_fd;
298 unsigned int clilen;
299 struct sockaddr_in cli_addr;
Andy Greena71eafc2011-02-14 17:59:43 +0000300 struct timeval tv;
Andy Greenbe93fef2011-02-14 20:25:43 +0000301 static const char magic_websocket_guid[] =
302 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
303 static const char magic_websocket_04_masking_guid[] =
304 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
305 char hash[20];
306 char pkt[1024];
307 char *p = &pkt[0];
308 const char *pc;
309 int okay = 0;
310#ifdef LWS_OPENSSL_SUPPORT
311 char ssl_err_buf[512];
312#endif
Andy Greena71eafc2011-02-14 17:59:43 +0000313 /*
314 * you can call us with pollfd = NULL to just allow the once-per-second
315 * global timeout checks; if less than a second since the last check
316 * it returns immediately then.
317 */
318
319 gettimeofday(&tv, NULL);
320
321 if (this->last_timeout_check_s != tv.tv_sec) {
322 this->last_timeout_check_s = tv.tv_sec;
323
324 /* global timeout check once per second */
325
326 for (n = 0; n < this->fds_count; n++) {
327 wsi = wsi_from_fd(this, this->fds[n].fd);
328 if (!wsi->pending_timeout)
329 continue;
330
331 /*
332 * if we went beyond the allowed time, kill the
333 * connection
334 */
335
336 if (tv.tv_sec > wsi->pending_timeout_limit)
337 libwebsocket_close_and_free_session(this, wsi);
338 }
339 }
340
341 /* just here for timeout management? */
342
343 if (pollfd == NULL)
344 return 0;
345
346 /* no, here to service a socket descriptor */
347
348 wsi = wsi_from_fd(this, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +0000349
Andy Green0d338332011-02-12 11:57:43 +0000350 if (wsi == NULL)
351 return 1;
Andy Green8f037e42010-12-19 22:13:26 +0000352
Andy Green0d338332011-02-12 11:57:43 +0000353 switch (wsi->mode) {
354 case LWS_CONNMODE_SERVER_LISTENER:
355
356 /* pollin means a client has connected to us then */
357
358 if (!pollfd->revents & POLLIN)
359 break;
360
361 /* listen socket got an unencrypted connection... */
362
363 clilen = sizeof(cli_addr);
364 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
365 &clilen);
366 if (accept_fd < 0) {
367 fprintf(stderr, "ERROR on accept");
368 break;
369 }
370
371 if (this->fds_count >= MAX_CLIENTS) {
Andy Green3221f922011-02-12 13:14:11 +0000372 fprintf(stderr, "too busy to accept new client\n");
Andy Green0d338332011-02-12 11:57:43 +0000373 close(accept_fd);
374 break;
375 }
376
Andy Green07034092011-02-13 08:37:12 +0000377 /*
378 * look at who we connected to and give user code a chance
379 * to reject based on client IP. There's no protocol selected
380 * yet so we issue this to protocols[0]
381 */
382
Andy Green62c54d22011-02-14 09:14:25 +0000383 if ((this->protocols[0].callback)(this, wsi,
Andy Green07034092011-02-13 08:37:12 +0000384 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
385 (void*)(long)accept_fd, NULL, 0)) {
386 fprintf(stderr, "Callback denied network connection\n");
387 close(accept_fd);
388 break;
389 }
390
Andy Green0d338332011-02-12 11:57:43 +0000391 /* accepting connection to main listener */
392
393 new_wsi = malloc(sizeof(struct libwebsocket));
394 if (new_wsi == NULL) {
395 fprintf(stderr, "Out of memory for new connection\n");
396 break;
397 }
398
399 memset(new_wsi, 0, sizeof (struct libwebsocket));
400 new_wsi->sock = accept_fd;
Andy Greena71eafc2011-02-14 17:59:43 +0000401 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
Andy Green0d338332011-02-12 11:57:43 +0000402
403#ifdef LWS_OPENSSL_SUPPORT
404 new_wsi->ssl = NULL;
405 this->ssl_ctx = NULL;
406
407 if (this->use_ssl) {
408
409 new_wsi->ssl = SSL_new(this->ssl_ctx);
410 if (new_wsi->ssl == NULL) {
411 fprintf(stderr, "SSL_new failed: %s\n",
412 ERR_error_string(SSL_get_error(
413 new_wsi->ssl, 0), NULL));
414 free(new_wsi);
415 break;
416 }
417
418 SSL_set_fd(new_wsi->ssl, accept_fd);
419
420 n = SSL_accept(new_wsi->ssl);
421 if (n != 1) {
422 /*
423 * browsers seem to probe with various
424 * ssl params which fail then retry
425 * and succeed
426 */
427 debug("SSL_accept failed skt %u: %s\n",
428 pollfd->fd,
429 ERR_error_string(SSL_get_error(
430 new_wsi->ssl, n), NULL));
431 SSL_free(
432 new_wsi->ssl);
433 free(new_wsi);
434 break;
435 }
436 debug("accepted new SSL conn "
437 "port %u on fd=%d SSL ver %s\n",
438 ntohs(cli_addr.sin_port), accept_fd,
439 SSL_get_version(new_wsi->ssl));
440
441 } else
442#endif
443 debug("accepted new conn port %u on fd=%d\n",
444 ntohs(cli_addr.sin_port), accept_fd);
445
446 /* intialize the instance struct */
447
448 new_wsi->state = WSI_STATE_HTTP;
449 new_wsi->name_buffer_pos = 0;
450 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
451
452 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
453 new_wsi->utf8_token[n].token = NULL;
454 new_wsi->utf8_token[n].token_len = 0;
455 }
456
457 /*
458 * these can only be set once the protocol is known
459 * we set an unestablished connection's protocol pointer
460 * to the start of the supported list, so it can look
461 * for matching ones during the handshake
462 */
463 new_wsi->protocol = this->protocols;
464 new_wsi->user_space = NULL;
465
466 /*
467 * Default protocol is 76 / 00
468 * After 76, there's a header specified to inform which
469 * draft the client wants, when that's seen we modify
470 * the individual connection's spec revision accordingly
471 */
472 new_wsi->ietf_spec_revision = 0;
473
474 insert_wsi(this, new_wsi);
475
Andy Green0d338332011-02-12 11:57:43 +0000476 /*
477 * make sure NO events are seen yet on this new socket
478 * (otherwise we inherit old fds[client].revents from
479 * previous socket there and die mysteriously! )
480 */
481 this->fds[this->fds_count].revents = 0;
482
483 this->fds[this->fds_count].events = POLLIN;
484 this->fds[this->fds_count++].fd = accept_fd;
485
Andy Green3221f922011-02-12 13:14:11 +0000486 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +0000487 this->protocols[0].callback(this, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +0000488 LWS_CALLBACK_ADD_POLL_FD,
489 (void *)(long)accept_fd, NULL, POLLIN);
490
Andy Green0d338332011-02-12 11:57:43 +0000491 break;
492
493 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
494
495 /* as we are listening, POLLIN means accept() is needed */
496
497 if (!pollfd->revents & POLLIN)
498 break;
499
500 /* listen socket got an unencrypted connection... */
501
502 clilen = sizeof(cli_addr);
503 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
504 &clilen);
505 if (accept_fd < 0) {
506 fprintf(stderr, "ERROR on accept");
507 break;
508 }
509
510 if (this->fds_count >= MAX_CLIENTS) {
Andy Green3221f922011-02-12 13:14:11 +0000511 fprintf(stderr, "too busy to accept new broadcast "
512 "proxy client\n");
Andy Green0d338332011-02-12 11:57:43 +0000513 close(accept_fd);
514 break;
515 }
516
517 /* create a dummy wsi for the connection and add it */
518
519 new_wsi = malloc(sizeof(struct libwebsocket));
520 memset(new_wsi, 0, sizeof (struct libwebsocket));
521 new_wsi->sock = accept_fd;
522 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
523 new_wsi->state = WSI_STATE_ESTABLISHED;
524 /* note which protocol we are proxying */
525 new_wsi->protocol_index_for_broadcast_proxy =
526 wsi->protocol_index_for_broadcast_proxy;
527 insert_wsi(this, new_wsi);
528
529 /* add connected socket to internal poll array */
530
531 this->fds[this->fds_count].revents = 0;
532 this->fds[this->fds_count].events = POLLIN;
533 this->fds[this->fds_count++].fd = accept_fd;
534
Andy Green3221f922011-02-12 13:14:11 +0000535 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +0000536 this->protocols[0].callback(this, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +0000537 LWS_CALLBACK_ADD_POLL_FD,
538 (void *)(long)accept_fd, NULL, POLLIN);
539
Andy Green0d338332011-02-12 11:57:43 +0000540 break;
541
542 case LWS_CONNMODE_BROADCAST_PROXY:
Andy Green8f037e42010-12-19 22:13:26 +0000543
Andy Greenb45993c2010-12-18 15:13:50 +0000544 /* handle session socket closed */
Andy Green8f037e42010-12-19 22:13:26 +0000545
Andy Green0d338332011-02-12 11:57:43 +0000546 if (pollfd->revents & (POLLERR | POLLHUP)) {
Andy Green8f037e42010-12-19 22:13:26 +0000547
Andy Green0d338332011-02-12 11:57:43 +0000548 debug("Session Socket %p (fd=%d) dead\n",
Timothy J Fontaineb86d64e2011-02-14 17:55:27 +0000549 (void *)wsi, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +0000550
Andy Green4b6fbe12011-02-14 08:03:48 +0000551 libwebsocket_close_and_free_session(this, wsi);
552 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +0000553 }
Andy Green8f037e42010-12-19 22:13:26 +0000554
Andy Green90c7cbc2011-01-27 06:26:52 +0000555 /* the guy requested a callback when it was OK to write */
556
Andy Green0d338332011-02-12 11:57:43 +0000557 if (pollfd->revents & POLLOUT) {
Andy Green90c7cbc2011-01-27 06:26:52 +0000558
Andy Green0d338332011-02-12 11:57:43 +0000559 /* one shot */
Andy Green90c7cbc2011-01-27 06:26:52 +0000560
Andy Green0d338332011-02-12 11:57:43 +0000561 pollfd->events &= ~POLLOUT;
562
Andy Green3221f922011-02-12 13:14:11 +0000563 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +0000564 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +0000565 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
566 (void *)(long)wsi->sock, NULL, POLLOUT);
567
Andy Green62c54d22011-02-14 09:14:25 +0000568 wsi->protocol->callback(this, wsi,
Andy Green90c7cbc2011-01-27 06:26:52 +0000569 LWS_CALLBACK_CLIENT_WRITEABLE,
Andy Green0d338332011-02-12 11:57:43 +0000570 wsi->user_space,
Andy Green90c7cbc2011-01-27 06:26:52 +0000571 NULL, 0);
572 }
573
Andy Greenb45993c2010-12-18 15:13:50 +0000574 /* any incoming data ready? */
575
Andy Green0d338332011-02-12 11:57:43 +0000576 if (!(pollfd->revents & POLLIN))
577 break;
Andy Greenb45993c2010-12-18 15:13:50 +0000578
Andy Green0d338332011-02-12 11:57:43 +0000579 /* get the issued broadcast payload from the socket */
Andy Greenb45993c2010-12-18 15:13:50 +0000580
Andy Green0d338332011-02-12 11:57:43 +0000581 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
582 MAX_BROADCAST_PAYLOAD);
583 if (len < 0) {
584 fprintf(stderr, "Error reading broadcast payload\n");
Andy Green4b6fbe12011-02-14 08:03:48 +0000585 break;
Andy Green0d338332011-02-12 11:57:43 +0000586 }
Andy Greenb45993c2010-12-18 15:13:50 +0000587
Andy Green0d338332011-02-12 11:57:43 +0000588 /* broadcast it to all guys with this protocol index */
Andy Green8f037e42010-12-19 22:13:26 +0000589
Andy Green0d338332011-02-12 11:57:43 +0000590 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Green8f037e42010-12-19 22:13:26 +0000591
Andy Green0d338332011-02-12 11:57:43 +0000592 for (m = 0; m < this->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +0000593
Andy Green0d338332011-02-12 11:57:43 +0000594 new_wsi = this->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +0000595
Andy Green0d338332011-02-12 11:57:43 +0000596 /* only to clients we are serving to */
Andy Greenb45993c2010-12-18 15:13:50 +0000597
Andy Green0d338332011-02-12 11:57:43 +0000598 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
Andy Greenb45993c2010-12-18 15:13:50 +0000599 continue;
600
601 /*
602 * never broadcast to non-established
603 * connection
604 */
605
Andy Green0d338332011-02-12 11:57:43 +0000606 if (new_wsi->state != WSI_STATE_ESTABLISHED)
Andy Green4739e5c2011-01-22 12:51:57 +0000607 continue;
608
Andy Greenb45993c2010-12-18 15:13:50 +0000609 /*
610 * only broadcast to connections using
611 * the requested protocol
612 */
613
Andy Green0d338332011-02-12 11:57:43 +0000614 if (new_wsi->protocol->protocol_index !=
615 wsi->protocol_index_for_broadcast_proxy)
Andy Greenb45993c2010-12-18 15:13:50 +0000616 continue;
617
Andy Green8f037e42010-12-19 22:13:26 +0000618 /* broadcast it to this connection */
619
Andy Green62c54d22011-02-14 09:14:25 +0000620 new_wsi->protocol->callback(this, new_wsi,
Andy Green8f037e42010-12-19 22:13:26 +0000621 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +0000622 new_wsi->user_space,
Andy Green0ca6a172010-12-19 20:50:01 +0000623 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
Andy Greenb45993c2010-12-18 15:13:50 +0000624 }
Andy Green0d338332011-02-12 11:57:43 +0000625 }
626 break;
Andy Greenb45993c2010-12-18 15:13:50 +0000627
Andy Greenbe93fef2011-02-14 20:25:43 +0000628 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
629
630 /* handle proxy hung up on us */
631
632 if (pollfd->revents & (POLLERR | POLLHUP)) {
633
634 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
635 (void *)wsi, pollfd->fd);
636
637 libwebsocket_close_and_free_session(this, wsi);
638 return 1;
639 }
640
641 n = recv(wsi->sock, pkt, sizeof pkt, 0);
642 if (n < 0) {
643 libwebsocket_close_and_free_session(this, wsi);
644 fprintf(stderr, "ERROR reading from proxy socket\n");
645 return 1;
646 }
647
648 pkt[13] = '\0';
649 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
650 libwebsocket_close_and_free_session(this, wsi);
651 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
652 return 1;
653 }
654
655 /* clear his proxy connection timeout */
656
657 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
658
659 /* fallthru */
660
661 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
662
663 #ifdef LWS_OPENSSL_SUPPORT
664 if (wsi->use_ssl) {
665
666 wsi->ssl = SSL_new(this->ssl_client_ctx);
667 wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
668 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
669
670 if (SSL_connect(wsi->ssl) <= 0) {
671 fprintf(stderr, "SSL connect error %s\n",
672 ERR_error_string(ERR_get_error(), ssl_err_buf));
673 libwebsocket_close_and_free_session(this, wsi);
674 return 1;
675 }
676
677 n = SSL_get_verify_result(wsi->ssl);
678 if (n != X509_V_OK) {
679 if (n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
680 wsi->use_ssl != 2) {
681
682 fprintf(stderr, "server's cert didn't "
683 "look good %d\n", n);
684 libwebsocket_close_and_free_session(this, wsi);
685 return 1;
686 }
687 }
688 } else {
689 wsi->ssl = NULL;
690 #endif
691
692
693 #ifdef LWS_OPENSSL_SUPPORT
694 }
695 #endif
696
697 /*
698 * create the random key
699 */
700
701 n = read(this->fd_random, hash, 16);
702 if (n != 16) {
703 fprintf(stderr, "Unable to read from random dev %s\n",
704 SYSTEM_RANDOM_FILEPATH);
705 free(wsi->c_path);
706 free(wsi->c_host);
707 free(wsi->c_origin);
708 if (wsi->c_protocol)
709 free(wsi->c_protocol);
710 libwebsocket_close_and_free_session(this, wsi);
711 return 1;
712 }
713
714 lws_b64_encode_string(hash, 16, wsi->key_b64,
715 sizeof wsi->key_b64);
716
717 /*
718 * 04 example client handshake
719 *
720 * GET /chat HTTP/1.1
721 * Host: server.example.com
722 * Upgrade: websocket
723 * Connection: Upgrade
724 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
725 * Sec-WebSocket-Origin: http://example.com
726 * Sec-WebSocket-Protocol: chat, superchat
727 * Sec-WebSocket-Version: 4
728 */
729
730 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
731 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
732 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
733 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
734 "Sec-WebSocket-Key: ");
735 strcpy(p, wsi->key_b64);
736 p += strlen(wsi->key_b64);
737 p += sprintf(p, "\x0d\x0aSec-WebSocket-Origin: %s\x0d\x0a",
738 wsi->c_origin);
739 if (wsi->c_protocol != NULL)
740 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
741 wsi->c_protocol);
742 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a\x0d\x0a",
743 wsi->ietf_spec_revision);
744
745 /* done with these now */
746
747 free(wsi->c_path);
748 free(wsi->c_host);
749 free(wsi->c_origin);
750
751 /* prepare the expected server accept response */
752
753 strcpy((char *)buf, wsi->key_b64);
754 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
755
756 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
757
758 lws_b64_encode_string(hash, 20,
759 wsi->initial_handshake_hash_base64,
760 sizeof wsi->initial_handshake_hash_base64);
761
762 /* send our request to the server */
763
764 #ifdef LWS_OPENSSL_SUPPORT
765 if (wsi->use_ssl)
766 n = SSL_write(wsi->ssl, pkt, p - pkt);
767 else
768 #endif
769 n = send(wsi->sock, pkt, p - pkt, 0);
770
771 if (n < 0) {
772 fprintf(stderr, "ERROR writing to client socket\n");
773 libwebsocket_close_and_free_session(this, wsi);
774 return 1;
775 }
776
777 wsi->parser_state = WSI_TOKEN_NAME_PART;
778 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
779 libwebsocket_set_timeout(wsi,
780 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
781
782 break;
783
784 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
785
786 /* handle server hung up on us */
787
788 if (pollfd->revents & (POLLERR | POLLHUP)) {
789
790 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
791 (void *)wsi, pollfd->fd);
792
793 goto bail3;
794 }
795
796
797 /* interpret the server response */
798
799 /*
800 * HTTP/1.1 101 Switching Protocols
801 * Upgrade: websocket
802 * Connection: Upgrade
803 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
804 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
805 * Sec-WebSocket-Protocol: chat
806 */
807
808 #ifdef LWS_OPENSSL_SUPPORT
809 if (wsi->use_ssl)
810 len = SSL_read(wsi->ssl, pkt, sizeof pkt);
811 else
812 #endif
813 len = recv(wsi->sock, pkt, sizeof pkt, 0);
814
815 if (len < 0) {
816 fprintf(stderr,
817 "libwebsocket_client_handshake read error\n");
818 goto bail3;
819 }
820
821 p = pkt;
822 for (n = 0; n < len; n++)
823 libwebsocket_parse(wsi, *p++);
824
825 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
826 fprintf(stderr, "libwebsocket_client_handshake "
827 "server response ailed parsing\n");
828 goto bail3;
829 }
830
831 /*
832 * well, what the server sent looked reasonable for syntax.
833 * Now let's confirm it sent all the necessary headers
834 */
835
836 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
837 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
838 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
839 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
840 !wsi->utf8_token[WSI_TOKEN_NONCE].token_len ||
841 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
842 wsi->c_protocol != NULL)) {
843 fprintf(stderr, "libwebsocket_client_handshake "
844 "missing required header(s)\n");
845 pkt[len] = '\0';
846 fprintf(stderr, "%s", pkt);
847 goto bail3;
848 }
849
850 /*
851 * Everything seems to be there, now take a closer look at what
852 * is in each header
853 */
854
855 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
856 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
857 "101 switching protocols")) {
858 fprintf(stderr, "libwebsocket_client_handshake "
859 "server sent bad HTTP response '%s'\n",
860 wsi->utf8_token[WSI_TOKEN_HTTP].token);
861 goto bail3;
862 }
863
864 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
865 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
866 "websocket")) {
867 fprintf(stderr, "libwebsocket_client_handshake server "
868 "sent bad Upgrade header '%s'\n",
869 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
870 goto bail3;
871 }
872
873 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
874 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
875 "upgrade")) {
876 fprintf(stderr, "libwebsocket_client_handshake server "
877 "sent bad Connection hdr '%s'\n",
878 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
879 goto bail3;
880 }
881
882
883 pc = wsi->c_protocol;
884
885 /*
886 * confirm the protocol the server wants to talk was in the list
887 * of protocols we offered
888 */
889
890 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
891
892 /*
893 * no protocol name to work from,
894 * default to first protocol
895 */
896 wsi->protocol = &this->protocols[0];
897
898 free(wsi->c_protocol);
899
900 goto check_accept;
901 }
902
903 while (*pc && !okay) {
904 if ((!strncmp(pc,
905 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
906 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
907 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
908 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
909 okay = 1;
910 continue;
911 }
912 while (*pc && *pc != ',')
913 pc++;
914 while (*pc && *pc != ' ')
915 pc++;
916 }
917
918 /* done with him now */
919
920 if (wsi->c_protocol)
921 free(wsi->c_protocol);
922
923
924 if (!okay) {
925 fprintf(stderr, "libwebsocket_client_handshake server "
926 "sent bad protocol '%s'\n",
927 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
928 goto bail2;
929 }
930
931 /*
932 * identify the selected protocol struct and set it
933 */
934 n = 0;
935 wsi->protocol = NULL;
936 while (this->protocols[n].callback) {
937 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
938 this->protocols[n].name) == 0)
939 wsi->protocol = &this->protocols[n];
940 n++;
941 }
942
943 if (wsi->protocol == NULL) {
944 fprintf(stderr, "libwebsocket_client_handshake server "
945 "requested protocol '%s', which we "
946 "said we supported but we don't!\n",
947 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
948 goto bail2;
949 }
950
951 check_accept:
952 /*
953 * Confirm his accept token is the one we precomputed
954 */
955
956 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
957 wsi->initial_handshake_hash_base64)) {
958 fprintf(stderr, "libwebsocket_client_handshake server "
959 "sent bad ACCEPT '%s' vs computed '%s'\n",
960 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
961 wsi->initial_handshake_hash_base64);
962 goto bail2;
963 }
964
965 /*
966 * Calculate the masking key to use when sending data to server
967 */
968
969 strcpy((char *)buf, wsi->key_b64);
970 p = (char *)buf + strlen(wsi->key_b64);
971 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
972 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
973 strcpy(p, magic_websocket_04_masking_guid);
974 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
975
976 /* allocate the per-connection user memory (if any) */
977
978 if (wsi->protocol->per_session_data_size) {
979 wsi->user_space = malloc(
980 wsi->protocol->per_session_data_size);
981 if (wsi->user_space == NULL) {
982 fprintf(stderr, "Out of memory for "
983 "conn user space\n");
984 goto bail2;
985 }
986 } else
987 wsi->user_space = NULL;
988
989 /* clear his proxy connection timeout */
990
991 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
992
993 /* mark him as being alive */
994
995 wsi->state = WSI_STATE_ESTABLISHED;
996 wsi->mode = LWS_CONNMODE_WS_CLIENT;
997
998 fprintf(stderr, "handshake OK for protocol %s\n",
999 wsi->protocol->name);
1000
1001 /* call him back to inform him he is up */
1002
1003 wsi->protocol->callback(this, wsi,
1004 LWS_CALLBACK_CLIENT_ESTABLISHED,
1005 wsi->user_space,
1006 NULL, 0);
1007
1008 break;
1009
1010bail3:
1011 if (wsi->c_protocol)
1012 free(wsi->c_protocol);
1013
1014bail2:
1015 libwebsocket_close_and_free_session(this, wsi);
1016 return 1;
1017
1018
Andy Green0d338332011-02-12 11:57:43 +00001019 case LWS_CONNMODE_WS_SERVING:
1020 case LWS_CONNMODE_WS_CLIENT:
1021
1022 /* handle session socket closed */
1023
1024 if (pollfd->revents & (POLLERR | POLLHUP)) {
1025
Andy Green62c54d22011-02-14 09:14:25 +00001026 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
Andy Green0d338332011-02-12 11:57:43 +00001027 (void *)wsi, pollfd->fd);
1028
Andy Green4b6fbe12011-02-14 08:03:48 +00001029 libwebsocket_close_and_free_session(this, wsi);
1030 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001031 }
1032
Andy Green0d338332011-02-12 11:57:43 +00001033 /* the guy requested a callback when it was OK to write */
1034
1035 if (pollfd->revents & POLLOUT) {
1036
1037 pollfd->events &= ~POLLOUT;
1038
Andy Green3221f922011-02-12 13:14:11 +00001039 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001040 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001041 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1042 (void *)(long)wsi->sock, NULL, POLLOUT);
1043
Andy Green62c54d22011-02-14 09:14:25 +00001044 wsi->protocol->callback(this, wsi,
Andy Green0d338332011-02-12 11:57:43 +00001045 LWS_CALLBACK_CLIENT_WRITEABLE,
1046 wsi->user_space,
1047 NULL, 0);
1048 }
1049
1050 /* any incoming data ready? */
1051
1052 if (!(pollfd->revents & POLLIN))
1053 break;
1054
Andy Greenb45993c2010-12-18 15:13:50 +00001055#ifdef LWS_OPENSSL_SUPPORT
Andy Green0d338332011-02-12 11:57:43 +00001056 if (wsi->ssl)
1057 n = SSL_read(wsi->ssl, buf, sizeof buf);
Andy Greenb45993c2010-12-18 15:13:50 +00001058 else
1059#endif
Andy Green0d338332011-02-12 11:57:43 +00001060 n = recv(pollfd->fd, buf, sizeof buf, 0);
Andy Greenb45993c2010-12-18 15:13:50 +00001061
1062 if (n < 0) {
1063 fprintf(stderr, "Socket read returned %d\n", n);
Andy Green4b6fbe12011-02-14 08:03:48 +00001064 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001065 }
1066 if (!n) {
Andy Green4b6fbe12011-02-14 08:03:48 +00001067 libwebsocket_close_and_free_session(this, wsi);
1068 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001069 }
1070
Andy Greenb45993c2010-12-18 15:13:50 +00001071 /* service incoming data */
1072
Andy Green4b6fbe12011-02-14 08:03:48 +00001073 n = libwebsocket_read(this, wsi, buf, n);
Andy Green6964bb52011-01-23 16:50:33 +00001074 if (n >= 0)
Andy Green4b6fbe12011-02-14 08:03:48 +00001075 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001076
Andy Green4b6fbe12011-02-14 08:03:48 +00001077 /* we closed wsi */
Andy Green0d338332011-02-12 11:57:43 +00001078
Andy Green4b6fbe12011-02-14 08:03:48 +00001079 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001080 }
1081
1082 return 0;
1083}
1084
Andy Green0d338332011-02-12 11:57:43 +00001085
Andy Green6964bb52011-01-23 16:50:33 +00001086/**
1087 * libwebsocket_context_destroy() - Destroy the websocket context
1088 * @this: Websocket context
1089 *
1090 * This function closes any active connections and then frees the
1091 * context. After calling this, any further use of the context is
1092 * undefined.
1093 */
1094void
1095libwebsocket_context_destroy(struct libwebsocket_context *this)
1096{
Andy Green0d338332011-02-12 11:57:43 +00001097 int n;
1098 int m;
1099 struct libwebsocket *wsi;
Andy Green6964bb52011-01-23 16:50:33 +00001100
Andy Green4b6fbe12011-02-14 08:03:48 +00001101 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
Andy Green0d338332011-02-12 11:57:43 +00001102 for (m = 0; m < this->fd_hashtable[n].length; m++) {
Andy Green0d338332011-02-12 11:57:43 +00001103 wsi = this->fd_hashtable[n].wsi[m];
Andy Green4b6fbe12011-02-14 08:03:48 +00001104 libwebsocket_close_and_free_session(this, wsi);
Andy Greenf3d3b402011-02-09 07:16:34 +00001105 }
Andy Green6964bb52011-01-23 16:50:33 +00001106
Andy Green44eee682011-02-10 09:32:24 +00001107 close(this->fd_random);
1108
Andy Green6964bb52011-01-23 16:50:33 +00001109#ifdef LWS_OPENSSL_SUPPORT
Andy Green44eee682011-02-10 09:32:24 +00001110 if (this->ssl_ctx)
Andy Green90c7cbc2011-01-27 06:26:52 +00001111 SSL_CTX_free(this->ssl_ctx);
Andy Green44eee682011-02-10 09:32:24 +00001112 if (this->ssl_client_ctx)
Andy Green5e1fa172011-02-10 09:07:05 +00001113 SSL_CTX_free(this->ssl_client_ctx);
Andy Green6964bb52011-01-23 16:50:33 +00001114#endif
1115
Andy Green44eee682011-02-10 09:32:24 +00001116 free(this);
Andy Green6964bb52011-01-23 16:50:33 +00001117}
1118
1119/**
1120 * libwebsocket_service() - Service any pending websocket activity
1121 * @this: Websocket context
1122 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1123 * service otherwise block and service immediately, returning
1124 * after the timeout if nothing needed service.
1125 *
1126 * This function deals with any pending websocket traffic, for three
1127 * kinds of event. It handles these events on both server and client
1128 * types of connection the same.
1129 *
1130 * 1) Accept new connections to our context's server
1131 *
1132 * 2) Perform pending broadcast writes initiated from other forked
1133 * processes (effectively serializing asynchronous broadcasts)
1134 *
1135 * 3) Call the receive callback for incoming frame data received by
1136 * server or client connections.
1137 *
1138 * You need to call this service function periodically to all the above
1139 * functions to happen; if your application is single-threaded you can
1140 * just call it in your main event loop.
1141 *
1142 * Alternatively you can fork a new process that asynchronously handles
1143 * calling this service in a loop. In that case you are happy if this
1144 * call blocks your thread until it needs to take care of something and
1145 * would call it with a large nonzero timeout. Your loop then takes no
1146 * CPU while there is nothing happening.
1147 *
1148 * If you are calling it in a single-threaded app, you don't want it to
1149 * wait around blocking other things in your loop from happening, so you
1150 * would call it with a timeout_ms of 0, so it returns immediately if
1151 * nothing is pending, or as soon as it services whatever was pending.
1152 */
1153
Andy Greenb45993c2010-12-18 15:13:50 +00001154
Andy Greene92cd172011-01-19 13:11:55 +00001155int
1156libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
1157{
1158 int n;
Andy Greene92cd172011-01-19 13:11:55 +00001159
1160 /* stay dead once we are dead */
1161
1162 if (this == NULL)
1163 return 1;
1164
Andy Green0d338332011-02-12 11:57:43 +00001165 /* wait for something to need service */
Andy Green4739e5c2011-01-22 12:51:57 +00001166
Andy Green0d338332011-02-12 11:57:43 +00001167 n = poll(this->fds, this->fds_count, timeout_ms);
Andy Green3221f922011-02-12 13:14:11 +00001168 if (n == 0) /* poll timeout */
1169 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00001170
Andy Green62c54d22011-02-14 09:14:25 +00001171 if (n < 0) {
Andy Green5e1fa172011-02-10 09:07:05 +00001172 /*
Andy Greene92cd172011-01-19 13:11:55 +00001173 fprintf(stderr, "Listen Socket dead\n");
Andy Green5e1fa172011-02-10 09:07:05 +00001174 */
Andy Green0d338332011-02-12 11:57:43 +00001175 return 1;
Andy Greene92cd172011-01-19 13:11:55 +00001176 }
Andy Greene92cd172011-01-19 13:11:55 +00001177
1178 /* handle accept on listening socket? */
1179
Andy Green0d338332011-02-12 11:57:43 +00001180 for (n = 0; n < this->fds_count; n++)
1181 if (this->fds[n].revents)
1182 libwebsocket_service_fd(this, &this->fds[n]);
Andy Greene92cd172011-01-19 13:11:55 +00001183
1184 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00001185}
1186
Andy Green90c7cbc2011-01-27 06:26:52 +00001187/**
1188 * libwebsocket_callback_on_writable() - Request a callback when this socket
1189 * becomes able to be written to without
1190 * blocking
Andy Green3221f922011-02-12 13:14:11 +00001191 * *
Andy Green90c7cbc2011-01-27 06:26:52 +00001192 * @wsi: Websocket connection instance to get callback for
1193 */
1194
1195int
Andy Green62c54d22011-02-14 09:14:25 +00001196libwebsocket_callback_on_writable(struct libwebsocket_context *this,
1197 struct libwebsocket *wsi)
Andy Green90c7cbc2011-01-27 06:26:52 +00001198{
Andy Green90c7cbc2011-01-27 06:26:52 +00001199 int n;
1200
Andy Green0d338332011-02-12 11:57:43 +00001201 for (n = 0; n < this->fds_count; n++)
1202 if (this->fds[n].fd == wsi->sock) {
Andy Green90c7cbc2011-01-27 06:26:52 +00001203 this->fds[n].events |= POLLOUT;
Andy Green3221f922011-02-12 13:14:11 +00001204 n = this->fds_count;
Andy Green90c7cbc2011-01-27 06:26:52 +00001205 }
1206
Andy Green3221f922011-02-12 13:14:11 +00001207 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001208 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001209 LWS_CALLBACK_SET_MODE_POLL_FD,
1210 (void *)(long)wsi->sock, NULL, POLLOUT);
1211
Andy Green90c7cbc2011-01-27 06:26:52 +00001212 return 1;
1213}
1214
1215/**
1216 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1217 * all connections using the given protocol when it
1218 * becomes possible to write to each socket without
1219 * blocking in turn.
1220 *
1221 * @protocol: Protocol whose connections will get callbacks
1222 */
1223
1224int
1225libwebsocket_callback_on_writable_all_protocol(
1226 const struct libwebsocket_protocols *protocol)
1227{
1228 struct libwebsocket_context *this = protocol->owning_server;
1229 int n;
Andy Green0d338332011-02-12 11:57:43 +00001230 int m;
1231 struct libwebsocket *wsi;
Andy Green90c7cbc2011-01-27 06:26:52 +00001232
Andy Green0d338332011-02-12 11:57:43 +00001233 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1234
1235 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1236
1237 wsi = this->fd_hashtable[n].wsi[m];
1238
1239 if (wsi->protocol == protocol)
Andy Green62c54d22011-02-14 09:14:25 +00001240 libwebsocket_callback_on_writable(this, wsi);
Andy Green0d338332011-02-12 11:57:43 +00001241 }
1242 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001243
1244 return 0;
1245}
1246
Andy Greenbe93fef2011-02-14 20:25:43 +00001247/**
1248 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1249 *
1250 * You will not need this unless you are doing something special
1251 *
1252 * @wsi: Websocket connection instance
1253 * @reason: timeout reason
1254 * @secs: how many seconds
1255 */
1256
1257void
1258libwebsocket_set_timeout(struct libwebsocket *wsi,
1259 enum pending_timeout reason, int secs)
1260{
1261 struct timeval tv;
1262
1263 gettimeofday(&tv, NULL);
1264
1265 wsi->pending_timeout_limit = tv.tv_sec + secs;
1266 wsi->pending_timeout = reason;
1267}
1268
Andy Greena6cbece2011-01-27 20:06:03 +00001269
1270/**
1271 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1272 *
1273 * You will not need this unless you are doing something special
1274 *
1275 * @wsi: Websocket connection instance
1276 */
1277
1278int
1279libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1280{
1281 return wsi->sock;
1282}
1283
Andy Green90c7cbc2011-01-27 06:26:52 +00001284/**
1285 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1286 * receieved packets.
1287 *
1288 * If the output side of a server process becomes choked, this allows flow
1289 * control for the input side.
1290 *
1291 * @wsi: Websocket connection instance to get callback for
1292 * @enable: 0 = disable read servicing for this connection, 1 = enable
1293 */
1294
1295int
1296libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1297{
1298 struct libwebsocket_context *this = wsi->protocol->owning_server;
1299 int n;
1300
Andy Green0d338332011-02-12 11:57:43 +00001301 for (n = 0; n < this->fds_count; n++)
1302 if (this->fds[n].fd == wsi->sock) {
Andy Green90c7cbc2011-01-27 06:26:52 +00001303 if (enable)
1304 this->fds[n].events |= POLLIN;
1305 else
1306 this->fds[n].events &= ~POLLIN;
1307
1308 return 0;
1309 }
1310
Andy Green3221f922011-02-12 13:14:11 +00001311 if (enable)
1312 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001313 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001314 LWS_CALLBACK_SET_MODE_POLL_FD,
1315 (void *)(long)wsi->sock, NULL, POLLIN);
1316 else
1317 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001318 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001319 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1320 (void *)(long)wsi->sock, NULL, POLLIN);
1321
1322
Andy Green90c7cbc2011-01-27 06:26:52 +00001323 fprintf(stderr, "libwebsocket_callback_on_writable "
1324 "unable to find socket\n");
1325 return 1;
1326}
1327
Andy Green2ac5a6f2011-01-28 10:00:18 +00001328/**
1329 * libwebsocket_canonical_hostname() - returns this host's hostname
1330 *
1331 * This is typically used by client code to fill in the host parameter
1332 * when making a client connection. You can only call it after the context
1333 * has been created.
1334 *
1335 * @this: Websocket context
1336 */
1337
1338
1339extern const char *
1340libwebsocket_canonical_hostname(struct libwebsocket_context *this)
1341{
1342 return (const char *)this->canonical_hostname;
1343}
1344
1345
Andy Green90c7cbc2011-01-27 06:26:52 +00001346static void sigpipe_handler(int x)
1347{
1348}
1349
Andy Greenb45993c2010-12-18 15:13:50 +00001350
Andy Green0d338332011-02-12 11:57:43 +00001351
Andy Greenab990e42010-10-31 12:42:52 +00001352/**
Andy Green4739e5c2011-01-22 12:51:57 +00001353 * libwebsocket_create_context() - Create the websocket handler
1354 * @port: Port to listen on... you can use 0 to suppress listening on
Andy Green6964bb52011-01-23 16:50:33 +00001355 * any port, that's what you want if you are not running a
1356 * websocket server at all but just using it as a client
Andy Green4f3943a2010-11-12 10:44:16 +00001357 * @protocols: Array of structures listing supported protocols and a protocol-
Andy Green8f037e42010-12-19 22:13:26 +00001358 * specific callback for each one. The list is ended with an
1359 * entry that has a NULL callback pointer.
Andy Green6964bb52011-01-23 16:50:33 +00001360 * It's not const because we write the owning_server member
Andy Green3faa9c72010-11-08 17:03:03 +00001361 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
Andy Green8f037e42010-12-19 22:13:26 +00001362 * to listen using SSL, set to the filepath to fetch the
1363 * server cert from, otherwise NULL for unencrypted
Andy Green3faa9c72010-11-08 17:03:03 +00001364 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
Andy Green8f037e42010-12-19 22:13:26 +00001365 * else ignored
Andy Green3faa9c72010-11-08 17:03:03 +00001366 * @gid: group id to change to after setting listen socket, or -1.
1367 * @uid: user id to change to after setting listen socket, or -1.
Andy Greenbfb051f2011-02-09 08:49:14 +00001368 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
Andy Green05464c62010-11-12 10:44:18 +00001369 *
Andy Green8f037e42010-12-19 22:13:26 +00001370 * This function creates the listening socket and takes care
1371 * of all initialization in one step.
1372 *
Andy Greene92cd172011-01-19 13:11:55 +00001373 * After initialization, it returns a struct libwebsocket_context * that
1374 * represents this server. After calling, user code needs to take care
1375 * of calling libwebsocket_service() with the context pointer to get the
1376 * server's sockets serviced. This can be done in the same process context
1377 * or a forked process, or another thread,
Andy Green05464c62010-11-12 10:44:18 +00001378 *
Andy Green8f037e42010-12-19 22:13:26 +00001379 * The protocol callback functions are called for a handful of events
1380 * including http requests coming in, websocket connections becoming
1381 * established, and data arriving; it's also called periodically to allow
1382 * async transmission.
1383 *
1384 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1385 * at that time websocket protocol has not been negotiated. Other
1386 * protocols after the first one never see any HTTP callack activity.
1387 *
1388 * The server created is a simple http server by default; part of the
1389 * websocket standard is upgrading this http connection to a websocket one.
1390 *
1391 * This allows the same server to provide files like scripts and favicon /
1392 * images or whatever over http and dynamic data over websockets all in
1393 * one place; they're all handled in the user callback.
Andy Greenab990e42010-10-31 12:42:52 +00001394 */
Andy Green4ea60062010-10-30 12:15:07 +01001395
Andy Greene92cd172011-01-19 13:11:55 +00001396struct libwebsocket_context *
Andy Green4739e5c2011-01-22 12:51:57 +00001397libwebsocket_create_context(int port,
Andy Greenb45993c2010-12-18 15:13:50 +00001398 struct libwebsocket_protocols *protocols,
Andy Green8f037e42010-12-19 22:13:26 +00001399 const char *ssl_cert_filepath,
1400 const char *ssl_private_key_filepath,
Andy Green8014b292011-01-30 20:57:25 +00001401 int gid, int uid, unsigned int options)
Andy Greenff95d7a2010-10-28 22:36:01 +01001402{
1403 int n;
Andy Green4739e5c2011-01-22 12:51:57 +00001404 int sockfd = 0;
Andy Green251f6fa2010-11-03 11:13:06 +00001405 int fd;
Andy Greenff95d7a2010-10-28 22:36:01 +01001406 struct sockaddr_in serv_addr, cli_addr;
Andy Green251f6fa2010-11-03 11:13:06 +00001407 int opt = 1;
Andy Green8f037e42010-12-19 22:13:26 +00001408 struct libwebsocket_context *this = NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001409 unsigned int slen;
Andy Green9659f372011-01-27 22:01:43 +00001410 char *p;
Andy Green2ac5a6f2011-01-28 10:00:18 +00001411 char hostname[1024];
Andy Green42f69142011-01-30 08:10:02 +00001412 struct hostent *he;
Andy Green0d338332011-02-12 11:57:43 +00001413 struct libwebsocket *wsi;
Andy Greenff95d7a2010-10-28 22:36:01 +01001414
Andy Green3faa9c72010-11-08 17:03:03 +00001415#ifdef LWS_OPENSSL_SUPPORT
Andy Greenf2f54d52010-11-15 22:08:00 +00001416 SSL_METHOD *method;
Andy Green3faa9c72010-11-08 17:03:03 +00001417 char ssl_err_buf[512];
Andy Green3faa9c72010-11-08 17:03:03 +00001418#endif
1419
Andy Green90c7cbc2011-01-27 06:26:52 +00001420 this = malloc(sizeof(struct libwebsocket_context));
1421 if (!this) {
1422 fprintf(stderr, "No memory for websocket context\n");
1423 return NULL;
1424 }
1425 this->protocols = protocols;
1426 this->listen_port = port;
Andy Green9659f372011-01-27 22:01:43 +00001427 this->http_proxy_port = 0;
1428 this->http_proxy_address[0] = '\0';
Andy Green8014b292011-01-30 20:57:25 +00001429 this->options = options;
Andy Green0d338332011-02-12 11:57:43 +00001430 this->fds_count = 0;
Andy Green9659f372011-01-27 22:01:43 +00001431
Andy Green44eee682011-02-10 09:32:24 +00001432 this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1433 if (this->fd_random < 0) {
1434 fprintf(stderr, "Unable to open random device %s %d\n",
1435 SYSTEM_RANDOM_FILEPATH, this->fd_random);
1436 return NULL;
1437 }
1438
Andy Green2ac5a6f2011-01-28 10:00:18 +00001439 /* find canonical hostname */
1440
1441 hostname[(sizeof hostname) - 1] = '\0';
1442 gethostname(hostname, (sizeof hostname) - 1);
1443 he = gethostbyname(hostname);
Darin Willitsc19456f2011-02-14 17:52:39 +00001444 if (he) {
1445 strncpy(this->canonical_hostname, he->h_name,
Andy Green2ac5a6f2011-01-28 10:00:18 +00001446 sizeof this->canonical_hostname - 1);
Darin Willitsc19456f2011-02-14 17:52:39 +00001447 this->canonical_hostname[sizeof this->canonical_hostname - 1] =
1448 '\0';
1449 } else
1450 strncpy(this->canonical_hostname, hostname,
1451 sizeof this->canonical_hostname - 1);
Andy Green2ac5a6f2011-01-28 10:00:18 +00001452
Andy Green9659f372011-01-27 22:01:43 +00001453 /* split the proxy ads:port if given */
1454
1455 p = getenv("http_proxy");
1456 if (p) {
1457 strncpy(this->http_proxy_address, p,
1458 sizeof this->http_proxy_address - 1);
1459 this->http_proxy_address[
1460 sizeof this->http_proxy_address - 1] = '\0';
1461
1462 p = strchr(this->http_proxy_address, ':');
1463 if (p == NULL) {
1464 fprintf(stderr, "http_proxy needs to be ads:port\n");
1465 return NULL;
1466 }
1467 *p = '\0';
1468 this->http_proxy_port = atoi(p + 1);
1469
1470 fprintf(stderr, "Using proxy %s:%u\n",
1471 this->http_proxy_address,
1472 this->http_proxy_port);
1473 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001474
1475 if (port) {
1476
Andy Green3faa9c72010-11-08 17:03:03 +00001477#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +00001478 this->use_ssl = ssl_cert_filepath != NULL &&
1479 ssl_private_key_filepath != NULL;
1480 if (this->use_ssl)
1481 fprintf(stderr, " Compiled with SSL support, "
1482 "using it\n");
1483 else
1484 fprintf(stderr, " Compiled with SSL support, "
1485 "not using it\n");
Andy Green3faa9c72010-11-08 17:03:03 +00001486
Andy Green90c7cbc2011-01-27 06:26:52 +00001487#else
1488 if (ssl_cert_filepath != NULL &&
1489 ssl_private_key_filepath != NULL) {
1490 fprintf(stderr, " Not compiled for OpenSSl support!\n");
Andy Greene92cd172011-01-19 13:11:55 +00001491 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00001492 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001493 fprintf(stderr, " Compiled without SSL support, "
1494 "serving unencrypted\n");
1495#endif
1496 }
1497
1498 /* ignore SIGPIPE */
1499
1500 signal(SIGPIPE, sigpipe_handler);
1501
1502
1503#ifdef LWS_OPENSSL_SUPPORT
1504
1505 /* basic openssl init */
1506
1507 SSL_library_init();
1508
1509 OpenSSL_add_all_algorithms();
1510 SSL_load_error_strings();
1511
1512 /*
1513 * Firefox insists on SSLv23 not SSLv3
1514 * Konq disables SSLv2 by default now, SSLv23 works
1515 */
1516
1517 method = (SSL_METHOD *)SSLv23_server_method();
1518 if (!method) {
1519 fprintf(stderr, "problem creating ssl method: %s\n",
1520 ERR_error_string(ERR_get_error(), ssl_err_buf));
1521 return NULL;
1522 }
1523 this->ssl_ctx = SSL_CTX_new(method); /* create context */
1524 if (!this->ssl_ctx) {
1525 fprintf(stderr, "problem creating ssl context: %s\n",
1526 ERR_error_string(ERR_get_error(), ssl_err_buf));
1527 return NULL;
1528 }
1529
1530 /* client context */
1531
1532 method = (SSL_METHOD *)SSLv23_client_method();
1533 if (!method) {
1534 fprintf(stderr, "problem creating ssl method: %s\n",
1535 ERR_error_string(ERR_get_error(), ssl_err_buf));
1536 return NULL;
1537 }
1538 this->ssl_client_ctx = SSL_CTX_new(method); /* create context */
1539 if (!this->ssl_client_ctx) {
1540 fprintf(stderr, "problem creating ssl context: %s\n",
1541 ERR_error_string(ERR_get_error(), ssl_err_buf));
1542 return NULL;
1543 }
1544
1545
1546 /* openssl init for cert verification (used with client sockets) */
1547
1548 if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
1549 LWS_OPENSSL_CLIENT_CERTS)) {
1550 fprintf(stderr, "Unable to load SSL Client certs from %s "
1551 "(set by --with-client-cert-dir= in configure) -- "
1552 " client ssl isn't going to work",
1553 LWS_OPENSSL_CLIENT_CERTS);
1554 }
1555
1556 if (this->use_ssl) {
1557
1558 /* openssl init for server sockets */
1559
Andy Green3faa9c72010-11-08 17:03:03 +00001560 /* set the local certificate from CertFile */
Andy Green90c7cbc2011-01-27 06:26:52 +00001561 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
Andy Green3faa9c72010-11-08 17:03:03 +00001562 ssl_cert_filepath, SSL_FILETYPE_PEM);
1563 if (n != 1) {
1564 fprintf(stderr, "problem getting cert '%s': %s\n",
1565 ssl_cert_filepath,
1566 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00001567 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00001568 }
1569 /* set the private key from KeyFile */
Andy Green90c7cbc2011-01-27 06:26:52 +00001570 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
Andy Green018d8eb2010-11-08 21:04:23 +00001571 ssl_private_key_filepath,
Andy Green4739e5c2011-01-22 12:51:57 +00001572 SSL_FILETYPE_PEM) != 1) {
Andy Green018d8eb2010-11-08 21:04:23 +00001573 fprintf(stderr, "ssl problem getting key '%s': %s\n",
1574 ssl_private_key_filepath,
1575 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00001576 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00001577 }
1578 /* verify private key */
Andy Green90c7cbc2011-01-27 06:26:52 +00001579 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
Andy Green018d8eb2010-11-08 21:04:23 +00001580 fprintf(stderr, "Private SSL key doesn't match cert\n");
Andy Greene92cd172011-01-19 13:11:55 +00001581 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00001582 }
1583
1584 /* SSL is happy and has a cert it's content with */
1585 }
1586#endif
Andy Greenb45993c2010-12-18 15:13:50 +00001587
Andy Greendf736162011-01-18 15:39:02 +00001588 /* selftest */
1589
1590 if (lws_b64_selftest())
Andy Greene92cd172011-01-19 13:11:55 +00001591 return NULL;
Andy Greendf736162011-01-18 15:39:02 +00001592
Andy Green0d338332011-02-12 11:57:43 +00001593 /* fd hashtable init */
1594
1595 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1596 this->fd_hashtable[n].length = 0;
1597
Andy Greenb45993c2010-12-18 15:13:50 +00001598 /* set up our external listening socket we serve on */
Andy Green8f037e42010-12-19 22:13:26 +00001599
Andy Green4739e5c2011-01-22 12:51:57 +00001600 if (port) {
Andy Green8f037e42010-12-19 22:13:26 +00001601
Andy Green4739e5c2011-01-22 12:51:57 +00001602 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1603 if (sockfd < 0) {
1604 fprintf(stderr, "ERROR opening socket");
1605 return NULL;
1606 }
Andy Green775c0dd2010-10-29 14:15:22 +01001607
Andy Green4739e5c2011-01-22 12:51:57 +00001608 /* allow us to restart even if old sockets in TIME_WAIT */
1609 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
Andy Greene77ddd82010-11-13 10:03:47 +00001610
Andy Green4739e5c2011-01-22 12:51:57 +00001611 bzero((char *) &serv_addr, sizeof(serv_addr));
1612 serv_addr.sin_family = AF_INET;
1613 serv_addr.sin_addr.s_addr = INADDR_ANY;
1614 serv_addr.sin_port = htons(port);
1615
1616 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1617 sizeof(serv_addr));
1618 if (n < 0) {
1619 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Green8f037e42010-12-19 22:13:26 +00001620 port, n, errno);
Andy Green4739e5c2011-01-22 12:51:57 +00001621 return NULL;
1622 }
Andy Green0d338332011-02-12 11:57:43 +00001623
1624 wsi = malloc(sizeof(struct libwebsocket));
1625 memset(wsi, 0, sizeof (struct libwebsocket));
1626 wsi->sock = sockfd;
1627 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1628 insert_wsi(this, wsi);
1629
1630 listen(sockfd, 5);
1631 fprintf(stderr, " Listening on port %d\n", port);
1632
1633 /* list in the internal poll array */
1634
1635 this->fds[this->fds_count].fd = sockfd;
1636 this->fds[this->fds_count++].events = POLLIN;
Andy Green3221f922011-02-12 13:14:11 +00001637
1638 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001639 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001640 LWS_CALLBACK_ADD_POLL_FD,
1641 (void *)(long)sockfd, NULL, POLLIN);
1642
Andy Green8f037e42010-12-19 22:13:26 +00001643 }
Andy Greenb45993c2010-12-18 15:13:50 +00001644
Andy Greene77ddd82010-11-13 10:03:47 +00001645 /* drop any root privs for this process */
Andy Green3faa9c72010-11-08 17:03:03 +00001646
1647 if (gid != -1)
1648 if (setgid(gid))
1649 fprintf(stderr, "setgid: %s\n", strerror(errno));
1650 if (uid != -1)
1651 if (setuid(uid))
1652 fprintf(stderr, "setuid: %s\n", strerror(errno));
1653
Andy Greenb45993c2010-12-18 15:13:50 +00001654
1655 /* set up our internal broadcast trigger sockets per-protocol */
1656
Andy Green0d338332011-02-12 11:57:43 +00001657 for (this->count_protocols = 0;
1658 protocols[this->count_protocols].callback;
Andy Greenb45993c2010-12-18 15:13:50 +00001659 this->count_protocols++) {
1660 protocols[this->count_protocols].owning_server = this;
1661 protocols[this->count_protocols].protocol_index =
1662 this->count_protocols;
1663
1664 fd = socket(AF_INET, SOCK_STREAM, 0);
1665 if (fd < 0) {
1666 fprintf(stderr, "ERROR opening socket");
Andy Greene92cd172011-01-19 13:11:55 +00001667 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001668 }
Andy Green8f037e42010-12-19 22:13:26 +00001669
Andy Greenb45993c2010-12-18 15:13:50 +00001670 /* allow us to restart even if old sockets in TIME_WAIT */
1671 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1672
1673 bzero((char *) &serv_addr, sizeof(serv_addr));
1674 serv_addr.sin_family = AF_INET;
1675 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1676 serv_addr.sin_port = 0; /* pick the port for us */
1677
1678 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1679 if (n < 0) {
Andy Green8f037e42010-12-19 22:13:26 +00001680 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Greenb45993c2010-12-18 15:13:50 +00001681 port, n, errno);
Andy Greene92cd172011-01-19 13:11:55 +00001682 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001683 }
1684
1685 slen = sizeof cli_addr;
1686 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1687 if (n < 0) {
1688 fprintf(stderr, "getsockname failed\n");
Andy Greene92cd172011-01-19 13:11:55 +00001689 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001690 }
1691 protocols[this->count_protocols].broadcast_socket_port =
1692 ntohs(cli_addr.sin_port);
1693 listen(fd, 5);
1694
1695 debug(" Protocol %s broadcast socket %d\n",
1696 protocols[this->count_protocols].name,
1697 ntohs(cli_addr.sin_port));
1698
Andy Green0d338332011-02-12 11:57:43 +00001699 /* dummy wsi per broadcast proxy socket */
1700
1701 wsi = malloc(sizeof(struct libwebsocket));
1702 memset(wsi, 0, sizeof (struct libwebsocket));
1703 wsi->sock = fd;
1704 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1705 /* note which protocol we are proxying */
1706 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1707 insert_wsi(this, wsi);
1708
1709 /* list in internal poll array */
1710
Andy Greenb45993c2010-12-18 15:13:50 +00001711 this->fds[this->fds_count].fd = fd;
1712 this->fds[this->fds_count].events = POLLIN;
Andy Green3221f922011-02-12 13:14:11 +00001713 this->fds[this->fds_count].revents = 0;
Andy Greenb45993c2010-12-18 15:13:50 +00001714 this->fds_count++;
Andy Green3221f922011-02-12 13:14:11 +00001715
1716 /* external POLL support via protocol 0 */
Andy Green62c54d22011-02-14 09:14:25 +00001717 this->protocols[0].callback(this, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001718 LWS_CALLBACK_ADD_POLL_FD,
1719 (void *)(long)fd, NULL, POLLIN);
Andy Greenb45993c2010-12-18 15:13:50 +00001720 }
1721
Andy Greene92cd172011-01-19 13:11:55 +00001722 return this;
1723}
Andy Greenb45993c2010-12-18 15:13:50 +00001724
Andy Green4739e5c2011-01-22 12:51:57 +00001725
Andy Greened11a022011-01-20 10:23:50 +00001726#ifndef LWS_NO_FORK
1727
Andy Greene92cd172011-01-19 13:11:55 +00001728/**
1729 * libwebsockets_fork_service_loop() - Optional helper function forks off
1730 * a process for the websocket server loop.
Andy Green6964bb52011-01-23 16:50:33 +00001731 * You don't have to use this but if not, you
1732 * have to make sure you are calling
1733 * libwebsocket_service periodically to service
1734 * the websocket traffic
Andy Greene92cd172011-01-19 13:11:55 +00001735 * @this: server context returned by creation function
1736 */
Andy Greenb45993c2010-12-18 15:13:50 +00001737
Andy Greene92cd172011-01-19 13:11:55 +00001738int
1739libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1740{
Andy Greene92cd172011-01-19 13:11:55 +00001741 int fd;
1742 struct sockaddr_in cli_addr;
1743 int n;
Andy Green3221f922011-02-12 13:14:11 +00001744 int p;
Andy Greenb45993c2010-12-18 15:13:50 +00001745
Andy Greened11a022011-01-20 10:23:50 +00001746 n = fork();
1747 if (n < 0)
1748 return n;
1749
1750 if (!n) {
1751
1752 /* main process context */
1753
Andy Green3221f922011-02-12 13:14:11 +00001754 /*
1755 * set up the proxy sockets to allow broadcast from
1756 * service process context
1757 */
1758
1759 for (p = 0; p < this->count_protocols; p++) {
Andy Greened11a022011-01-20 10:23:50 +00001760 fd = socket(AF_INET, SOCK_STREAM, 0);
1761 if (fd < 0) {
1762 fprintf(stderr, "Unable to create socket\n");
1763 return -1;
1764 }
1765 cli_addr.sin_family = AF_INET;
1766 cli_addr.sin_port = htons(
Andy Green3221f922011-02-12 13:14:11 +00001767 this->protocols[p].broadcast_socket_port);
Andy Greened11a022011-01-20 10:23:50 +00001768 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1769 n = connect(fd, (struct sockaddr *)&cli_addr,
1770 sizeof cli_addr);
1771 if (n < 0) {
1772 fprintf(stderr, "Unable to connect to "
1773 "broadcast socket %d, %s\n",
Andy Green3221f922011-02-12 13:14:11 +00001774 n, strerror(errno));
Andy Greened11a022011-01-20 10:23:50 +00001775 return -1;
1776 }
1777
Andy Green3221f922011-02-12 13:14:11 +00001778 this->protocols[p].broadcast_socket_user_fd = fd;
Andy Greened11a022011-01-20 10:23:50 +00001779 }
1780
Andy Greene92cd172011-01-19 13:11:55 +00001781 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00001782 }
1783
1784 /* we want a SIGHUP when our parent goes down */
1785 prctl(PR_SET_PDEATHSIG, SIGHUP);
1786
1787 /* in this forked process, sit and service websocket connections */
Andy Green8f037e42010-12-19 22:13:26 +00001788
Andy Greene92cd172011-01-19 13:11:55 +00001789 while (1)
1790 if (libwebsocket_service(this, 1000))
1791 return -1;
Andy Green8f037e42010-12-19 22:13:26 +00001792
Andy Green251f6fa2010-11-03 11:13:06 +00001793 return 0;
Andy Greenff95d7a2010-10-28 22:36:01 +01001794}
1795
Andy Greened11a022011-01-20 10:23:50 +00001796#endif
1797
Andy Greenb45993c2010-12-18 15:13:50 +00001798/**
1799 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
Andy Green8f037e42010-12-19 22:13:26 +00001800 * connection.
Andy Greenb45993c2010-12-18 15:13:50 +00001801 * @wsi: pointer to struct websocket you want to know the protocol of
1802 *
Andy Green8f037e42010-12-19 22:13:26 +00001803 *
1804 * This is useful to get the protocol to broadcast back to from inside
Andy Greenb45993c2010-12-18 15:13:50 +00001805 * the callback.
1806 */
Andy Greenab990e42010-10-31 12:42:52 +00001807
Andy Greenb45993c2010-12-18 15:13:50 +00001808const struct libwebsocket_protocols *
1809libwebsockets_get_protocol(struct libwebsocket *wsi)
1810{
1811 return wsi->protocol;
1812}
1813
1814/**
Andy Greene92cd172011-01-19 13:11:55 +00001815 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
Andy Green8f037e42010-12-19 22:13:26 +00001816 * connections of the given protocol.
Andy Greenb45993c2010-12-18 15:13:50 +00001817 * @protocol: pointer to the protocol you will broadcast to all members of
1818 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
Andy Green8f037e42010-12-19 22:13:26 +00001819 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1820 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1821 * case you are calling this function from callback context.
Andy Greenb45993c2010-12-18 15:13:50 +00001822 * @len: length of payload data in buf, starting from buf.
Andy Green8f037e42010-12-19 22:13:26 +00001823 *
1824 * This function allows bulk sending of a packet to every connection using
Andy Greenb45993c2010-12-18 15:13:50 +00001825 * the given protocol. It does not send the data directly; instead it calls
1826 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
1827 * wants to actually send the data for that connection, the callback itself
1828 * should call libwebsocket_write().
1829 *
1830 * libwebsockets_broadcast() can be called from another fork context without
1831 * having to take any care about data visibility between the processes, it'll
1832 * "just work".
1833 */
1834
1835
1836int
Andy Green8f037e42010-12-19 22:13:26 +00001837libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
Andy Greenb45993c2010-12-18 15:13:50 +00001838 unsigned char *buf, size_t len)
1839{
Andy Green8f037e42010-12-19 22:13:26 +00001840 struct libwebsocket_context *this = protocol->owning_server;
Andy Greenb45993c2010-12-18 15:13:50 +00001841 int n;
Andy Green0d338332011-02-12 11:57:43 +00001842 int m;
1843 struct libwebsocket * wsi;
Andy Greenb45993c2010-12-18 15:13:50 +00001844
1845 if (!protocol->broadcast_socket_user_fd) {
1846 /*
Andy Greene92cd172011-01-19 13:11:55 +00001847 * We are either running unforked / flat, or we are being
1848 * called from poll thread context
Andy Greenb45993c2010-12-18 15:13:50 +00001849 * eg, from a callback. In that case don't use sockets for
1850 * broadcast IPC (since we can't open a socket connection to
1851 * a socket listening on our own thread) but directly do the
1852 * send action.
1853 *
1854 * Locking is not needed because we are by definition being
1855 * called in the poll thread context and are serialized.
1856 */
1857
Andy Green0d338332011-02-12 11:57:43 +00001858 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Greenb45993c2010-12-18 15:13:50 +00001859
Andy Green0d338332011-02-12 11:57:43 +00001860 for (m = 0; m < this->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +00001861
Andy Green0d338332011-02-12 11:57:43 +00001862 wsi = this->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +00001863
Andy Green0d338332011-02-12 11:57:43 +00001864 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1865 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00001866
Andy Green0d338332011-02-12 11:57:43 +00001867 /*
1868 * never broadcast to
1869 * non-established connections
1870 */
1871 if (wsi->state != WSI_STATE_ESTABLISHED)
1872 continue;
1873
1874 /* only broadcast to guys using
1875 * requested protocol
1876 */
1877 if (wsi->protocol != protocol)
1878 continue;
1879
Andy Green62c54d22011-02-14 09:14:25 +00001880 wsi->protocol->callback(this, wsi,
Andy Green8f037e42010-12-19 22:13:26 +00001881 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +00001882 wsi->user_space,
Andy Greenb45993c2010-12-18 15:13:50 +00001883 buf, len);
Andy Green0d338332011-02-12 11:57:43 +00001884 }
Andy Greenb45993c2010-12-18 15:13:50 +00001885 }
1886
1887 return 0;
1888 }
1889
Andy Green0ca6a172010-12-19 20:50:01 +00001890 /*
1891 * We're being called from a different process context than the server
1892 * loop. Instead of broadcasting directly, we send our
1893 * payload on a socket to do the IPC; the server process will serialize
1894 * the broadcast action in its main poll() loop.
1895 *
1896 * There's one broadcast socket listening for each protocol supported
1897 * set up when the websocket server initializes
1898 */
1899
Andy Green6964bb52011-01-23 16:50:33 +00001900 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
Andy Greenb45993c2010-12-18 15:13:50 +00001901
1902 return n;
1903}