blob: 1c4bd1760aff81e5722048c86af17c273b33a48b [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 Green3faa9c72010-11-08 17:03:03 +000024#ifdef LWS_OPENSSL_SUPPORT
Andy Green3faa9c72010-11-08 17:03:03 +000025SSL_CTX *ssl_ctx;
26int use_ssl;
27#endif
28
Andy Green8f037e42010-12-19 22:13:26 +000029void
Andy Green251f6fa2010-11-03 11:13:06 +000030libwebsocket_close_and_free_session(struct libwebsocket *wsi)
31{
Andy Greenb45993c2010-12-18 15:13:50 +000032 int n;
33
34 if ((unsigned long)wsi < LWS_MAX_PROTOCOLS)
35 return;
36
37 n = wsi->state;
Andy Green251f6fa2010-11-03 11:13:06 +000038
39 wsi->state = WSI_STATE_DEAD_SOCKET;
40
Andy Green4f3943a2010-11-12 10:44:16 +000041 if (wsi->protocol->callback && n == WSI_STATE_ESTABLISHED)
Andy Greene77ddd82010-11-13 10:03:47 +000042 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
43 wsi->user_space, NULL, 0);
Andy Green251f6fa2010-11-03 11:13:06 +000044
45 for (n = 0; n < WSI_TOKEN_COUNT; n++)
46 if (wsi->utf8_token[n].token)
47 free(wsi->utf8_token[n].token);
48
Andy Green0ca6a172010-12-19 20:50:01 +000049/* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
Andy Green251f6fa2010-11-03 11:13:06 +000050
Andy Green3faa9c72010-11-08 17:03:03 +000051#ifdef LWS_OPENSSL_SUPPORT
52 if (use_ssl) {
53 n = SSL_get_fd(wsi->ssl);
54 SSL_shutdown(wsi->ssl);
55 close(n);
56 SSL_free(wsi->ssl);
57 } else {
58#endif
59 shutdown(wsi->sock, SHUT_RDWR);
60 close(wsi->sock);
61#ifdef LWS_OPENSSL_SUPPORT
62 }
63#endif
Andy Green4f3943a2010-11-12 10:44:16 +000064 if (wsi->user_space)
65 free(wsi->user_space);
66
Andy Green251f6fa2010-11-03 11:13:06 +000067 free(wsi);
68}
69
Andy Greenb45993c2010-12-18 15:13:50 +000070static int
71libwebsocket_poll_connections(struct libwebsocket_context *this)
72{
73 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
74 LWS_SEND_BUFFER_POST_PADDING];
Andy Green8f037e42010-12-19 22:13:26 +000075 int client = this->count_protocols + 1;
76 struct libwebsocket *wsi;
Andy Greenb45993c2010-12-18 15:13:50 +000077 int n;
78 size_t len;
79
80 /* check for activity on client sockets */
Andy Green8f037e42010-12-19 22:13:26 +000081
82 for (; client < this->fds_count; client++) {
83
Andy Greenb45993c2010-12-18 15:13:50 +000084 /* handle session socket closed */
Andy Green8f037e42010-12-19 22:13:26 +000085
Andy Greenb45993c2010-12-18 15:13:50 +000086 if (this->fds[client].revents & (POLLERR | POLLHUP)) {
Andy Green8f037e42010-12-19 22:13:26 +000087
Andy Greenb45993c2010-12-18 15:13:50 +000088 debug("Session Socket %d %p (fd=%d) dead\n",
Andy Green6964bb52011-01-23 16:50:33 +000089 client, (void *)this->wsi[client],
90 this->fds[client].fd);
Andy Greenb45993c2010-12-18 15:13:50 +000091
92 libwebsocket_close_and_free_session(this->wsi[client]);
93 goto nuke_this;
94 }
Andy Green8f037e42010-12-19 22:13:26 +000095
Andy Greenb45993c2010-12-18 15:13:50 +000096 /* any incoming data ready? */
97
98 if (!(this->fds[client].revents & POLLIN))
99 continue;
100
101 /* broadcast? */
102
103 if ((unsigned long)this->wsi[client] < LWS_MAX_PROTOCOLS) {
104
Andy Green8f037e42010-12-19 22:13:26 +0000105 /* get the issued broadcast payload from the socket */
106
Andy Greenb45993c2010-12-18 15:13:50 +0000107 len = read(this->fds[client].fd,
108 buf + LWS_SEND_BUFFER_PRE_PADDING,
109 MAX_BROADCAST_PAYLOAD);
Andy Green8f037e42010-12-19 22:13:26 +0000110
Andy Greenb45993c2010-12-18 15:13:50 +0000111 if (len < 0) {
Andy Green8f037e42010-12-19 22:13:26 +0000112 fprintf(stderr,
113 "Error reading broadcast payload\n");
Andy Greenb45993c2010-12-18 15:13:50 +0000114 continue;
115 }
116
117 /* broadcast it to all guys with this protocol index */
118
119 for (n = this->count_protocols + 1;
120 n < this->fds_count; n++) {
121
Andy Green8f037e42010-12-19 22:13:26 +0000122 wsi = this->wsi[n];
123
124 if ((unsigned long)wsi < LWS_MAX_PROTOCOLS)
Andy Greenb45993c2010-12-18 15:13:50 +0000125 continue;
126
127 /*
128 * never broadcast to non-established
129 * connection
130 */
131
Andy Green8f037e42010-12-19 22:13:26 +0000132 if (wsi->state != WSI_STATE_ESTABLISHED)
Andy Greenb45993c2010-12-18 15:13:50 +0000133 continue;
134
Andy Green4739e5c2011-01-22 12:51:57 +0000135 /* only to clients connected to us */
Andy Green6964bb52011-01-23 16:50:33 +0000136
Andy Green4739e5c2011-01-22 12:51:57 +0000137 if (wsi->client_mode)
138 continue;
139
Andy Greenb45993c2010-12-18 15:13:50 +0000140 /*
141 * only broadcast to connections using
142 * the requested protocol
143 */
144
Andy Green8f037e42010-12-19 22:13:26 +0000145 if (wsi->protocol->protocol_index !=
146 (int)(unsigned long)this->wsi[client])
Andy Greenb45993c2010-12-18 15:13:50 +0000147 continue;
148
Andy Green8f037e42010-12-19 22:13:26 +0000149 /* broadcast it to this connection */
150
151 wsi->protocol->callback(wsi,
152 LWS_CALLBACK_BROADCAST,
153 wsi->user_space,
Andy Green0ca6a172010-12-19 20:50:01 +0000154 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
Andy Greenb45993c2010-12-18 15:13:50 +0000155 }
156
157 continue;
158 }
159
160#ifdef LWS_OPENSSL_SUPPORT
161 if (this->use_ssl)
162 n = SSL_read(this->wsi[client]->ssl, buf, sizeof buf);
163 else
164#endif
165 n = recv(this->fds[client].fd, buf, sizeof buf, 0);
166
167 if (n < 0) {
168 fprintf(stderr, "Socket read returned %d\n", n);
169 continue;
170 }
171 if (!n) {
Andy Green8f037e42010-12-19 22:13:26 +0000172 libwebsocket_close_and_free_session(this->wsi[client]);
Andy Greenb45993c2010-12-18 15:13:50 +0000173 goto nuke_this;
174 }
175
Andy Greenb45993c2010-12-18 15:13:50 +0000176 /* service incoming data */
177
Andy Green6964bb52011-01-23 16:50:33 +0000178 n = libwebsocket_read(this->wsi[client], buf, n);
179 if (n >= 0)
Andy Greenb45993c2010-12-18 15:13:50 +0000180 continue;
Andy Greenb45993c2010-12-18 15:13:50 +0000181 /*
182 * it closed and nuked wsi[client], so remove the
183 * socket handle and wsi from our service list
184 */
185nuke_this:
186
187 debug("nuking wsi %p, fsd_count = %d\n",
Andy Green6964bb52011-01-23 16:50:33 +0000188 (void *)this->wsi[client], this->fds_count - 1);
Andy Greenb45993c2010-12-18 15:13:50 +0000189
190 this->fds_count--;
191 for (n = client; n < this->fds_count; n++) {
192 this->fds[n] = this->fds[n + 1];
193 this->wsi[n] = this->wsi[n + 1];
194 }
Andy Green6964bb52011-01-23 16:50:33 +0000195
196 return 0;
197
Andy Greenb45993c2010-12-18 15:13:50 +0000198 }
199
200 return 0;
201}
202
Andy Green6964bb52011-01-23 16:50:33 +0000203/**
204 * libwebsocket_context_destroy() - Destroy the websocket context
205 * @this: Websocket context
206 *
207 * This function closes any active connections and then frees the
208 * context. After calling this, any further use of the context is
209 * undefined.
210 */
211void
212libwebsocket_context_destroy(struct libwebsocket_context *this)
213{
214 int client;
215
216 /* close listening skt and per-protocol broadcast sockets */
217 for (client = 0; client < this->fds_count; client++)
218 libwebsocket_close_and_free_session(this->wsi[client]);
219
220#ifdef LWS_OPENSSL_SUPPORT
221 if (ssl_ctx)
222 SSL_CTX_free(ssl_ctx);
223#endif
224
225 if (this)
226 free(this);
227}
228
229/**
230 * libwebsocket_service() - Service any pending websocket activity
231 * @this: Websocket context
232 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
233 * service otherwise block and service immediately, returning
234 * after the timeout if nothing needed service.
235 *
236 * This function deals with any pending websocket traffic, for three
237 * kinds of event. It handles these events on both server and client
238 * types of connection the same.
239 *
240 * 1) Accept new connections to our context's server
241 *
242 * 2) Perform pending broadcast writes initiated from other forked
243 * processes (effectively serializing asynchronous broadcasts)
244 *
245 * 3) Call the receive callback for incoming frame data received by
246 * server or client connections.
247 *
248 * You need to call this service function periodically to all the above
249 * functions to happen; if your application is single-threaded you can
250 * just call it in your main event loop.
251 *
252 * Alternatively you can fork a new process that asynchronously handles
253 * calling this service in a loop. In that case you are happy if this
254 * call blocks your thread until it needs to take care of something and
255 * would call it with a large nonzero timeout. Your loop then takes no
256 * CPU while there is nothing happening.
257 *
258 * If you are calling it in a single-threaded app, you don't want it to
259 * wait around blocking other things in your loop from happening, so you
260 * would call it with a timeout_ms of 0, so it returns immediately if
261 * nothing is pending, or as soon as it services whatever was pending.
262 */
263
Andy Greenb45993c2010-12-18 15:13:50 +0000264
Andy Greene92cd172011-01-19 13:11:55 +0000265int
266libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
267{
268 int n;
269 int client;
270 unsigned int clilen;
271 struct sockaddr_in cli_addr;
272 int fd;
273
274 /* stay dead once we are dead */
275
276 if (this == NULL)
277 return 1;
278
Andy Green4739e5c2011-01-22 12:51:57 +0000279 /* don't check listen socket if we are not listening */
280
281 if (this->listen_port)
282 n = poll(this->fds, this->fds_count, timeout_ms);
283 else
284 n = poll(&this->fds[1], this->fds_count - 1, timeout_ms);
Andy Green6964bb52011-01-23 16:50:33 +0000285
Andy Greene92cd172011-01-19 13:11:55 +0000286
287 if (n < 0 || this->fds[0].revents & (POLLERR | POLLHUP)) {
288 fprintf(stderr, "Listen Socket dead\n");
289 goto fatal;
290 }
291 if (n == 0) /* poll timeout */
292 return 0;
293
294 /* handle accept on listening socket? */
295
296 for (client = 0; client < this->count_protocols + 1; client++) {
297
298 if (!this->fds[client].revents & POLLIN)
299 continue;
300
301 /* listen socket got an unencrypted connection... */
302
303 clilen = sizeof(cli_addr);
304 fd = accept(this->fds[client].fd,
305 (struct sockaddr *)&cli_addr, &clilen);
306 if (fd < 0) {
307 fprintf(stderr, "ERROR on accept");
308 continue;
309 }
310
311 if (this->fds_count >= MAX_CLIENTS) {
312 fprintf(stderr, "too busy");
313 close(fd);
314 continue;
315 }
316
317 if (client) {
318 /*
319 * accepting a connection to broadcast socket
320 * set wsi to be protocol index not pointer
321 */
322
323 this->wsi[this->fds_count] =
324 (struct libwebsocket *)(long)(client - 1);
325
326 goto fill_in_fds;
327 }
328
329 /* accepting connection to main listener */
330
331 this->wsi[this->fds_count] =
332 malloc(sizeof(struct libwebsocket));
333 if (!this->wsi[this->fds_count]) {
334 fprintf(stderr, "Out of memory for new connection\n");
335 continue;
336 }
337
338#ifdef LWS_OPENSSL_SUPPORT
339 if (this->use_ssl) {
340
341 this->wsi[this->fds_count]->ssl = SSL_new(ssl_ctx);
342 if (this->wsi[this->fds_count]->ssl == NULL) {
343 fprintf(stderr, "SSL_new failed: %s\n",
344 ERR_error_string(SSL_get_error(
345 this->wsi[this->fds_count]->ssl, 0),
346 NULL));
347 free(this->wsi[this->fds_count]);
348 continue;
349 }
350
351 SSL_set_fd(this->wsi[this->fds_count]->ssl, fd);
352
353 n = SSL_accept(this->wsi[this->fds_count]->ssl);
354 if (n != 1) {
355 /*
356 * browsers seem to probe with various
357 * ssl params which fail then retry
358 * and succeed
359 */
360 debug("SSL_accept failed skt %u: %s\n",
361 fd,
362 ERR_error_string(SSL_get_error(
363 this->wsi[this->fds_count]->ssl,
364 n), NULL));
365 SSL_free(
366 this->wsi[this->fds_count]->ssl);
367 free(this->wsi[this->fds_count]);
368 continue;
369 }
370 debug("accepted new SSL conn "
371 "port %u on fd=%d SSL ver %s\n",
372 ntohs(cli_addr.sin_port), fd,
373 SSL_get_version(this->wsi[
374 this->fds_count]->ssl));
375
376 } else
377#endif
378 debug("accepted new conn port %u on fd=%d\n",
379 ntohs(cli_addr.sin_port), fd);
380
381 /* intialize the instance struct */
382
383 this->wsi[this->fds_count]->sock = fd;
384 this->wsi[this->fds_count]->state = WSI_STATE_HTTP;
385 this->wsi[this->fds_count]->name_buffer_pos = 0;
Andy Green4739e5c2011-01-22 12:51:57 +0000386 this->wsi[this->fds_count]->client_mode = 0;
Andy Greene92cd172011-01-19 13:11:55 +0000387
388 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
389 this->wsi[this->fds_count]->
390 utf8_token[n].token = NULL;
391 this->wsi[this->fds_count]->
392 utf8_token[n].token_len = 0;
393 }
394
395 /*
396 * these can only be set once the protocol is known
397 * we set an unestablished connection's protocol pointer
398 * to the start of the supported list, so it can look
399 * for matching ones during the handshake
400 */
401 this->wsi[this->fds_count]->protocol = this->protocols;
402 this->wsi[this->fds_count]->user_space = NULL;
403
404 /*
405 * Default protocol is 76 / 00
406 * After 76, there's a header specified to inform which
407 * draft the client wants, when that's seen we modify
408 * the individual connection's spec revision accordingly
409 */
410 this->wsi[this->fds_count]->ietf_spec_revision = 0;
411
412fill_in_fds:
413
414 /*
415 * make sure NO events are seen yet on this new socket
416 * (otherwise we inherit old fds[client].revents from
417 * previous socket there and die mysteriously! )
418 */
419 this->fds[this->fds_count].revents = 0;
420
421 this->fds[this->fds_count].events = POLLIN;
422 this->fds[this->fds_count++].fd = fd;
423
424 }
425
426 /* service anything incoming on websocket connection */
427
428 libwebsocket_poll_connections(this);
429
430 /* this round is done */
431
432 return 0;
433
434fatal:
435
Andy Green6964bb52011-01-23 16:50:33 +0000436 fprintf(stderr, "service hits fatal\n");
437
Andy Greene92cd172011-01-19 13:11:55 +0000438 /* close listening skt and per-protocol broadcast sockets */
439 for (client = 0; client < this->fds_count; client++)
440 close(this->fds[0].fd);
441
442#ifdef LWS_OPENSSL_SUPPORT
443 SSL_CTX_free(ssl_ctx);
444#endif
Andy Greene92cd172011-01-19 13:11:55 +0000445
446 if (this)
447 free(this);
448
449 this = NULL;
450
451 /* inform caller we are dead */
452
453 return 1;
454}
455
Andy Greenb45993c2010-12-18 15:13:50 +0000456
Andy Greenab990e42010-10-31 12:42:52 +0000457/**
Andy Green4739e5c2011-01-22 12:51:57 +0000458 * libwebsocket_create_context() - Create the websocket handler
459 * @port: Port to listen on... you can use 0 to suppress listening on
Andy Green6964bb52011-01-23 16:50:33 +0000460 * any port, that's what you want if you are not running a
461 * websocket server at all but just using it as a client
Andy Green4f3943a2010-11-12 10:44:16 +0000462 * @protocols: Array of structures listing supported protocols and a protocol-
Andy Green8f037e42010-12-19 22:13:26 +0000463 * specific callback for each one. The list is ended with an
464 * entry that has a NULL callback pointer.
Andy Green6964bb52011-01-23 16:50:33 +0000465 * It's not const because we write the owning_server member
Andy Green3faa9c72010-11-08 17:03:03 +0000466 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
Andy Green8f037e42010-12-19 22:13:26 +0000467 * to listen using SSL, set to the filepath to fetch the
468 * server cert from, otherwise NULL for unencrypted
Andy Green3faa9c72010-11-08 17:03:03 +0000469 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
Andy Green8f037e42010-12-19 22:13:26 +0000470 * else ignored
Andy Green3faa9c72010-11-08 17:03:03 +0000471 * @gid: group id to change to after setting listen socket, or -1.
472 * @uid: user id to change to after setting listen socket, or -1.
Andy Green05464c62010-11-12 10:44:18 +0000473 *
Andy Green8f037e42010-12-19 22:13:26 +0000474 * This function creates the listening socket and takes care
475 * of all initialization in one step.
476 *
Andy Greene92cd172011-01-19 13:11:55 +0000477 * After initialization, it returns a struct libwebsocket_context * that
478 * represents this server. After calling, user code needs to take care
479 * of calling libwebsocket_service() with the context pointer to get the
480 * server's sockets serviced. This can be done in the same process context
481 * or a forked process, or another thread,
Andy Green05464c62010-11-12 10:44:18 +0000482 *
Andy Green8f037e42010-12-19 22:13:26 +0000483 * The protocol callback functions are called for a handful of events
484 * including http requests coming in, websocket connections becoming
485 * established, and data arriving; it's also called periodically to allow
486 * async transmission.
487 *
488 * HTTP requests are sent always to the FIRST protocol in @protocol, since
489 * at that time websocket protocol has not been negotiated. Other
490 * protocols after the first one never see any HTTP callack activity.
491 *
492 * The server created is a simple http server by default; part of the
493 * websocket standard is upgrading this http connection to a websocket one.
494 *
495 * This allows the same server to provide files like scripts and favicon /
496 * images or whatever over http and dynamic data over websockets all in
497 * one place; they're all handled in the user callback.
Andy Greenab990e42010-10-31 12:42:52 +0000498 */
Andy Green4ea60062010-10-30 12:15:07 +0100499
Andy Greene92cd172011-01-19 13:11:55 +0000500struct libwebsocket_context *
Andy Green4739e5c2011-01-22 12:51:57 +0000501libwebsocket_create_context(int port,
Andy Greenb45993c2010-12-18 15:13:50 +0000502 struct libwebsocket_protocols *protocols,
Andy Green8f037e42010-12-19 22:13:26 +0000503 const char *ssl_cert_filepath,
504 const char *ssl_private_key_filepath,
Andy Greence510c62010-11-11 12:48:13 +0000505 int gid, int uid)
Andy Greenff95d7a2010-10-28 22:36:01 +0100506{
507 int n;
Andy Green4739e5c2011-01-22 12:51:57 +0000508 int sockfd = 0;
Andy Green251f6fa2010-11-03 11:13:06 +0000509 int fd;
Andy Greenff95d7a2010-10-28 22:36:01 +0100510 struct sockaddr_in serv_addr, cli_addr;
Andy Green251f6fa2010-11-03 11:13:06 +0000511 int opt = 1;
Andy Green8f037e42010-12-19 22:13:26 +0000512 struct libwebsocket_context *this = NULL;
Andy Greenb45993c2010-12-18 15:13:50 +0000513 unsigned int slen;
Andy Greenff95d7a2010-10-28 22:36:01 +0100514
Andy Green3faa9c72010-11-08 17:03:03 +0000515#ifdef LWS_OPENSSL_SUPPORT
Andy Greenf2f54d52010-11-15 22:08:00 +0000516 SSL_METHOD *method;
Andy Green3faa9c72010-11-08 17:03:03 +0000517 char ssl_err_buf[512];
518
519 use_ssl = ssl_cert_filepath != NULL && ssl_private_key_filepath != NULL;
520 if (use_ssl)
521 fprintf(stderr, " Compiled with SSL support, using it\n");
522 else
Andy Green018d8eb2010-11-08 21:04:23 +0000523 fprintf(stderr, " Compiled with SSL support, not using it\n");
Andy Green3faa9c72010-11-08 17:03:03 +0000524
525#else
526 if (ssl_cert_filepath != NULL && ssl_private_key_filepath != NULL) {
527 fprintf(stderr, " Not compiled for OpenSSl support!\n");
Andy Greene92cd172011-01-19 13:11:55 +0000528 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +0000529 }
Andy Green018d8eb2010-11-08 21:04:23 +0000530 fprintf(stderr, " Compiled without SSL support, serving unencrypted\n");
Andy Green3faa9c72010-11-08 17:03:03 +0000531#endif
532
533#ifdef LWS_OPENSSL_SUPPORT
534 if (use_ssl) {
535 SSL_library_init();
536
537 OpenSSL_add_all_algorithms();
538 SSL_load_error_strings();
539
Andy Green0ca6a172010-12-19 20:50:01 +0000540 /*
541 * Firefox insists on SSLv23 not SSLv3
542 * Konq disables SSLv2 by default now, SSLv23 works
543 */
Andy Green3faa9c72010-11-08 17:03:03 +0000544
Andy Greenb45993c2010-12-18 15:13:50 +0000545 method = (SSL_METHOD *)SSLv23_server_method();
Andy Green3faa9c72010-11-08 17:03:03 +0000546 if (!method) {
547 fprintf(stderr, "problem creating ssl method: %s\n",
548 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +0000549 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +0000550 }
551 ssl_ctx = SSL_CTX_new(method); /* create context */
552 if (!ssl_ctx) {
553 printf("problem creating ssl context: %s\n",
554 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +0000555 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +0000556 }
557 /* set the local certificate from CertFile */
558 n = SSL_CTX_use_certificate_file(ssl_ctx,
559 ssl_cert_filepath, SSL_FILETYPE_PEM);
560 if (n != 1) {
561 fprintf(stderr, "problem getting cert '%s': %s\n",
562 ssl_cert_filepath,
563 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +0000564 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +0000565 }
566 /* set the private key from KeyFile */
Andy Green018d8eb2010-11-08 21:04:23 +0000567 if (SSL_CTX_use_PrivateKey_file(ssl_ctx,
568 ssl_private_key_filepath,
Andy Green4739e5c2011-01-22 12:51:57 +0000569 SSL_FILETYPE_PEM) != 1) {
Andy Green018d8eb2010-11-08 21:04:23 +0000570 fprintf(stderr, "ssl problem getting key '%s': %s\n",
571 ssl_private_key_filepath,
572 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +0000573 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +0000574 }
575 /* verify private key */
576 if (!SSL_CTX_check_private_key(ssl_ctx)) {
Andy Green018d8eb2010-11-08 21:04:23 +0000577 fprintf(stderr, "Private SSL key doesn't match cert\n");
Andy Greene92cd172011-01-19 13:11:55 +0000578 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +0000579 }
580
581 /* SSL is happy and has a cert it's content with */
582 }
583#endif
Andy Greenb45993c2010-12-18 15:13:50 +0000584
Andy Greendf736162011-01-18 15:39:02 +0000585 /* selftest */
586
587 if (lws_b64_selftest())
Andy Greene92cd172011-01-19 13:11:55 +0000588 return NULL;
Andy Greendf736162011-01-18 15:39:02 +0000589
590
Andy Green8f037e42010-12-19 22:13:26 +0000591 this = malloc(sizeof(struct libwebsocket_context));
Andy Greenb45993c2010-12-18 15:13:50 +0000592
Andy Greene92cd172011-01-19 13:11:55 +0000593 this->protocols = protocols;
Andy Green4739e5c2011-01-22 12:51:57 +0000594 this->listen_port = port;
Andy Greene92cd172011-01-19 13:11:55 +0000595
Andy Greenb45993c2010-12-18 15:13:50 +0000596 /* set up our external listening socket we serve on */
Andy Green8f037e42010-12-19 22:13:26 +0000597
Andy Green4739e5c2011-01-22 12:51:57 +0000598 if (port) {
Andy Green8f037e42010-12-19 22:13:26 +0000599
Andy Green4739e5c2011-01-22 12:51:57 +0000600 sockfd = socket(AF_INET, SOCK_STREAM, 0);
601 if (sockfd < 0) {
602 fprintf(stderr, "ERROR opening socket");
603 return NULL;
604 }
Andy Green775c0dd2010-10-29 14:15:22 +0100605
Andy Green4739e5c2011-01-22 12:51:57 +0000606 /* allow us to restart even if old sockets in TIME_WAIT */
607 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
Andy Greene77ddd82010-11-13 10:03:47 +0000608
Andy Green4739e5c2011-01-22 12:51:57 +0000609 bzero((char *) &serv_addr, sizeof(serv_addr));
610 serv_addr.sin_family = AF_INET;
611 serv_addr.sin_addr.s_addr = INADDR_ANY;
612 serv_addr.sin_port = htons(port);
613
614 n = bind(sockfd, (struct sockaddr *) &serv_addr,
615 sizeof(serv_addr));
616 if (n < 0) {
617 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Green8f037e42010-12-19 22:13:26 +0000618 port, n, errno);
Andy Green4739e5c2011-01-22 12:51:57 +0000619 return NULL;
620 }
Andy Green8f037e42010-12-19 22:13:26 +0000621 }
Andy Greenb45993c2010-12-18 15:13:50 +0000622
Andy Greene77ddd82010-11-13 10:03:47 +0000623 /* drop any root privs for this process */
Andy Green3faa9c72010-11-08 17:03:03 +0000624
625 if (gid != -1)
626 if (setgid(gid))
627 fprintf(stderr, "setgid: %s\n", strerror(errno));
628 if (uid != -1)
629 if (setuid(uid))
630 fprintf(stderr, "setuid: %s\n", strerror(errno));
631
Andy Green8f037e42010-12-19 22:13:26 +0000632 /*
Andy Greenb45993c2010-12-18 15:13:50 +0000633 * prepare the poll() fd array... it's like this
634 *
635 * [0] = external listening socket
636 * [1 .. this->count_protocols] = per-protocol broadcast sockets
637 * [this->count_protocols + 1 ... this->fds_count-1] = connection skts
Andy Green4f3943a2010-11-12 10:44:16 +0000638 */
639
Andy Greenb45993c2010-12-18 15:13:50 +0000640 this->fds_count = 1;
641 this->fds[0].fd = sockfd;
642 this->fds[0].events = POLLIN;
643 this->count_protocols = 0;
644#ifdef LWS_OPENSSL_SUPPORT
645 this->use_ssl = use_ssl;
646#endif
647
Andy Green4739e5c2011-01-22 12:51:57 +0000648 if (port) {
649 listen(sockfd, 5);
650 fprintf(stderr, " Listening on port %d\n", port);
651 }
Andy Greenb45993c2010-12-18 15:13:50 +0000652
653 /* set up our internal broadcast trigger sockets per-protocol */
654
655 for (; protocols[this->count_protocols].callback;
656 this->count_protocols++) {
657 protocols[this->count_protocols].owning_server = this;
658 protocols[this->count_protocols].protocol_index =
659 this->count_protocols;
660
661 fd = socket(AF_INET, SOCK_STREAM, 0);
662 if (fd < 0) {
663 fprintf(stderr, "ERROR opening socket");
Andy Greene92cd172011-01-19 13:11:55 +0000664 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +0000665 }
Andy Green8f037e42010-12-19 22:13:26 +0000666
Andy Greenb45993c2010-12-18 15:13:50 +0000667 /* allow us to restart even if old sockets in TIME_WAIT */
668 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
669
670 bzero((char *) &serv_addr, sizeof(serv_addr));
671 serv_addr.sin_family = AF_INET;
672 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
673 serv_addr.sin_port = 0; /* pick the port for us */
674
675 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
676 if (n < 0) {
Andy Green8f037e42010-12-19 22:13:26 +0000677 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Greenb45993c2010-12-18 15:13:50 +0000678 port, n, errno);
Andy Greene92cd172011-01-19 13:11:55 +0000679 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +0000680 }
681
682 slen = sizeof cli_addr;
683 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
684 if (n < 0) {
685 fprintf(stderr, "getsockname failed\n");
Andy Greene92cd172011-01-19 13:11:55 +0000686 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +0000687 }
688 protocols[this->count_protocols].broadcast_socket_port =
689 ntohs(cli_addr.sin_port);
690 listen(fd, 5);
691
692 debug(" Protocol %s broadcast socket %d\n",
693 protocols[this->count_protocols].name,
694 ntohs(cli_addr.sin_port));
695
696 this->fds[this->fds_count].fd = fd;
697 this->fds[this->fds_count].events = POLLIN;
698 /* wsi only exists for connections, not broadcast listener */
699 this->wsi[this->fds_count] = NULL;
700 this->fds_count++;
701 }
702
Andy Greene92cd172011-01-19 13:11:55 +0000703 return this;
704}
Andy Greenb45993c2010-12-18 15:13:50 +0000705
Andy Green4739e5c2011-01-22 12:51:57 +0000706
Andy Greened11a022011-01-20 10:23:50 +0000707#ifndef LWS_NO_FORK
708
Andy Greene92cd172011-01-19 13:11:55 +0000709/**
710 * libwebsockets_fork_service_loop() - Optional helper function forks off
711 * a process for the websocket server loop.
Andy Green6964bb52011-01-23 16:50:33 +0000712 * You don't have to use this but if not, you
713 * have to make sure you are calling
714 * libwebsocket_service periodically to service
715 * the websocket traffic
Andy Greene92cd172011-01-19 13:11:55 +0000716 * @this: server context returned by creation function
717 */
Andy Greenb45993c2010-12-18 15:13:50 +0000718
Andy Greene92cd172011-01-19 13:11:55 +0000719int
720libwebsockets_fork_service_loop(struct libwebsocket_context *this)
721{
722 int client;
723 int fd;
724 struct sockaddr_in cli_addr;
725 int n;
Andy Greenb45993c2010-12-18 15:13:50 +0000726
Andy Greened11a022011-01-20 10:23:50 +0000727 n = fork();
728 if (n < 0)
729 return n;
730
731 if (!n) {
732
733 /* main process context */
734
735 for (client = 1; client < this->count_protocols + 1; client++) {
736 fd = socket(AF_INET, SOCK_STREAM, 0);
737 if (fd < 0) {
738 fprintf(stderr, "Unable to create socket\n");
739 return -1;
740 }
741 cli_addr.sin_family = AF_INET;
742 cli_addr.sin_port = htons(
Andy Green4739e5c2011-01-22 12:51:57 +0000743 this->protocols[client - 1].broadcast_socket_port);
Andy Greened11a022011-01-20 10:23:50 +0000744 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
745 n = connect(fd, (struct sockaddr *)&cli_addr,
746 sizeof cli_addr);
747 if (n < 0) {
748 fprintf(stderr, "Unable to connect to "
749 "broadcast socket %d, %s\n",
750 client, strerror(errno));
751 return -1;
752 }
753
Andy Green4739e5c2011-01-22 12:51:57 +0000754 this->protocols[client - 1].broadcast_socket_user_fd =
755 fd;
Andy Greened11a022011-01-20 10:23:50 +0000756 }
757
758
Andy Greene92cd172011-01-19 13:11:55 +0000759 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +0000760 }
761
762 /* we want a SIGHUP when our parent goes down */
763 prctl(PR_SET_PDEATHSIG, SIGHUP);
764
765 /* in this forked process, sit and service websocket connections */
Andy Green8f037e42010-12-19 22:13:26 +0000766
Andy Greene92cd172011-01-19 13:11:55 +0000767 while (1)
768 if (libwebsocket_service(this, 1000))
769 return -1;
Andy Green8f037e42010-12-19 22:13:26 +0000770
Andy Green251f6fa2010-11-03 11:13:06 +0000771 return 0;
Andy Greenff95d7a2010-10-28 22:36:01 +0100772}
773
Andy Greened11a022011-01-20 10:23:50 +0000774#endif
775
Andy Greenb45993c2010-12-18 15:13:50 +0000776/**
777 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
Andy Green8f037e42010-12-19 22:13:26 +0000778 * connection.
Andy Greenb45993c2010-12-18 15:13:50 +0000779 * @wsi: pointer to struct websocket you want to know the protocol of
780 *
Andy Green8f037e42010-12-19 22:13:26 +0000781 *
782 * This is useful to get the protocol to broadcast back to from inside
Andy Greenb45993c2010-12-18 15:13:50 +0000783 * the callback.
784 */
Andy Greenab990e42010-10-31 12:42:52 +0000785
Andy Greenb45993c2010-12-18 15:13:50 +0000786const struct libwebsocket_protocols *
787libwebsockets_get_protocol(struct libwebsocket *wsi)
788{
789 return wsi->protocol;
790}
791
792/**
Andy Greene92cd172011-01-19 13:11:55 +0000793 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
Andy Green8f037e42010-12-19 22:13:26 +0000794 * connections of the given protocol.
Andy Greenb45993c2010-12-18 15:13:50 +0000795 * @protocol: pointer to the protocol you will broadcast to all members of
796 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
Andy Green8f037e42010-12-19 22:13:26 +0000797 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
798 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
799 * case you are calling this function from callback context.
Andy Greenb45993c2010-12-18 15:13:50 +0000800 * @len: length of payload data in buf, starting from buf.
Andy Green8f037e42010-12-19 22:13:26 +0000801 *
802 * This function allows bulk sending of a packet to every connection using
Andy Greenb45993c2010-12-18 15:13:50 +0000803 * the given protocol. It does not send the data directly; instead it calls
804 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
805 * wants to actually send the data for that connection, the callback itself
806 * should call libwebsocket_write().
807 *
808 * libwebsockets_broadcast() can be called from another fork context without
809 * having to take any care about data visibility between the processes, it'll
810 * "just work".
811 */
812
813
814int
Andy Green8f037e42010-12-19 22:13:26 +0000815libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
Andy Greenb45993c2010-12-18 15:13:50 +0000816 unsigned char *buf, size_t len)
817{
Andy Green8f037e42010-12-19 22:13:26 +0000818 struct libwebsocket_context *this = protocol->owning_server;
Andy Greenb45993c2010-12-18 15:13:50 +0000819 int n;
820
821 if (!protocol->broadcast_socket_user_fd) {
822 /*
Andy Greene92cd172011-01-19 13:11:55 +0000823 * We are either running unforked / flat, or we are being
824 * called from poll thread context
Andy Greenb45993c2010-12-18 15:13:50 +0000825 * eg, from a callback. In that case don't use sockets for
826 * broadcast IPC (since we can't open a socket connection to
827 * a socket listening on our own thread) but directly do the
828 * send action.
829 *
830 * Locking is not needed because we are by definition being
831 * called in the poll thread context and are serialized.
832 */
833
834 for (n = this->count_protocols + 1; n < this->fds_count; n++) {
835
836 if ((unsigned long)this->wsi[n] < LWS_MAX_PROTOCOLS)
837 continue;
838
839 /* never broadcast to non-established connection */
Andy Greenb45993c2010-12-18 15:13:50 +0000840 if (this->wsi[n]->state != WSI_STATE_ESTABLISHED)
841 continue;
842
843 /* only broadcast to guys using requested protocol */
Andy Greenb45993c2010-12-18 15:13:50 +0000844 if (this->wsi[n]->protocol != protocol)
845 continue;
846
Andy Green8f037e42010-12-19 22:13:26 +0000847 this->wsi[n]->protocol->callback(this->wsi[n],
848 LWS_CALLBACK_BROADCAST,
Andy Greenb45993c2010-12-18 15:13:50 +0000849 this->wsi[n]->user_space,
850 buf, len);
851 }
852
853 return 0;
854 }
855
Andy Green0ca6a172010-12-19 20:50:01 +0000856 /*
857 * We're being called from a different process context than the server
858 * loop. Instead of broadcasting directly, we send our
859 * payload on a socket to do the IPC; the server process will serialize
860 * the broadcast action in its main poll() loop.
861 *
862 * There's one broadcast socket listening for each protocol supported
863 * set up when the websocket server initializes
864 */
865
Andy Green6964bb52011-01-23 16:50:33 +0000866 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
Andy Greenb45993c2010-12-18 15:13:50 +0000867
868 return n;
869}