blob: 83505c8e9c3f4abd2b1dbcbd2b7de04fc69492f8 [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 Green0d338332011-02-12 11:57:43 +000024/* file descriptor hash management */
25
26struct libwebsocket *
27wsi_from_fd(struct libwebsocket_context *this, int fd)
28{
29 int h = LWS_FD_HASH(fd);
30 int n = 0;
31
32 for (n = 0; n < this->fd_hashtable[h].length; n++)
33 if (this->fd_hashtable[h].wsi[n]->sock == fd)
34 return this->fd_hashtable[h].wsi[n];
35
36 return NULL;
37}
38
39int
40insert_wsi(struct libwebsocket_context *this, struct libwebsocket *wsi)
41{
42 int h = LWS_FD_HASH(wsi->sock);
43
44 if (this->fd_hashtable[h].length == MAX_CLIENTS - 1) {
45 fprintf(stderr, "hash table overflow\n");
46 return 1;
47 }
48
49 this->fd_hashtable[h].wsi[this->fd_hashtable[h].length++] = wsi;
50
51 return 0;
52}
53
54int
55delete_from_fd(struct libwebsocket_context *this, int fd)
56{
57 int h = LWS_FD_HASH(fd);
58 int n = 0;
59
60 for (n = 0; n < this->fd_hashtable[h].length; n++)
61 if (this->fd_hashtable[h].wsi[n]->sock == fd) {
62 while (n < this->fd_hashtable[h].length) {
63 this->fd_hashtable[h].wsi[n] =
64 this->fd_hashtable[h].wsi[n + 1];
65 n++;
66 }
67 this->fd_hashtable[h].length--;
68
69 return 0;
70 }
71
72 fprintf(stderr, "Failed to find fd %d requested for "
73 "delete in hashtable\n", fd);
74 return 1;
75}
76
77
Andy Green8f037e42010-12-19 22:13:26 +000078void
Andy Green251f6fa2010-11-03 11:13:06 +000079libwebsocket_close_and_free_session(struct libwebsocket *wsi)
80{
Andy Greenb45993c2010-12-18 15:13:50 +000081 int n;
Andy Green5e1fa172011-02-10 09:07:05 +000082 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
83 LWS_SEND_BUFFER_POST_PADDING];
Andy Greenb45993c2010-12-18 15:13:50 +000084
85 if ((unsigned long)wsi < LWS_MAX_PROTOCOLS)
86 return;
87
88 n = wsi->state;
Andy Green251f6fa2010-11-03 11:13:06 +000089
Andy Green5e1fa172011-02-10 09:07:05 +000090 if (n == WSI_STATE_DEAD_SOCKET)
91 return;
92
93 /*
94 * signal we are closing, libsocket_write will
95 * add any necessary version-specific stuff. If the write fails,
96 * no worries we are closing anyway. If we didn't initiate this
97 * close, then our state has been changed to
98 * WSI_STATE_RETURNED_CLOSE_ALREADY and we can skip this
99 */
100
101 if (n == WSI_STATE_ESTABLISHED)
102 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
103 LWS_WRITE_CLOSE);
104
Andy Green251f6fa2010-11-03 11:13:06 +0000105 wsi->state = WSI_STATE_DEAD_SOCKET;
106
Andy Green4f3943a2010-11-12 10:44:16 +0000107 if (wsi->protocol->callback && n == WSI_STATE_ESTABLISHED)
Andy Greene77ddd82010-11-13 10:03:47 +0000108 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
109 wsi->user_space, NULL, 0);
Andy Green251f6fa2010-11-03 11:13:06 +0000110
111 for (n = 0; n < WSI_TOKEN_COUNT; n++)
112 if (wsi->utf8_token[n].token)
113 free(wsi->utf8_token[n].token);
114
Andy Green0ca6a172010-12-19 20:50:01 +0000115/* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
Andy Green251f6fa2010-11-03 11:13:06 +0000116
Andy Green3faa9c72010-11-08 17:03:03 +0000117#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +0000118 if (wsi->ssl) {
Andy Green3faa9c72010-11-08 17:03:03 +0000119 n = SSL_get_fd(wsi->ssl);
120 SSL_shutdown(wsi->ssl);
121 close(n);
122 SSL_free(wsi->ssl);
123 } else {
124#endif
125 shutdown(wsi->sock, SHUT_RDWR);
126 close(wsi->sock);
127#ifdef LWS_OPENSSL_SUPPORT
128 }
129#endif
Andy Green4f3943a2010-11-12 10:44:16 +0000130 if (wsi->user_space)
131 free(wsi->user_space);
132
Andy Green251f6fa2010-11-03 11:13:06 +0000133 free(wsi);
134}
135
Andy Green9f990342011-02-12 11:57:45 +0000136
137/**
138 * libwebsocket_service_fd() - Service polled socket with something waiting
139 * @this: Websocket context
140 * @pollfd: The pollfd entry describing the socket fd and which events
141 * happened.
142 *
143 * This function closes any active connections and then frees the
144 * context. After calling this, any further use of the context is
145 * undefined.
146 */
147
148int
Andy Green0d338332011-02-12 11:57:43 +0000149libwebsocket_service_fd(struct libwebsocket_context *this,
150 struct pollfd *pollfd)
Andy Greenb45993c2010-12-18 15:13:50 +0000151{
152 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
153 LWS_SEND_BUFFER_POST_PADDING];
Andy Green0d338332011-02-12 11:57:43 +0000154 struct libwebsocket *wsi = wsi_from_fd(this, pollfd->fd);
155 struct libwebsocket *new_wsi;
Andy Greenb45993c2010-12-18 15:13:50 +0000156 int n;
Andy Green0d338332011-02-12 11:57:43 +0000157 int m;
Andy Greenb45993c2010-12-18 15:13:50 +0000158 size_t len;
Andy Green0d338332011-02-12 11:57:43 +0000159 int accept_fd;
160 unsigned int clilen;
161 struct sockaddr_in cli_addr;
Andy Greenb45993c2010-12-18 15:13:50 +0000162
Andy Green0d338332011-02-12 11:57:43 +0000163 if (wsi == NULL)
164 return 1;
Andy Green8f037e42010-12-19 22:13:26 +0000165
Andy Green0d338332011-02-12 11:57:43 +0000166 switch (wsi->mode) {
167 case LWS_CONNMODE_SERVER_LISTENER:
168
169 /* pollin means a client has connected to us then */
170
171 if (!pollfd->revents & POLLIN)
172 break;
173
174 /* listen socket got an unencrypted connection... */
175
176 clilen = sizeof(cli_addr);
177 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
178 &clilen);
179 if (accept_fd < 0) {
180 fprintf(stderr, "ERROR on accept");
181 break;
182 }
183
184 if (this->fds_count >= MAX_CLIENTS) {
185 fprintf(stderr, "too busy");
186 close(accept_fd);
187 break;
188 }
189
190 /* accepting connection to main listener */
191
192 new_wsi = malloc(sizeof(struct libwebsocket));
193 if (new_wsi == NULL) {
194 fprintf(stderr, "Out of memory for new connection\n");
195 break;
196 }
197
198 memset(new_wsi, 0, sizeof (struct libwebsocket));
199 new_wsi->sock = accept_fd;
200
201#ifdef LWS_OPENSSL_SUPPORT
202 new_wsi->ssl = NULL;
203 this->ssl_ctx = NULL;
204
205 if (this->use_ssl) {
206
207 new_wsi->ssl = SSL_new(this->ssl_ctx);
208 if (new_wsi->ssl == NULL) {
209 fprintf(stderr, "SSL_new failed: %s\n",
210 ERR_error_string(SSL_get_error(
211 new_wsi->ssl, 0), NULL));
212 free(new_wsi);
213 break;
214 }
215
216 SSL_set_fd(new_wsi->ssl, accept_fd);
217
218 n = SSL_accept(new_wsi->ssl);
219 if (n != 1) {
220 /*
221 * browsers seem to probe with various
222 * ssl params which fail then retry
223 * and succeed
224 */
225 debug("SSL_accept failed skt %u: %s\n",
226 pollfd->fd,
227 ERR_error_string(SSL_get_error(
228 new_wsi->ssl, n), NULL));
229 SSL_free(
230 new_wsi->ssl);
231 free(new_wsi);
232 break;
233 }
234 debug("accepted new SSL conn "
235 "port %u on fd=%d SSL ver %s\n",
236 ntohs(cli_addr.sin_port), accept_fd,
237 SSL_get_version(new_wsi->ssl));
238
239 } else
240#endif
241 debug("accepted new conn port %u on fd=%d\n",
242 ntohs(cli_addr.sin_port), accept_fd);
243
244 /* intialize the instance struct */
245
246 new_wsi->state = WSI_STATE_HTTP;
247 new_wsi->name_buffer_pos = 0;
248 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
249
250 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
251 new_wsi->utf8_token[n].token = NULL;
252 new_wsi->utf8_token[n].token_len = 0;
253 }
254
255 /*
256 * these can only be set once the protocol is known
257 * we set an unestablished connection's protocol pointer
258 * to the start of the supported list, so it can look
259 * for matching ones during the handshake
260 */
261 new_wsi->protocol = this->protocols;
262 new_wsi->user_space = NULL;
263
264 /*
265 * Default protocol is 76 / 00
266 * After 76, there's a header specified to inform which
267 * draft the client wants, when that's seen we modify
268 * the individual connection's spec revision accordingly
269 */
270 new_wsi->ietf_spec_revision = 0;
271
272 insert_wsi(this, new_wsi);
273
274
275 /*
276 * make sure NO events are seen yet on this new socket
277 * (otherwise we inherit old fds[client].revents from
278 * previous socket there and die mysteriously! )
279 */
280 this->fds[this->fds_count].revents = 0;
281
282 this->fds[this->fds_count].events = POLLIN;
283 this->fds[this->fds_count++].fd = accept_fd;
284
285 break;
286
287 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
288
289 /* as we are listening, POLLIN means accept() is needed */
290
291 if (!pollfd->revents & POLLIN)
292 break;
293
294 /* listen socket got an unencrypted connection... */
295
296 clilen = sizeof(cli_addr);
297 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
298 &clilen);
299 if (accept_fd < 0) {
300 fprintf(stderr, "ERROR on accept");
301 break;
302 }
303
304 if (this->fds_count >= MAX_CLIENTS) {
305 fprintf(stderr, "too busy");
306 close(accept_fd);
307 break;
308 }
309
310 /* create a dummy wsi for the connection and add it */
311
312 new_wsi = malloc(sizeof(struct libwebsocket));
313 memset(new_wsi, 0, sizeof (struct libwebsocket));
314 new_wsi->sock = accept_fd;
315 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
316 new_wsi->state = WSI_STATE_ESTABLISHED;
317 /* note which protocol we are proxying */
318 new_wsi->protocol_index_for_broadcast_proxy =
319 wsi->protocol_index_for_broadcast_proxy;
320 insert_wsi(this, new_wsi);
321
322 /* add connected socket to internal poll array */
323
324 this->fds[this->fds_count].revents = 0;
325 this->fds[this->fds_count].events = POLLIN;
326 this->fds[this->fds_count++].fd = accept_fd;
327
328 break;
329
330 case LWS_CONNMODE_BROADCAST_PROXY:
Andy Green8f037e42010-12-19 22:13:26 +0000331
Andy Greenb45993c2010-12-18 15:13:50 +0000332 /* handle session socket closed */
Andy Green8f037e42010-12-19 22:13:26 +0000333
Andy Green0d338332011-02-12 11:57:43 +0000334 if (pollfd->revents & (POLLERR | POLLHUP)) {
Andy Green8f037e42010-12-19 22:13:26 +0000335
Andy Green0d338332011-02-12 11:57:43 +0000336 debug("Session Socket %p (fd=%d) dead\n",
337 (void *)wsi, accept_fd);
Andy Greenb45993c2010-12-18 15:13:50 +0000338
Andy Green0d338332011-02-12 11:57:43 +0000339 libwebsocket_close_and_free_session(wsi);
Andy Greenb45993c2010-12-18 15:13:50 +0000340 goto nuke_this;
341 }
Andy Green8f037e42010-12-19 22:13:26 +0000342
Andy Green90c7cbc2011-01-27 06:26:52 +0000343 /* the guy requested a callback when it was OK to write */
344
Andy Green0d338332011-02-12 11:57:43 +0000345 if (pollfd->revents & POLLOUT) {
Andy Green90c7cbc2011-01-27 06:26:52 +0000346
Andy Green0d338332011-02-12 11:57:43 +0000347 /* one shot */
Andy Green90c7cbc2011-01-27 06:26:52 +0000348
Andy Green0d338332011-02-12 11:57:43 +0000349 pollfd->events &= ~POLLOUT;
350
351 wsi->protocol->callback(wsi,
Andy Green90c7cbc2011-01-27 06:26:52 +0000352 LWS_CALLBACK_CLIENT_WRITEABLE,
Andy Green0d338332011-02-12 11:57:43 +0000353 wsi->user_space,
Andy Green90c7cbc2011-01-27 06:26:52 +0000354 NULL, 0);
355 }
356
Andy Greenb45993c2010-12-18 15:13:50 +0000357 /* any incoming data ready? */
358
Andy Green0d338332011-02-12 11:57:43 +0000359 if (!(pollfd->revents & POLLIN))
360 break;
Andy Greenb45993c2010-12-18 15:13:50 +0000361
Andy Green0d338332011-02-12 11:57:43 +0000362 /* get the issued broadcast payload from the socket */
Andy Greenb45993c2010-12-18 15:13:50 +0000363
Andy Green0d338332011-02-12 11:57:43 +0000364 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
365 MAX_BROADCAST_PAYLOAD);
366 if (len < 0) {
367 fprintf(stderr, "Error reading broadcast payload\n");
368 break;;
369 }
Andy Greenb45993c2010-12-18 15:13:50 +0000370
Andy Green0d338332011-02-12 11:57:43 +0000371 /* broadcast it to all guys with this protocol index */
Andy Green8f037e42010-12-19 22:13:26 +0000372
Andy Green0d338332011-02-12 11:57:43 +0000373 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Green8f037e42010-12-19 22:13:26 +0000374
Andy Green0d338332011-02-12 11:57:43 +0000375 for (m = 0; m < this->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +0000376
Andy Green0d338332011-02-12 11:57:43 +0000377 new_wsi = this->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +0000378
Andy Green0d338332011-02-12 11:57:43 +0000379 /* only to clients we are serving to */
Andy Greenb45993c2010-12-18 15:13:50 +0000380
Andy Green0d338332011-02-12 11:57:43 +0000381 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
Andy Greenb45993c2010-12-18 15:13:50 +0000382 continue;
383
384 /*
385 * never broadcast to non-established
386 * connection
387 */
388
Andy Green0d338332011-02-12 11:57:43 +0000389 if (new_wsi->state != WSI_STATE_ESTABLISHED)
Andy Green4739e5c2011-01-22 12:51:57 +0000390 continue;
391
Andy Greenb45993c2010-12-18 15:13:50 +0000392 /*
393 * only broadcast to connections using
394 * the requested protocol
395 */
396
Andy Green0d338332011-02-12 11:57:43 +0000397 if (new_wsi->protocol->protocol_index !=
398 wsi->protocol_index_for_broadcast_proxy)
Andy Greenb45993c2010-12-18 15:13:50 +0000399 continue;
400
Andy Green8f037e42010-12-19 22:13:26 +0000401 /* broadcast it to this connection */
402
Andy Green0d338332011-02-12 11:57:43 +0000403 new_wsi->protocol->callback(new_wsi,
Andy Green8f037e42010-12-19 22:13:26 +0000404 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +0000405 new_wsi->user_space,
Andy Green0ca6a172010-12-19 20:50:01 +0000406 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
Andy Greenb45993c2010-12-18 15:13:50 +0000407 }
Andy Green0d338332011-02-12 11:57:43 +0000408 }
409 break;
Andy Greenb45993c2010-12-18 15:13:50 +0000410
Andy Green0d338332011-02-12 11:57:43 +0000411 case LWS_CONNMODE_WS_SERVING:
412 case LWS_CONNMODE_WS_CLIENT:
413
414 /* handle session socket closed */
415
416 if (pollfd->revents & (POLLERR | POLLHUP)) {
417
418 debug("Session Socket %p (fd=%d) dead\n",
419 (void *)wsi, pollfd->fd);
420
421 libwebsocket_close_and_free_session(wsi);
422 goto nuke_this;
Andy Greenb45993c2010-12-18 15:13:50 +0000423 }
424
Andy Green0d338332011-02-12 11:57:43 +0000425 /* the guy requested a callback when it was OK to write */
426
427 if (pollfd->revents & POLLOUT) {
428
429 pollfd->events &= ~POLLOUT;
430
431 wsi->protocol->callback(wsi,
432 LWS_CALLBACK_CLIENT_WRITEABLE,
433 wsi->user_space,
434 NULL, 0);
435 }
436
437 /* any incoming data ready? */
438
439 if (!(pollfd->revents & POLLIN))
440 break;
441
Andy Greenb45993c2010-12-18 15:13:50 +0000442#ifdef LWS_OPENSSL_SUPPORT
Andy Green0d338332011-02-12 11:57:43 +0000443 if (wsi->ssl)
444 n = SSL_read(wsi->ssl, buf, sizeof buf);
Andy Greenb45993c2010-12-18 15:13:50 +0000445 else
446#endif
Andy Green0d338332011-02-12 11:57:43 +0000447 n = recv(pollfd->fd, buf, sizeof buf, 0);
Andy Greenb45993c2010-12-18 15:13:50 +0000448
449 if (n < 0) {
450 fprintf(stderr, "Socket read returned %d\n", n);
Andy Green0d338332011-02-12 11:57:43 +0000451 break;;
Andy Greenb45993c2010-12-18 15:13:50 +0000452 }
453 if (!n) {
Andy Green0d338332011-02-12 11:57:43 +0000454 libwebsocket_close_and_free_session(wsi);
Andy Greenb45993c2010-12-18 15:13:50 +0000455 goto nuke_this;
456 }
457
Andy Greenb45993c2010-12-18 15:13:50 +0000458 /* service incoming data */
459
Andy Green0d338332011-02-12 11:57:43 +0000460 n = libwebsocket_read(wsi, buf, n);
Andy Green6964bb52011-01-23 16:50:33 +0000461 if (n >= 0)
Andy Green0d338332011-02-12 11:57:43 +0000462 break;;
Andy Greenb45993c2010-12-18 15:13:50 +0000463 /*
464 * it closed and nuked wsi[client], so remove the
465 * socket handle and wsi from our service list
466 */
467nuke_this:
468
469 debug("nuking wsi %p, fsd_count = %d\n",
Andy Green0d338332011-02-12 11:57:43 +0000470 (void *)wsi, this->fds_count - 1);
471
472 delete_from_fd(this, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +0000473
474 this->fds_count--;
Andy Green0d338332011-02-12 11:57:43 +0000475 for (n = 0; n < this->fds_count; n++)
476 if (this->fds[n].fd == pollfd->fd) {
477 while (n < this->fds_count) {
478 this->fds[n] = this->fds[n + 1];
479 n++;
480 }
481 n = this->fds_count;
482 }
Andy Green6964bb52011-01-23 16:50:33 +0000483
Andy Green0d338332011-02-12 11:57:43 +0000484 break;
Andy Greenb45993c2010-12-18 15:13:50 +0000485 }
486
487 return 0;
488}
489
Andy Green0d338332011-02-12 11:57:43 +0000490
Andy Green6964bb52011-01-23 16:50:33 +0000491/**
492 * libwebsocket_context_destroy() - Destroy the websocket context
493 * @this: Websocket context
494 *
495 * This function closes any active connections and then frees the
496 * context. After calling this, any further use of the context is
497 * undefined.
498 */
499void
500libwebsocket_context_destroy(struct libwebsocket_context *this)
501{
Andy Green0d338332011-02-12 11:57:43 +0000502 int n;
503 int m;
504 struct libwebsocket *wsi;
Andy Green6964bb52011-01-23 16:50:33 +0000505
Andy Green0d338332011-02-12 11:57:43 +0000506 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
507
508 for (m = 0; m < this->fd_hashtable[n].length; m++) {
509
510 wsi = this->fd_hashtable[n].wsi[m];
511
512 switch (wsi->mode) {
513 case LWS_CONNMODE_WS_SERVING:
514 libwebsocket_close_and_free_session(wsi);
515 break;
516 case LWS_CONNMODE_WS_CLIENT:
517 libwebsocket_client_close(wsi);
518 break;
519 default:
520 break;
521 }
Andy Greenf3d3b402011-02-09 07:16:34 +0000522 }
Andy Green0d338332011-02-12 11:57:43 +0000523 }
Andy Green6964bb52011-01-23 16:50:33 +0000524
Andy Green44eee682011-02-10 09:32:24 +0000525 close(this->fd_random);
526
Andy Green6964bb52011-01-23 16:50:33 +0000527#ifdef LWS_OPENSSL_SUPPORT
Andy Green44eee682011-02-10 09:32:24 +0000528 if (this->ssl_ctx)
Andy Green90c7cbc2011-01-27 06:26:52 +0000529 SSL_CTX_free(this->ssl_ctx);
Andy Green44eee682011-02-10 09:32:24 +0000530 if (this->ssl_client_ctx)
Andy Green5e1fa172011-02-10 09:07:05 +0000531 SSL_CTX_free(this->ssl_client_ctx);
Andy Green6964bb52011-01-23 16:50:33 +0000532#endif
533
Andy Green44eee682011-02-10 09:32:24 +0000534 free(this);
Andy Green6964bb52011-01-23 16:50:33 +0000535}
536
537/**
538 * libwebsocket_service() - Service any pending websocket activity
539 * @this: Websocket context
540 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
541 * service otherwise block and service immediately, returning
542 * after the timeout if nothing needed service.
543 *
544 * This function deals with any pending websocket traffic, for three
545 * kinds of event. It handles these events on both server and client
546 * types of connection the same.
547 *
548 * 1) Accept new connections to our context's server
549 *
550 * 2) Perform pending broadcast writes initiated from other forked
551 * processes (effectively serializing asynchronous broadcasts)
552 *
553 * 3) Call the receive callback for incoming frame data received by
554 * server or client connections.
555 *
556 * You need to call this service function periodically to all the above
557 * functions to happen; if your application is single-threaded you can
558 * just call it in your main event loop.
559 *
560 * Alternatively you can fork a new process that asynchronously handles
561 * calling this service in a loop. In that case you are happy if this
562 * call blocks your thread until it needs to take care of something and
563 * would call it with a large nonzero timeout. Your loop then takes no
564 * CPU while there is nothing happening.
565 *
566 * If you are calling it in a single-threaded app, you don't want it to
567 * wait around blocking other things in your loop from happening, so you
568 * would call it with a timeout_ms of 0, so it returns immediately if
569 * nothing is pending, or as soon as it services whatever was pending.
570 */
571
Andy Greenb45993c2010-12-18 15:13:50 +0000572
Andy Greene92cd172011-01-19 13:11:55 +0000573int
574libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
575{
576 int n;
Andy Greene92cd172011-01-19 13:11:55 +0000577
578 /* stay dead once we are dead */
579
580 if (this == NULL)
581 return 1;
582
Andy Green0d338332011-02-12 11:57:43 +0000583 /* wait for something to need service */
Andy Green4739e5c2011-01-22 12:51:57 +0000584
Andy Green0d338332011-02-12 11:57:43 +0000585 n = poll(this->fds, this->fds_count, timeout_ms);
Andy Greene92cd172011-01-19 13:11:55 +0000586
587 if (n < 0 || this->fds[0].revents & (POLLERR | POLLHUP)) {
Andy Green5e1fa172011-02-10 09:07:05 +0000588 /*
Andy Greene92cd172011-01-19 13:11:55 +0000589 fprintf(stderr, "Listen Socket dead\n");
Andy Green5e1fa172011-02-10 09:07:05 +0000590 */
Andy Green0d338332011-02-12 11:57:43 +0000591 return 1;
Andy Greene92cd172011-01-19 13:11:55 +0000592 }
593 if (n == 0) /* poll timeout */
594 return 0;
595
596 /* handle accept on listening socket? */
597
Andy Green0d338332011-02-12 11:57:43 +0000598 for (n = 0; n < this->fds_count; n++)
599 if (this->fds[n].revents)
600 libwebsocket_service_fd(this, &this->fds[n]);
Andy Greene92cd172011-01-19 13:11:55 +0000601
602 return 0;
Andy Greene92cd172011-01-19 13:11:55 +0000603}
604
Andy Green90c7cbc2011-01-27 06:26:52 +0000605/**
606 * libwebsocket_callback_on_writable() - Request a callback when this socket
607 * becomes able to be written to without
608 * blocking
609 *
Andy Green0d338332011-02-12 11:57:43 +0000610 * This only works for internal poll() management, (ie, calling the libwebsocket
611 * service loop, you will have to make your own arrangements if your poll()
612 * loop is managed externally.
613 *
Andy Green90c7cbc2011-01-27 06:26:52 +0000614 * @wsi: Websocket connection instance to get callback for
615 */
616
617int
618libwebsocket_callback_on_writable(struct libwebsocket *wsi)
619{
620 struct libwebsocket_context *this = wsi->protocol->owning_server;
621 int n;
622
Andy Green0d338332011-02-12 11:57:43 +0000623 for (n = 0; n < this->fds_count; n++)
624 if (this->fds[n].fd == wsi->sock) {
Andy Green90c7cbc2011-01-27 06:26:52 +0000625 this->fds[n].events |= POLLOUT;
626 return 0;
627 }
628
629 fprintf(stderr, "libwebsocket_callback_on_writable "
630 "didn't find socket\n");
631 return 1;
632}
633
634/**
635 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
636 * all connections using the given protocol when it
637 * becomes possible to write to each socket without
638 * blocking in turn.
639 *
Andy Green0d338332011-02-12 11:57:43 +0000640 * This only works for internal poll() management, (ie, calling the libwebsocket
641 * service loop, you will have to make your own arrangements if your poll()
642 * loop is managed externally.
643 *
Andy Green90c7cbc2011-01-27 06:26:52 +0000644 * @protocol: Protocol whose connections will get callbacks
645 */
646
647int
648libwebsocket_callback_on_writable_all_protocol(
649 const struct libwebsocket_protocols *protocol)
650{
651 struct libwebsocket_context *this = protocol->owning_server;
652 int n;
Andy Green0d338332011-02-12 11:57:43 +0000653 int m;
654 struct libwebsocket *wsi;
Andy Green90c7cbc2011-01-27 06:26:52 +0000655
Andy Green0d338332011-02-12 11:57:43 +0000656 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
657
658 for (m = 0; m < this->fd_hashtable[n].length; m++) {
659
660 wsi = this->fd_hashtable[n].wsi[m];
661
662 if (wsi->protocol == protocol)
663 libwebsocket_callback_on_writable(wsi);
664 }
665 }
Andy Green90c7cbc2011-01-27 06:26:52 +0000666
667 return 0;
668}
669
Andy Greena6cbece2011-01-27 20:06:03 +0000670
671/**
672 * libwebsocket_get_socket_fd() - returns the socket file descriptor
673 *
674 * You will not need this unless you are doing something special
675 *
676 * @wsi: Websocket connection instance
677 */
678
679int
680libwebsocket_get_socket_fd(struct libwebsocket *wsi)
681{
682 return wsi->sock;
683}
684
Andy Green90c7cbc2011-01-27 06:26:52 +0000685/**
686 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
687 * receieved packets.
688 *
689 * If the output side of a server process becomes choked, this allows flow
690 * control for the input side.
691 *
Andy Green0d338332011-02-12 11:57:43 +0000692 * This only works for internal poll() management, (ie, calling the libwebsocket
693 * service loop, you will have to make your own arrangements if your poll()
694 * loop is managed externally.
695 *
Andy Green90c7cbc2011-01-27 06:26:52 +0000696 * @wsi: Websocket connection instance to get callback for
697 * @enable: 0 = disable read servicing for this connection, 1 = enable
698 */
699
700int
701libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
702{
703 struct libwebsocket_context *this = wsi->protocol->owning_server;
704 int n;
705
Andy Green0d338332011-02-12 11:57:43 +0000706 for (n = 0; n < this->fds_count; n++)
707 if (this->fds[n].fd == wsi->sock) {
Andy Green90c7cbc2011-01-27 06:26:52 +0000708 if (enable)
709 this->fds[n].events |= POLLIN;
710 else
711 this->fds[n].events &= ~POLLIN;
712
713 return 0;
714 }
715
716 fprintf(stderr, "libwebsocket_callback_on_writable "
717 "unable to find socket\n");
718 return 1;
719}
720
Andy Green2ac5a6f2011-01-28 10:00:18 +0000721/**
722 * libwebsocket_canonical_hostname() - returns this host's hostname
723 *
724 * This is typically used by client code to fill in the host parameter
725 * when making a client connection. You can only call it after the context
726 * has been created.
727 *
728 * @this: Websocket context
729 */
730
731
732extern const char *
733libwebsocket_canonical_hostname(struct libwebsocket_context *this)
734{
735 return (const char *)this->canonical_hostname;
736}
737
738
Andy Green90c7cbc2011-01-27 06:26:52 +0000739static void sigpipe_handler(int x)
740{
741}
742
Andy Greenb45993c2010-12-18 15:13:50 +0000743
Andy Green0d338332011-02-12 11:57:43 +0000744
Andy Greenab990e42010-10-31 12:42:52 +0000745/**
Andy Green4739e5c2011-01-22 12:51:57 +0000746 * libwebsocket_create_context() - Create the websocket handler
747 * @port: Port to listen on... you can use 0 to suppress listening on
Andy Green6964bb52011-01-23 16:50:33 +0000748 * any port, that's what you want if you are not running a
749 * websocket server at all but just using it as a client
Andy Green4f3943a2010-11-12 10:44:16 +0000750 * @protocols: Array of structures listing supported protocols and a protocol-
Andy Green8f037e42010-12-19 22:13:26 +0000751 * specific callback for each one. The list is ended with an
752 * entry that has a NULL callback pointer.
Andy Green6964bb52011-01-23 16:50:33 +0000753 * It's not const because we write the owning_server member
Andy Green3faa9c72010-11-08 17:03:03 +0000754 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
Andy Green8f037e42010-12-19 22:13:26 +0000755 * to listen using SSL, set to the filepath to fetch the
756 * server cert from, otherwise NULL for unencrypted
Andy Green3faa9c72010-11-08 17:03:03 +0000757 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
Andy Green8f037e42010-12-19 22:13:26 +0000758 * else ignored
Andy Green3faa9c72010-11-08 17:03:03 +0000759 * @gid: group id to change to after setting listen socket, or -1.
760 * @uid: user id to change to after setting listen socket, or -1.
Andy Greenbfb051f2011-02-09 08:49:14 +0000761 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
Andy Green05464c62010-11-12 10:44:18 +0000762 *
Andy Green8f037e42010-12-19 22:13:26 +0000763 * This function creates the listening socket and takes care
764 * of all initialization in one step.
765 *
Andy Greene92cd172011-01-19 13:11:55 +0000766 * After initialization, it returns a struct libwebsocket_context * that
767 * represents this server. After calling, user code needs to take care
768 * of calling libwebsocket_service() with the context pointer to get the
769 * server's sockets serviced. This can be done in the same process context
770 * or a forked process, or another thread,
Andy Green05464c62010-11-12 10:44:18 +0000771 *
Andy Green8f037e42010-12-19 22:13:26 +0000772 * The protocol callback functions are called for a handful of events
773 * including http requests coming in, websocket connections becoming
774 * established, and data arriving; it's also called periodically to allow
775 * async transmission.
776 *
777 * HTTP requests are sent always to the FIRST protocol in @protocol, since
778 * at that time websocket protocol has not been negotiated. Other
779 * protocols after the first one never see any HTTP callack activity.
780 *
781 * The server created is a simple http server by default; part of the
782 * websocket standard is upgrading this http connection to a websocket one.
783 *
784 * This allows the same server to provide files like scripts and favicon /
785 * images or whatever over http and dynamic data over websockets all in
786 * one place; they're all handled in the user callback.
Andy Greenab990e42010-10-31 12:42:52 +0000787 */
Andy Green4ea60062010-10-30 12:15:07 +0100788
Andy Greene92cd172011-01-19 13:11:55 +0000789struct libwebsocket_context *
Andy Green4739e5c2011-01-22 12:51:57 +0000790libwebsocket_create_context(int port,
Andy Greenb45993c2010-12-18 15:13:50 +0000791 struct libwebsocket_protocols *protocols,
Andy Green8f037e42010-12-19 22:13:26 +0000792 const char *ssl_cert_filepath,
793 const char *ssl_private_key_filepath,
Andy Green8014b292011-01-30 20:57:25 +0000794 int gid, int uid, unsigned int options)
Andy Greenff95d7a2010-10-28 22:36:01 +0100795{
796 int n;
Andy Green4739e5c2011-01-22 12:51:57 +0000797 int sockfd = 0;
Andy Green251f6fa2010-11-03 11:13:06 +0000798 int fd;
Andy Greenff95d7a2010-10-28 22:36:01 +0100799 struct sockaddr_in serv_addr, cli_addr;
Andy Green251f6fa2010-11-03 11:13:06 +0000800 int opt = 1;
Andy Green8f037e42010-12-19 22:13:26 +0000801 struct libwebsocket_context *this = NULL;
Andy Greenb45993c2010-12-18 15:13:50 +0000802 unsigned int slen;
Andy Green9659f372011-01-27 22:01:43 +0000803 char *p;
Andy Green2ac5a6f2011-01-28 10:00:18 +0000804 char hostname[1024];
Andy Green42f69142011-01-30 08:10:02 +0000805 struct hostent *he;
Andy Green0d338332011-02-12 11:57:43 +0000806 struct libwebsocket *wsi;
Andy Greenff95d7a2010-10-28 22:36:01 +0100807
Andy Green3faa9c72010-11-08 17:03:03 +0000808#ifdef LWS_OPENSSL_SUPPORT
Andy Greenf2f54d52010-11-15 22:08:00 +0000809 SSL_METHOD *method;
Andy Green3faa9c72010-11-08 17:03:03 +0000810 char ssl_err_buf[512];
Andy Green3faa9c72010-11-08 17:03:03 +0000811#endif
812
Andy Green90c7cbc2011-01-27 06:26:52 +0000813 this = malloc(sizeof(struct libwebsocket_context));
814 if (!this) {
815 fprintf(stderr, "No memory for websocket context\n");
816 return NULL;
817 }
818 this->protocols = protocols;
819 this->listen_port = port;
Andy Green9659f372011-01-27 22:01:43 +0000820 this->http_proxy_port = 0;
821 this->http_proxy_address[0] = '\0';
Andy Green8014b292011-01-30 20:57:25 +0000822 this->options = options;
Andy Green0d338332011-02-12 11:57:43 +0000823 this->fds_count = 0;
Andy Green9659f372011-01-27 22:01:43 +0000824
Andy Green44eee682011-02-10 09:32:24 +0000825 this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
826 if (this->fd_random < 0) {
827 fprintf(stderr, "Unable to open random device %s %d\n",
828 SYSTEM_RANDOM_FILEPATH, this->fd_random);
829 return NULL;
830 }
831
Andy Green2ac5a6f2011-01-28 10:00:18 +0000832 /* find canonical hostname */
833
834 hostname[(sizeof hostname) - 1] = '\0';
835 gethostname(hostname, (sizeof hostname) - 1);
836 he = gethostbyname(hostname);
837 strncpy(this->canonical_hostname, he->h_name,
838 sizeof this->canonical_hostname - 1);
839 this->canonical_hostname[sizeof this->canonical_hostname - 1] = '\0';
Andy Green1efb63c2011-02-06 17:42:06 +0000840 fprintf(stderr, " canonical hostname = '%s'\n",
841 this->canonical_hostname);
Andy Green2ac5a6f2011-01-28 10:00:18 +0000842
Andy Green9659f372011-01-27 22:01:43 +0000843 /* split the proxy ads:port if given */
844
845 p = getenv("http_proxy");
846 if (p) {
847 strncpy(this->http_proxy_address, p,
848 sizeof this->http_proxy_address - 1);
849 this->http_proxy_address[
850 sizeof this->http_proxy_address - 1] = '\0';
851
852 p = strchr(this->http_proxy_address, ':');
853 if (p == NULL) {
854 fprintf(stderr, "http_proxy needs to be ads:port\n");
855 return NULL;
856 }
857 *p = '\0';
858 this->http_proxy_port = atoi(p + 1);
859
860 fprintf(stderr, "Using proxy %s:%u\n",
861 this->http_proxy_address,
862 this->http_proxy_port);
863 }
Andy Green90c7cbc2011-01-27 06:26:52 +0000864
865 if (port) {
866
Andy Green3faa9c72010-11-08 17:03:03 +0000867#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +0000868 this->use_ssl = ssl_cert_filepath != NULL &&
869 ssl_private_key_filepath != NULL;
870 if (this->use_ssl)
871 fprintf(stderr, " Compiled with SSL support, "
872 "using it\n");
873 else
874 fprintf(stderr, " Compiled with SSL support, "
875 "not using it\n");
Andy Green3faa9c72010-11-08 17:03:03 +0000876
Andy Green90c7cbc2011-01-27 06:26:52 +0000877#else
878 if (ssl_cert_filepath != NULL &&
879 ssl_private_key_filepath != NULL) {
880 fprintf(stderr, " Not compiled for OpenSSl support!\n");
Andy Greene92cd172011-01-19 13:11:55 +0000881 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +0000882 }
Andy Green90c7cbc2011-01-27 06:26:52 +0000883 fprintf(stderr, " Compiled without SSL support, "
884 "serving unencrypted\n");
885#endif
886 }
887
888 /* ignore SIGPIPE */
889
890 signal(SIGPIPE, sigpipe_handler);
891
892
893#ifdef LWS_OPENSSL_SUPPORT
894
895 /* basic openssl init */
896
897 SSL_library_init();
898
899 OpenSSL_add_all_algorithms();
900 SSL_load_error_strings();
901
902 /*
903 * Firefox insists on SSLv23 not SSLv3
904 * Konq disables SSLv2 by default now, SSLv23 works
905 */
906
907 method = (SSL_METHOD *)SSLv23_server_method();
908 if (!method) {
909 fprintf(stderr, "problem creating ssl method: %s\n",
910 ERR_error_string(ERR_get_error(), ssl_err_buf));
911 return NULL;
912 }
913 this->ssl_ctx = SSL_CTX_new(method); /* create context */
914 if (!this->ssl_ctx) {
915 fprintf(stderr, "problem creating ssl context: %s\n",
916 ERR_error_string(ERR_get_error(), ssl_err_buf));
917 return NULL;
918 }
919
920 /* client context */
921
922 method = (SSL_METHOD *)SSLv23_client_method();
923 if (!method) {
924 fprintf(stderr, "problem creating ssl method: %s\n",
925 ERR_error_string(ERR_get_error(), ssl_err_buf));
926 return NULL;
927 }
928 this->ssl_client_ctx = SSL_CTX_new(method); /* create context */
929 if (!this->ssl_client_ctx) {
930 fprintf(stderr, "problem creating ssl context: %s\n",
931 ERR_error_string(ERR_get_error(), ssl_err_buf));
932 return NULL;
933 }
934
935
936 /* openssl init for cert verification (used with client sockets) */
937
938 if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
939 LWS_OPENSSL_CLIENT_CERTS)) {
940 fprintf(stderr, "Unable to load SSL Client certs from %s "
941 "(set by --with-client-cert-dir= in configure) -- "
942 " client ssl isn't going to work",
943 LWS_OPENSSL_CLIENT_CERTS);
944 }
945
946 if (this->use_ssl) {
947
948 /* openssl init for server sockets */
949
Andy Green3faa9c72010-11-08 17:03:03 +0000950 /* set the local certificate from CertFile */
Andy Green90c7cbc2011-01-27 06:26:52 +0000951 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
Andy Green3faa9c72010-11-08 17:03:03 +0000952 ssl_cert_filepath, SSL_FILETYPE_PEM);
953 if (n != 1) {
954 fprintf(stderr, "problem getting cert '%s': %s\n",
955 ssl_cert_filepath,
956 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +0000957 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +0000958 }
959 /* set the private key from KeyFile */
Andy Green90c7cbc2011-01-27 06:26:52 +0000960 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
Andy Green018d8eb2010-11-08 21:04:23 +0000961 ssl_private_key_filepath,
Andy Green4739e5c2011-01-22 12:51:57 +0000962 SSL_FILETYPE_PEM) != 1) {
Andy Green018d8eb2010-11-08 21:04:23 +0000963 fprintf(stderr, "ssl problem getting key '%s': %s\n",
964 ssl_private_key_filepath,
965 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +0000966 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +0000967 }
968 /* verify private key */
Andy Green90c7cbc2011-01-27 06:26:52 +0000969 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
Andy Green018d8eb2010-11-08 21:04:23 +0000970 fprintf(stderr, "Private SSL key doesn't match cert\n");
Andy Greene92cd172011-01-19 13:11:55 +0000971 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +0000972 }
973
974 /* SSL is happy and has a cert it's content with */
975 }
976#endif
Andy Greenb45993c2010-12-18 15:13:50 +0000977
Andy Greendf736162011-01-18 15:39:02 +0000978 /* selftest */
979
980 if (lws_b64_selftest())
Andy Greene92cd172011-01-19 13:11:55 +0000981 return NULL;
Andy Greendf736162011-01-18 15:39:02 +0000982
Andy Green0d338332011-02-12 11:57:43 +0000983 /* fd hashtable init */
984
985 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
986 this->fd_hashtable[n].length = 0;
987
Andy Greenb45993c2010-12-18 15:13:50 +0000988 /* set up our external listening socket we serve on */
Andy Green8f037e42010-12-19 22:13:26 +0000989
Andy Green4739e5c2011-01-22 12:51:57 +0000990 if (port) {
Andy Green8f037e42010-12-19 22:13:26 +0000991
Andy Green4739e5c2011-01-22 12:51:57 +0000992 sockfd = socket(AF_INET, SOCK_STREAM, 0);
993 if (sockfd < 0) {
994 fprintf(stderr, "ERROR opening socket");
995 return NULL;
996 }
Andy Green775c0dd2010-10-29 14:15:22 +0100997
Andy Green4739e5c2011-01-22 12:51:57 +0000998 /* allow us to restart even if old sockets in TIME_WAIT */
999 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
Andy Greene77ddd82010-11-13 10:03:47 +00001000
Andy Green4739e5c2011-01-22 12:51:57 +00001001 bzero((char *) &serv_addr, sizeof(serv_addr));
1002 serv_addr.sin_family = AF_INET;
1003 serv_addr.sin_addr.s_addr = INADDR_ANY;
1004 serv_addr.sin_port = htons(port);
1005
1006 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1007 sizeof(serv_addr));
1008 if (n < 0) {
1009 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Green8f037e42010-12-19 22:13:26 +00001010 port, n, errno);
Andy Green4739e5c2011-01-22 12:51:57 +00001011 return NULL;
1012 }
Andy Green0d338332011-02-12 11:57:43 +00001013
1014 wsi = malloc(sizeof(struct libwebsocket));
1015 memset(wsi, 0, sizeof (struct libwebsocket));
1016 wsi->sock = sockfd;
1017 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1018 insert_wsi(this, wsi);
1019
1020 listen(sockfd, 5);
1021 fprintf(stderr, " Listening on port %d\n", port);
1022
1023 /* list in the internal poll array */
1024
1025 this->fds[this->fds_count].fd = sockfd;
1026 this->fds[this->fds_count++].events = POLLIN;
Andy Green8f037e42010-12-19 22:13:26 +00001027 }
Andy Greenb45993c2010-12-18 15:13:50 +00001028
Andy Greene77ddd82010-11-13 10:03:47 +00001029 /* drop any root privs for this process */
Andy Green3faa9c72010-11-08 17:03:03 +00001030
1031 if (gid != -1)
1032 if (setgid(gid))
1033 fprintf(stderr, "setgid: %s\n", strerror(errno));
1034 if (uid != -1)
1035 if (setuid(uid))
1036 fprintf(stderr, "setuid: %s\n", strerror(errno));
1037
Andy Greenb45993c2010-12-18 15:13:50 +00001038
1039 /* set up our internal broadcast trigger sockets per-protocol */
1040
Andy Green0d338332011-02-12 11:57:43 +00001041 for (this->count_protocols = 0;
1042 protocols[this->count_protocols].callback;
Andy Greenb45993c2010-12-18 15:13:50 +00001043 this->count_protocols++) {
1044 protocols[this->count_protocols].owning_server = this;
1045 protocols[this->count_protocols].protocol_index =
1046 this->count_protocols;
1047
1048 fd = socket(AF_INET, SOCK_STREAM, 0);
1049 if (fd < 0) {
1050 fprintf(stderr, "ERROR opening socket");
Andy Greene92cd172011-01-19 13:11:55 +00001051 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001052 }
Andy Green8f037e42010-12-19 22:13:26 +00001053
Andy Greenb45993c2010-12-18 15:13:50 +00001054 /* allow us to restart even if old sockets in TIME_WAIT */
1055 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1056
1057 bzero((char *) &serv_addr, sizeof(serv_addr));
1058 serv_addr.sin_family = AF_INET;
1059 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1060 serv_addr.sin_port = 0; /* pick the port for us */
1061
1062 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1063 if (n < 0) {
Andy Green8f037e42010-12-19 22:13:26 +00001064 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Greenb45993c2010-12-18 15:13:50 +00001065 port, n, errno);
Andy Greene92cd172011-01-19 13:11:55 +00001066 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001067 }
1068
1069 slen = sizeof cli_addr;
1070 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1071 if (n < 0) {
1072 fprintf(stderr, "getsockname failed\n");
Andy Greene92cd172011-01-19 13:11:55 +00001073 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001074 }
1075 protocols[this->count_protocols].broadcast_socket_port =
1076 ntohs(cli_addr.sin_port);
1077 listen(fd, 5);
1078
1079 debug(" Protocol %s broadcast socket %d\n",
1080 protocols[this->count_protocols].name,
1081 ntohs(cli_addr.sin_port));
1082
Andy Green0d338332011-02-12 11:57:43 +00001083 /* dummy wsi per broadcast proxy socket */
1084
1085 wsi = malloc(sizeof(struct libwebsocket));
1086 memset(wsi, 0, sizeof (struct libwebsocket));
1087 wsi->sock = fd;
1088 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1089 /* note which protocol we are proxying */
1090 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1091 insert_wsi(this, wsi);
1092
1093 /* list in internal poll array */
1094
Andy Greenb45993c2010-12-18 15:13:50 +00001095 this->fds[this->fds_count].fd = fd;
1096 this->fds[this->fds_count].events = POLLIN;
Andy Greenb45993c2010-12-18 15:13:50 +00001097 this->fds_count++;
1098 }
1099
Andy Greene92cd172011-01-19 13:11:55 +00001100 return this;
1101}
Andy Greenb45993c2010-12-18 15:13:50 +00001102
Andy Green4739e5c2011-01-22 12:51:57 +00001103
Andy Greened11a022011-01-20 10:23:50 +00001104#ifndef LWS_NO_FORK
1105
Andy Greene92cd172011-01-19 13:11:55 +00001106/**
1107 * libwebsockets_fork_service_loop() - Optional helper function forks off
1108 * a process for the websocket server loop.
Andy Green6964bb52011-01-23 16:50:33 +00001109 * You don't have to use this but if not, you
1110 * have to make sure you are calling
1111 * libwebsocket_service periodically to service
1112 * the websocket traffic
Andy Greene92cd172011-01-19 13:11:55 +00001113 * @this: server context returned by creation function
1114 */
Andy Greenb45993c2010-12-18 15:13:50 +00001115
Andy Greene92cd172011-01-19 13:11:55 +00001116int
1117libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1118{
1119 int client;
1120 int fd;
1121 struct sockaddr_in cli_addr;
1122 int n;
Andy Greenb45993c2010-12-18 15:13:50 +00001123
Andy Greened11a022011-01-20 10:23:50 +00001124 n = fork();
1125 if (n < 0)
1126 return n;
1127
1128 if (!n) {
1129
1130 /* main process context */
1131
1132 for (client = 1; client < this->count_protocols + 1; client++) {
1133 fd = socket(AF_INET, SOCK_STREAM, 0);
1134 if (fd < 0) {
1135 fprintf(stderr, "Unable to create socket\n");
1136 return -1;
1137 }
1138 cli_addr.sin_family = AF_INET;
1139 cli_addr.sin_port = htons(
Andy Green4739e5c2011-01-22 12:51:57 +00001140 this->protocols[client - 1].broadcast_socket_port);
Andy Greened11a022011-01-20 10:23:50 +00001141 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1142 n = connect(fd, (struct sockaddr *)&cli_addr,
1143 sizeof cli_addr);
1144 if (n < 0) {
1145 fprintf(stderr, "Unable to connect to "
1146 "broadcast socket %d, %s\n",
1147 client, strerror(errno));
1148 return -1;
1149 }
1150
Andy Green4739e5c2011-01-22 12:51:57 +00001151 this->protocols[client - 1].broadcast_socket_user_fd =
1152 fd;
Andy Greened11a022011-01-20 10:23:50 +00001153 }
1154
1155
Andy Greene92cd172011-01-19 13:11:55 +00001156 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00001157 }
1158
1159 /* we want a SIGHUP when our parent goes down */
1160 prctl(PR_SET_PDEATHSIG, SIGHUP);
1161
1162 /* in this forked process, sit and service websocket connections */
Andy Green8f037e42010-12-19 22:13:26 +00001163
Andy Greene92cd172011-01-19 13:11:55 +00001164 while (1)
1165 if (libwebsocket_service(this, 1000))
1166 return -1;
Andy Green8f037e42010-12-19 22:13:26 +00001167
Andy Green251f6fa2010-11-03 11:13:06 +00001168 return 0;
Andy Greenff95d7a2010-10-28 22:36:01 +01001169}
1170
Andy Greened11a022011-01-20 10:23:50 +00001171#endif
1172
Andy Greenb45993c2010-12-18 15:13:50 +00001173/**
1174 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
Andy Green8f037e42010-12-19 22:13:26 +00001175 * connection.
Andy Greenb45993c2010-12-18 15:13:50 +00001176 * @wsi: pointer to struct websocket you want to know the protocol of
1177 *
Andy Green8f037e42010-12-19 22:13:26 +00001178 *
1179 * This is useful to get the protocol to broadcast back to from inside
Andy Greenb45993c2010-12-18 15:13:50 +00001180 * the callback.
1181 */
Andy Greenab990e42010-10-31 12:42:52 +00001182
Andy Greenb45993c2010-12-18 15:13:50 +00001183const struct libwebsocket_protocols *
1184libwebsockets_get_protocol(struct libwebsocket *wsi)
1185{
1186 return wsi->protocol;
1187}
1188
1189/**
Andy Greene92cd172011-01-19 13:11:55 +00001190 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
Andy Green8f037e42010-12-19 22:13:26 +00001191 * connections of the given protocol.
Andy Greenb45993c2010-12-18 15:13:50 +00001192 * @protocol: pointer to the protocol you will broadcast to all members of
1193 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
Andy Green8f037e42010-12-19 22:13:26 +00001194 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1195 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1196 * case you are calling this function from callback context.
Andy Greenb45993c2010-12-18 15:13:50 +00001197 * @len: length of payload data in buf, starting from buf.
Andy Green8f037e42010-12-19 22:13:26 +00001198 *
1199 * This function allows bulk sending of a packet to every connection using
Andy Greenb45993c2010-12-18 15:13:50 +00001200 * the given protocol. It does not send the data directly; instead it calls
1201 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
1202 * wants to actually send the data for that connection, the callback itself
1203 * should call libwebsocket_write().
1204 *
1205 * libwebsockets_broadcast() can be called from another fork context without
1206 * having to take any care about data visibility between the processes, it'll
1207 * "just work".
1208 */
1209
1210
1211int
Andy Green8f037e42010-12-19 22:13:26 +00001212libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
Andy Greenb45993c2010-12-18 15:13:50 +00001213 unsigned char *buf, size_t len)
1214{
Andy Green8f037e42010-12-19 22:13:26 +00001215 struct libwebsocket_context *this = protocol->owning_server;
Andy Greenb45993c2010-12-18 15:13:50 +00001216 int n;
Andy Green0d338332011-02-12 11:57:43 +00001217 int m;
1218 struct libwebsocket * wsi;
Andy Greenb45993c2010-12-18 15:13:50 +00001219
1220 if (!protocol->broadcast_socket_user_fd) {
1221 /*
Andy Greene92cd172011-01-19 13:11:55 +00001222 * We are either running unforked / flat, or we are being
1223 * called from poll thread context
Andy Greenb45993c2010-12-18 15:13:50 +00001224 * eg, from a callback. In that case don't use sockets for
1225 * broadcast IPC (since we can't open a socket connection to
1226 * a socket listening on our own thread) but directly do the
1227 * send action.
1228 *
1229 * Locking is not needed because we are by definition being
1230 * called in the poll thread context and are serialized.
1231 */
1232
Andy Green0d338332011-02-12 11:57:43 +00001233 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Greenb45993c2010-12-18 15:13:50 +00001234
Andy Green0d338332011-02-12 11:57:43 +00001235 for (m = 0; m < this->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +00001236
Andy Green0d338332011-02-12 11:57:43 +00001237 wsi = this->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +00001238
Andy Green0d338332011-02-12 11:57:43 +00001239 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1240 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00001241
Andy Green0d338332011-02-12 11:57:43 +00001242 /*
1243 * never broadcast to
1244 * non-established connections
1245 */
1246 if (wsi->state != WSI_STATE_ESTABLISHED)
1247 continue;
1248
1249 /* only broadcast to guys using
1250 * requested protocol
1251 */
1252 if (wsi->protocol != protocol)
1253 continue;
1254
1255 wsi->protocol->callback(wsi,
Andy Green8f037e42010-12-19 22:13:26 +00001256 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +00001257 wsi->user_space,
Andy Greenb45993c2010-12-18 15:13:50 +00001258 buf, len);
Andy Green0d338332011-02-12 11:57:43 +00001259 }
Andy Greenb45993c2010-12-18 15:13:50 +00001260 }
1261
1262 return 0;
1263 }
1264
Andy Green0ca6a172010-12-19 20:50:01 +00001265 /*
1266 * We're being called from a different process context than the server
1267 * loop. Instead of broadcasting directly, we send our
1268 * payload on a socket to do the IPC; the server process will serialize
1269 * the broadcast action in its main poll() loop.
1270 *
1271 * There's one broadcast socket listening for each protocol supported
1272 * set up when the websocket server initializes
1273 */
1274
Andy Green6964bb52011-01-23 16:50:33 +00001275 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
Andy Greenb45993c2010-12-18 15:13:50 +00001276
1277 return n;
1278}