blob: bfc56153612ebe0efbab2e5ca1106c79eef07cb5 [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
3 *
4 * 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 Green3faa9c72010-11-08 17:03:03 +000029
Andy Green7c212cc2010-11-08 20:20:42 +000030extern int
Andy Green251f6fa2010-11-03 11:13:06 +000031libwebsocket_read(struct libwebsocket *wsi, unsigned char * buf, size_t len);
Andy Greenff95d7a2010-10-28 22:36:01 +010032
Andy Green775c0dd2010-10-29 14:15:22 +010033
Andy Green4f3943a2010-11-12 10:44:16 +000034/* document the generic callback (it's a fake prototype under this) */
35/**
36 * callback() - User server actions
37 * @wsi: Opaque websocket instance pointer
38 * @reason: The reason for the call
39 * @user: Pointer to per-session user data allocated by library
40 * @in: Pointer used for some callback reasons
41 * @len: Length set for some callback reasons
42 *
43 * This callback is the way the user controls what is served. All the
44 * protocol detail is hidden and handled by the library.
45 *
46 * For each connection / session there is user data allocated that is
47 * pointed to by "user". You set the size of this user data area when
48 * the library is initialized with libwebsocket_create_server.
49 *
50 * You get an opportunity to initialize user data when called back with
51 * LWS_CALLBACK_ESTABLISHED reason.
52 *
53 * LWS_CALLBACK_ESTABLISHED: after successful websocket handshake
54 *
55 * LWS_CALLBACK_CLOSED: when the websocket session ends
56 *
Andy Greenb45993c2010-12-18 15:13:50 +000057 * LWS_CALLBACK_BROADCAST: signal to send to client (you would use
Andy Green4f3943a2010-11-12 10:44:16 +000058 * libwebsocket_write() taking care about the
59 * special buffer requirements
60 * LWS_CALLBACK_RECEIVE: data has appeared for the server, it can be
61 * found at *in and is len bytes long
62 *
63 * LWS_CALLBACK_HTTP: an http request has come from a client that is not
64 * asking to upgrade the connection to a websocket
65 * one. This is a chance to serve http content,
66 * for example, to send a script to the client
67 * which will then open the websockets connection.
68 * @in points to the URI path requested and
69 * libwebsockets_serve_http_file() makes it very
70 * simple to send back a file to the client.
71 */
72extern int callback(struct libwebsocket * wsi,
73 enum libwebsocket_callback_reasons reason, void * user,
74 void *in, size_t len);
75
Andy Green775c0dd2010-10-29 14:15:22 +010076
Andy Green7c212cc2010-11-08 20:20:42 +000077void
Andy Green251f6fa2010-11-03 11:13:06 +000078libwebsocket_close_and_free_session(struct libwebsocket *wsi)
79{
Andy Greenb45993c2010-12-18 15:13:50 +000080 int n;
81
82 if ((unsigned long)wsi < LWS_MAX_PROTOCOLS)
83 return;
84
85 n = wsi->state;
Andy Green251f6fa2010-11-03 11:13:06 +000086
87 wsi->state = WSI_STATE_DEAD_SOCKET;
88
Andy Green4f3943a2010-11-12 10:44:16 +000089 if (wsi->protocol->callback && n == WSI_STATE_ESTABLISHED)
Andy Greene77ddd82010-11-13 10:03:47 +000090 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
91 wsi->user_space, NULL, 0);
Andy Green251f6fa2010-11-03 11:13:06 +000092
93 for (n = 0; n < WSI_TOKEN_COUNT; n++)
94 if (wsi->utf8_token[n].token)
95 free(wsi->utf8_token[n].token);
96
97// fprintf(stderr, "closing fd=%d\n", wsi->sock);
98
Andy Green3faa9c72010-11-08 17:03:03 +000099#ifdef LWS_OPENSSL_SUPPORT
100 if (use_ssl) {
101 n = SSL_get_fd(wsi->ssl);
102 SSL_shutdown(wsi->ssl);
103 close(n);
104 SSL_free(wsi->ssl);
105 } else {
106#endif
107 shutdown(wsi->sock, SHUT_RDWR);
108 close(wsi->sock);
109#ifdef LWS_OPENSSL_SUPPORT
110 }
111#endif
Andy Green4f3943a2010-11-12 10:44:16 +0000112 if (wsi->user_space)
113 free(wsi->user_space);
114
Andy Green251f6fa2010-11-03 11:13:06 +0000115 free(wsi);
116}
117
Andy Greenb45993c2010-12-18 15:13:50 +0000118static int
119libwebsocket_poll_connections(struct libwebsocket_context *this)
120{
121 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
122 LWS_SEND_BUFFER_POST_PADDING];
123 int client;
124 int n;
125 size_t len;
126
127 /* check for activity on client sockets */
128
129 for (client = this->count_protocols + 1; client < this->fds_count;
130 client++) {
131
132 /* handle session socket closed */
133
134 if (this->fds[client].revents & (POLLERR | POLLHUP)) {
135
136 debug("Session Socket %d %p (fd=%d) dead\n",
137 client, this->wsi[client], this->fds[client]);
138
139 libwebsocket_close_and_free_session(this->wsi[client]);
140 goto nuke_this;
141 }
142
143 /* any incoming data ready? */
144
145 if (!(this->fds[client].revents & POLLIN))
146 continue;
147
148 /* broadcast? */
149
150 if ((unsigned long)this->wsi[client] < LWS_MAX_PROTOCOLS) {
151
152 len = read(this->fds[client].fd,
153 buf + LWS_SEND_BUFFER_PRE_PADDING,
154 MAX_BROADCAST_PAYLOAD);
155 if (len < 0) {
156 fprintf(stderr, "Error receiving broadcast payload\n");
157 continue;
158 }
159
160 /* broadcast it to all guys with this protocol index */
161
162 for (n = this->count_protocols + 1;
163 n < this->fds_count; n++) {
164
165 if ((unsigned long)this->wsi[n] <
166 LWS_MAX_PROTOCOLS)
167 continue;
168
169 /*
170 * never broadcast to non-established
171 * connection
172 */
173
174 if (this->wsi[n]->state != WSI_STATE_ESTABLISHED)
175 continue;
176
177 /*
178 * only broadcast to connections using
179 * the requested protocol
180 */
181
182 if (this->wsi[n]->protocol->protocol_index !=
183 (unsigned long)this->wsi[client])
184 continue;
185
186 this->wsi[n]->protocol-> callback(this->wsi[n],
187 LWS_CALLBACK_BROADCAST,
188 this->wsi[n]->user_space,
189 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
190 }
191
192 continue;
193 }
194
195#ifdef LWS_OPENSSL_SUPPORT
196 if (this->use_ssl)
197 n = SSL_read(this->wsi[client]->ssl, buf, sizeof buf);
198 else
199#endif
200 n = recv(this->fds[client].fd, buf, sizeof buf, 0);
201
202 if (n < 0) {
203 fprintf(stderr, "Socket read returned %d\n", n);
204 continue;
205 }
206 if (!n) {
207// fprintf(stderr, "POLLIN with 0 len waiting\n");
208 libwebsocket_close_and_free_session(
209 this->wsi[client]);
210 goto nuke_this;
211 }
212
213
214 /* service incoming data */
215
216 if (libwebsocket_read(this->wsi[client], buf, n) >= 0)
217 continue;
218
219 /*
220 * it closed and nuked wsi[client], so remove the
221 * socket handle and wsi from our service list
222 */
223nuke_this:
224
225 debug("nuking wsi %p, fsd_count = %d\n",
226 this->wsi[client], this->fds_count - 1);
227
228 this->fds_count--;
229 for (n = client; n < this->fds_count; n++) {
230 this->fds[n] = this->fds[n + 1];
231 this->wsi[n] = this->wsi[n + 1];
232 }
233 break;
234 }
235
236 return 0;
237}
238
239
240
Andy Greenab990e42010-10-31 12:42:52 +0000241/**
242 * libwebsocket_create_server() - Create the listening websockets server
243 * @port: Port to listen on
Andy Green4f3943a2010-11-12 10:44:16 +0000244 * @protocols: Array of structures listing supported protocols and a protocol-
245 * specific callback for each one. The list is ended with an
246 * entry that has a NULL callback pointer.
Andy Greenb45993c2010-12-18 15:13:50 +0000247 * It's not const because we write the owning_server member
Andy Green3faa9c72010-11-08 17:03:03 +0000248 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
249 * to listen using SSL, set to the filepath to fetch the
250 * server cert from, otherwise NULL for unencrypted
251 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
252 * else ignored
253 * @gid: group id to change to after setting listen socket, or -1.
254 * @uid: user id to change to after setting listen socket, or -1.
Andy Greenab990e42010-10-31 12:42:52 +0000255 *
Andy Green05464c62010-11-12 10:44:18 +0000256 * This function creates the listening socket and takes care
Andy Greenab990e42010-10-31 12:42:52 +0000257 * of all initialization in one step.
Andy Green05464c62010-11-12 10:44:18 +0000258 *
Andy Greenb45993c2010-12-18 15:13:50 +0000259 * After initialization, it forks a thread that will sits in a service loop
260 * and returns to the caller. The actual service actions are performed by
261 * user code in a per-protocol callback from the appropriate one selected
262 * by the client from the list in @protocols.
Andy Greenab990e42010-10-31 12:42:52 +0000263 *
Andy Green05464c62010-11-12 10:44:18 +0000264 * The protocol callback functions are called for a handful of events
265 * including http requests coming in, websocket connections becoming
Andy Greenab990e42010-10-31 12:42:52 +0000266 * established, and data arriving; it's also called periodically to allow
267 * async transmission.
Andy Green05464c62010-11-12 10:44:18 +0000268 *
269 * HTTP requests are sent always to the FIRST protocol in @protocol, since
270 * at that time websocket protocol has not been negotiated. Other
271 * protocols after the first one never see any HTTP callack activity.
Andy Greenab990e42010-10-31 12:42:52 +0000272 *
273 * The server created is a simple http server by default; part of the
274 * websocket standard is upgrading this http connection to a websocket one.
275 *
276 * This allows the same server to provide files like scripts and favicon /
277 * images or whatever over http and dynamic data over websockets all in
278 * one place; they're all handled in the user callback.
279 */
Andy Green4ea60062010-10-30 12:15:07 +0100280
Andy Greenea71ed12010-10-31 07:40:33 +0000281int libwebsocket_create_server(int port,
Andy Greenb45993c2010-12-18 15:13:50 +0000282 struct libwebsocket_protocols *protocols,
Andy Greence510c62010-11-11 12:48:13 +0000283 const char * ssl_cert_filepath,
284 const char * ssl_private_key_filepath,
285 int gid, int uid)
Andy Greenff95d7a2010-10-28 22:36:01 +0100286{
287 int n;
Andy Green251f6fa2010-11-03 11:13:06 +0000288 int client;
Andy Green69fa0722010-11-03 08:25:13 +0000289 int sockfd;
Andy Green251f6fa2010-11-03 11:13:06 +0000290 int fd;
Andy Greenff95d7a2010-10-28 22:36:01 +0100291 unsigned int clilen;
292 struct sockaddr_in serv_addr, cli_addr;
Andy Green251f6fa2010-11-03 11:13:06 +0000293 int opt = 1;
Andy Greenb45993c2010-12-18 15:13:50 +0000294 struct libwebsocket_context * this = NULL;
295 unsigned int slen;
Andy Greenff95d7a2010-10-28 22:36:01 +0100296
Andy Green3faa9c72010-11-08 17:03:03 +0000297#ifdef LWS_OPENSSL_SUPPORT
Andy Greenf2f54d52010-11-15 22:08:00 +0000298 SSL_METHOD *method;
Andy Green3faa9c72010-11-08 17:03:03 +0000299 char ssl_err_buf[512];
300
301 use_ssl = ssl_cert_filepath != NULL && ssl_private_key_filepath != NULL;
302 if (use_ssl)
303 fprintf(stderr, " Compiled with SSL support, using it\n");
304 else
Andy Green018d8eb2010-11-08 21:04:23 +0000305 fprintf(stderr, " Compiled with SSL support, not using it\n");
Andy Green3faa9c72010-11-08 17:03:03 +0000306
307#else
308 if (ssl_cert_filepath != NULL && ssl_private_key_filepath != NULL) {
309 fprintf(stderr, " Not compiled for OpenSSl support!\n");
310 return -1;
311 }
Andy Green018d8eb2010-11-08 21:04:23 +0000312 fprintf(stderr, " Compiled without SSL support, serving unencrypted\n");
Andy Green3faa9c72010-11-08 17:03:03 +0000313#endif
314
315#ifdef LWS_OPENSSL_SUPPORT
316 if (use_ssl) {
317 SSL_library_init();
318
319 OpenSSL_add_all_algorithms();
320 SSL_load_error_strings();
321
322 // Firefox insists on SSLv23 not SSLv3
323 // Konq disables SSLv2 by default now, SSLv23 works
324
Andy Greenb45993c2010-12-18 15:13:50 +0000325 method = (SSL_METHOD *)SSLv23_server_method();
Andy Green3faa9c72010-11-08 17:03:03 +0000326 if (!method) {
327 fprintf(stderr, "problem creating ssl method: %s\n",
328 ERR_error_string(ERR_get_error(), ssl_err_buf));
329 return -1;
330 }
331 ssl_ctx = SSL_CTX_new(method); /* create context */
332 if (!ssl_ctx) {
333 printf("problem creating ssl context: %s\n",
334 ERR_error_string(ERR_get_error(), ssl_err_buf));
335 return -1;
336 }
337 /* set the local certificate from CertFile */
338 n = SSL_CTX_use_certificate_file(ssl_ctx,
339 ssl_cert_filepath, SSL_FILETYPE_PEM);
340 if (n != 1) {
341 fprintf(stderr, "problem getting cert '%s': %s\n",
342 ssl_cert_filepath,
343 ERR_error_string(ERR_get_error(), ssl_err_buf));
344 return -1;
345 }
346 /* set the private key from KeyFile */
Andy Green018d8eb2010-11-08 21:04:23 +0000347 if (SSL_CTX_use_PrivateKey_file(ssl_ctx,
348 ssl_private_key_filepath,
349 SSL_FILETYPE_PEM) != 1) {
350 fprintf(stderr, "ssl problem getting key '%s': %s\n",
351 ssl_private_key_filepath,
352 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Green3faa9c72010-11-08 17:03:03 +0000353 return (-1);
354 }
355 /* verify private key */
356 if (!SSL_CTX_check_private_key(ssl_ctx)) {
Andy Green018d8eb2010-11-08 21:04:23 +0000357 fprintf(stderr, "Private SSL key doesn't match cert\n");
Andy Green3faa9c72010-11-08 17:03:03 +0000358 return (-1);
359 }
360
361 /* SSL is happy and has a cert it's content with */
362 }
363#endif
Andy Greenb45993c2010-12-18 15:13:50 +0000364
365 this = malloc(sizeof (struct libwebsocket_context));
366
367 /* set up our external listening socket we serve on */
Andy Green4f3943a2010-11-12 10:44:16 +0000368
Andy Green775c0dd2010-10-29 14:15:22 +0100369 sockfd = socket(AF_INET, SOCK_STREAM, 0);
370 if (sockfd < 0) {
371 fprintf(stderr, "ERROR opening socket");
Andy Green251f6fa2010-11-03 11:13:06 +0000372 return -1;
Andy Green775c0dd2010-10-29 14:15:22 +0100373 }
Andy Green251f6fa2010-11-03 11:13:06 +0000374
375 /* allow us to restart even if old sockets in TIME_WAIT */
376 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
Andy Green775c0dd2010-10-29 14:15:22 +0100377
Andy Green251f6fa2010-11-03 11:13:06 +0000378 bzero((char *) &serv_addr, sizeof(serv_addr));
Andy Green775c0dd2010-10-29 14:15:22 +0100379 serv_addr.sin_family = AF_INET;
380 serv_addr.sin_addr.s_addr = INADDR_ANY;
381 serv_addr.sin_port = htons(port);
Andy Greene77ddd82010-11-13 10:03:47 +0000382
Andy Green775c0dd2010-10-29 14:15:22 +0100383 n = bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
384 if (n < 0) {
Andy Greenea71ed12010-10-31 07:40:33 +0000385 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n", port, n,
386 errno);
Andy Green775c0dd2010-10-29 14:15:22 +0100387 return -1;
388 }
Andy Greenb45993c2010-12-18 15:13:50 +0000389
Andy Greene77ddd82010-11-13 10:03:47 +0000390 /* drop any root privs for this process */
Andy Green3faa9c72010-11-08 17:03:03 +0000391
392 if (gid != -1)
393 if (setgid(gid))
394 fprintf(stderr, "setgid: %s\n", strerror(errno));
395 if (uid != -1)
396 if (setuid(uid))
397 fprintf(stderr, "setuid: %s\n", strerror(errno));
398
Andy Green4f3943a2010-11-12 10:44:16 +0000399 /*
Andy Greenb45993c2010-12-18 15:13:50 +0000400 * prepare the poll() fd array... it's like this
401 *
402 * [0] = external listening socket
403 * [1 .. this->count_protocols] = per-protocol broadcast sockets
404 * [this->count_protocols + 1 ... this->fds_count-1] = connection skts
Andy Green4f3943a2010-11-12 10:44:16 +0000405 */
406
Andy Greenb45993c2010-12-18 15:13:50 +0000407 this->fds_count = 1;
408 this->fds[0].fd = sockfd;
409 this->fds[0].events = POLLIN;
410 this->count_protocols = 0;
411#ifdef LWS_OPENSSL_SUPPORT
412 this->use_ssl = use_ssl;
413#endif
414
Andy Greenff95d7a2010-10-28 22:36:01 +0100415 listen(sockfd, 5);
Andy Green251f6fa2010-11-03 11:13:06 +0000416 fprintf(stderr, " Listening on port %d\n", port);
Andy Greenb45993c2010-12-18 15:13:50 +0000417
418 /* set up our internal broadcast trigger sockets per-protocol */
419
420 for (; protocols[this->count_protocols].callback;
421 this->count_protocols++) {
422 protocols[this->count_protocols].owning_server = this;
423 protocols[this->count_protocols].protocol_index =
424 this->count_protocols;
425
426 fd = socket(AF_INET, SOCK_STREAM, 0);
427 if (fd < 0) {
428 fprintf(stderr, "ERROR opening socket");
429 return -1;
430 }
431
432 /* allow us to restart even if old sockets in TIME_WAIT */
433 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
434
435 bzero((char *) &serv_addr, sizeof(serv_addr));
436 serv_addr.sin_family = AF_INET;
437 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
438 serv_addr.sin_port = 0; /* pick the port for us */
439
440 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
441 if (n < 0) {
442 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
443 port, n, errno);
444 return -1;
445 }
446
447 slen = sizeof cli_addr;
448 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
449 if (n < 0) {
450 fprintf(stderr, "getsockname failed\n");
451 return -1;
452 }
453 protocols[this->count_protocols].broadcast_socket_port =
454 ntohs(cli_addr.sin_port);
455 listen(fd, 5);
456
457 debug(" Protocol %s broadcast socket %d\n",
458 protocols[this->count_protocols].name,
459 ntohs(cli_addr.sin_port));
460
461 this->fds[this->fds_count].fd = fd;
462 this->fds[this->fds_count].events = POLLIN;
463 /* wsi only exists for connections, not broadcast listener */
464 this->wsi[this->fds_count] = NULL;
465 this->fds_count++;
466 }
467
468
469 /*
470 * We will enter out poll and service loop now, just before that
471 * fork and return to caller for the main thread of execution
472 */
473
474 n = fork();
475 if (n < 0) {
476 fprintf(stderr, "Failed to fork websocket poll loop\n");
477 return -1;
478 }
479 if (n) {
480 /* original process context */
481
482 /*
483 * before we return to caller, we set up per-protocol
484 * broadcast sockets connected to the server ready to use
485 */
486
487 /* give server fork a chance to start up */
488 sleep(1);
489
490 for (client = 1; client < this->count_protocols + 1; client++) {
491 fd = socket(AF_INET, SOCK_STREAM, 0);
492 if (fd < 0) {
493 fprintf(stderr,"Unable to create socket\n");
494 return -1;
495 }
496 cli_addr.sin_family = AF_INET;
497 cli_addr.sin_port = htons(
498 protocols[client - 1].broadcast_socket_port);
499 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
500 n = connect(fd, (struct sockaddr *)&cli_addr,
501 sizeof cli_addr);
502 if (n < 0) {
503 fprintf(stderr, "Unable to connect to "
504 "broadcast socket %d, %s\n",
505 client, strerror(errno));
506 return -1;
507 }
508
509 protocols[client - 1].broadcast_socket_user_fd = fd;
510 }
511
512 fprintf(stderr, "libwebsocket poll process forked\n");
513
514 return 0;
515 }
516
517 /* we want a SIGHUP when our parent goes down */
518 prctl(PR_SET_PDEATHSIG, SIGHUP);
519
520 /* in this forked process, sit and service websocket connections */
Andy Greenff95d7a2010-10-28 22:36:01 +0100521
522 while (1) {
Andy Greenff95d7a2010-10-28 22:36:01 +0100523
Andy Greenb45993c2010-12-18 15:13:50 +0000524 n = poll(this->fds, this->fds_count, 1000);
525
526 if (n < 0 || this->fds[0].revents & (POLLERR | POLLHUP)) {
Andy Green85ba32f2010-11-12 11:47:39 +0000527 fprintf(stderr, "Listen Socket dead\n");
Andy Green251f6fa2010-11-03 11:13:06 +0000528 goto fatal;
Andy Green775c0dd2010-10-29 14:15:22 +0100529 }
Andy Green251f6fa2010-11-03 11:13:06 +0000530 if (n == 0) /* poll timeout */
Andy Greenb45993c2010-12-18 15:13:50 +0000531 continue;
Andy Green251f6fa2010-11-03 11:13:06 +0000532
Andy Greenb45993c2010-12-18 15:13:50 +0000533 /* handle accept on listening socket? */
534
535 for (client = 0; client < this->count_protocols + 1; client++) {
536
537 if (!this->fds[client].revents & POLLIN)
538 continue;
Andy Green251f6fa2010-11-03 11:13:06 +0000539
Andy Green3faa9c72010-11-08 17:03:03 +0000540 /* listen socket got an unencrypted connection... */
541
Andy Green251f6fa2010-11-03 11:13:06 +0000542 clilen = sizeof(cli_addr);
Andy Greenb45993c2010-12-18 15:13:50 +0000543 fd = accept(this->fds[client].fd,
544 (struct sockaddr *)&cli_addr, &clilen);
Andy Green251f6fa2010-11-03 11:13:06 +0000545 if (fd < 0) {
546 fprintf(stderr, "ERROR on accept");
547 continue;
548 }
Andy Green3faa9c72010-11-08 17:03:03 +0000549
Andy Greenb45993c2010-12-18 15:13:50 +0000550 if (this->fds_count >= MAX_CLIENTS) {
Andy Green251f6fa2010-11-03 11:13:06 +0000551 fprintf(stderr, "too busy");
552 close(fd);
553 continue;
554 }
Andy Green3faa9c72010-11-08 17:03:03 +0000555
Andy Greenb45993c2010-12-18 15:13:50 +0000556 if (client) {
557 /*
558 * accepting a connection to broadcast socket
559 * set wsi to be protocol index not pointer
560 */
561
562 this->wsi[this->fds_count] =
563 (struct libwebsocket *)(long)(client - 1);
564
565 goto fill_in_fds;
566 }
567
568 /* accepting connection to main listener */
569
570 this->wsi[this->fds_count] =
571 malloc(sizeof(struct libwebsocket));
572 if (!this->wsi[this->fds_count])
Andy Green251f6fa2010-11-03 11:13:06 +0000573 return -1;
Andy Green3faa9c72010-11-08 17:03:03 +0000574
Andy Greenb45993c2010-12-18 15:13:50 +0000575 #ifdef LWS_OPENSSL_SUPPORT
576 if (this->use_ssl) {
Andy Green3faa9c72010-11-08 17:03:03 +0000577
Andy Greenb45993c2010-12-18 15:13:50 +0000578 this->wsi[this->fds_count]->ssl =
579 SSL_new(ssl_ctx);
580 if (this->wsi[this->fds_count]->ssl == NULL) {
Andy Green3faa9c72010-11-08 17:03:03 +0000581 fprintf(stderr, "SSL_new failed: %s\n",
Andy Green018d8eb2010-11-08 21:04:23 +0000582 ERR_error_string(SSL_get_error(
Andy Greenb45993c2010-12-18 15:13:50 +0000583 this->wsi[this->fds_count]->ssl, 0),
584 NULL));
585 free(this->wsi[this->fds_count]);
Andy Green3faa9c72010-11-08 17:03:03 +0000586 continue;
587 }
588
Andy Greenb45993c2010-12-18 15:13:50 +0000589 SSL_set_fd(this->wsi[this->fds_count]->ssl, fd);
Andy Green3faa9c72010-11-08 17:03:03 +0000590
Andy Greenb45993c2010-12-18 15:13:50 +0000591 n = SSL_accept(this->wsi[this->fds_count]->ssl);
Andy Green3faa9c72010-11-08 17:03:03 +0000592 if (n != 1) {
Andy Green018d8eb2010-11-08 21:04:23 +0000593 /*
594 * browsers seem to probe with various
595 * ssl params which fail then retry
596 * and succeed
597 */
598 debug("SSL_accept failed skt %u: %s\n",
Andy Greenb45993c2010-12-18 15:13:50 +0000599 fd,
600 ERR_error_string(SSL_get_error(
601 this->wsi[this->fds_count]->ssl,
602 n), NULL));
603 SSL_free(
604 this->wsi[this->fds_count]->ssl);
605 free(this->wsi[this->fds_count]);
Andy Green3faa9c72010-11-08 17:03:03 +0000606 continue;
607 }
Andy Green018d8eb2010-11-08 21:04:23 +0000608 debug("accepted new SSL conn "
609 "port %u on fd=%d SSL ver %s\n",
610 ntohs(cli_addr.sin_port), fd,
Andy Greenb45993c2010-12-18 15:13:50 +0000611 SSL_get_version(this->wsi[
612 this->fds_count]->ssl));
Andy Green3faa9c72010-11-08 17:03:03 +0000613
Andy Green4f3943a2010-11-12 10:44:16 +0000614 } else
Andy Greenb45993c2010-12-18 15:13:50 +0000615 #endif
Andy Green4f3943a2010-11-12 10:44:16 +0000616 debug("accepted new conn port %u on fd=%d\n",
617 ntohs(cli_addr.sin_port), fd);
Andy Greenb45993c2010-12-18 15:13:50 +0000618
Andy Green3faa9c72010-11-08 17:03:03 +0000619 /* intialize the instance struct */
620
Andy Greenb45993c2010-12-18 15:13:50 +0000621 this->wsi[this->fds_count]->sock = fd;
622 this->wsi[this->fds_count]->state = WSI_STATE_HTTP;
623 this->wsi[this->fds_count]->name_buffer_pos = 0;
Andy Green251f6fa2010-11-03 11:13:06 +0000624
625 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
Andy Greenb45993c2010-12-18 15:13:50 +0000626 this->wsi[this->fds_count]->
627 utf8_token[n].token = NULL;
628 this->wsi[this->fds_count]->
629 utf8_token[n].token_len = 0;
Andy Green251f6fa2010-11-03 11:13:06 +0000630 }
631
Andy Green4f3943a2010-11-12 10:44:16 +0000632 /*
633 * these can only be set once the protocol is known
634 * we set an unestablished connection's protocol pointer
635 * to the start of the supported list, so it can look
636 * for matching ones during the handshake
637 */
Andy Greenb45993c2010-12-18 15:13:50 +0000638 this->wsi[this->fds_count]->protocol = protocols;
639 this->wsi[this->fds_count]->user_space = NULL;
Andy Green4f3943a2010-11-12 10:44:16 +0000640
Andy Greence510c62010-11-11 12:48:13 +0000641 /*
642 * Default protocol is 76
643 * After 76, there's a header specified to inform which
Andy Green4f3943a2010-11-12 10:44:16 +0000644 * draft the client wants, when that's seen we modify
645 * the individual connection's spec revision accordingly
Andy Greence510c62010-11-11 12:48:13 +0000646 */
Andy Greenb45993c2010-12-18 15:13:50 +0000647 this->wsi[this->fds_count]->ietf_spec_revision = 76;
Andy Green251f6fa2010-11-03 11:13:06 +0000648
Andy Greenb45993c2010-12-18 15:13:50 +0000649fill_in_fds:
Andy Green85ba32f2010-11-12 11:47:39 +0000650
651 /*
652 * make sure NO events are seen yet on this new socket
653 * (otherwise we inherit old fds[client].revents from
654 * previous socket there and die mysteriously! )
655 */
Andy Greenb45993c2010-12-18 15:13:50 +0000656 this->fds[this->fds_count].revents = 0;
Andy Green251f6fa2010-11-03 11:13:06 +0000657
Andy Greenb45993c2010-12-18 15:13:50 +0000658 this->fds[this->fds_count].events = POLLIN;
659 this->fds[this->fds_count++].fd = fd;
Andy Green251f6fa2010-11-03 11:13:06 +0000660
Andy Green775c0dd2010-10-29 14:15:22 +0100661 }
662
Andy Green775c0dd2010-10-29 14:15:22 +0100663
Andy Greenb45993c2010-12-18 15:13:50 +0000664 /* service anything incoming on websocket connection */
Andy Green69fa0722010-11-03 08:25:13 +0000665
Andy Greenb45993c2010-12-18 15:13:50 +0000666 libwebsocket_poll_connections(this);
Andy Greenff95d7a2010-10-28 22:36:01 +0100667 }
Andy Green251f6fa2010-11-03 11:13:06 +0000668
669fatal:
Andy Greenb45993c2010-12-18 15:13:50 +0000670
671 /* close listening skt and per-protocol broadcast sockets */
672 for (client = 0; client < this->fds_count; client++)
673 close(this->fds[0].fd);
Andy Greenff95d7a2010-10-28 22:36:01 +0100674
Andy Green3faa9c72010-11-08 17:03:03 +0000675#ifdef LWS_OPENSSL_SUPPORT
676 SSL_CTX_free(ssl_ctx);
677#endif
Andy Green251f6fa2010-11-03 11:13:06 +0000678 kill(0, SIGTERM);
Andy Greenb45993c2010-12-18 15:13:50 +0000679
680 if (this)
681 free(this);
Andy Green251f6fa2010-11-03 11:13:06 +0000682
683 return 0;
Andy Greenff95d7a2010-10-28 22:36:01 +0100684}
685
Andy Greenb45993c2010-12-18 15:13:50 +0000686/**
687 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
688 * connection.
689 * @wsi: pointer to struct websocket you want to know the protocol of
690 *
691 *
692 * This is useful to get the protocol to broadcast back to from inside
693 * the callback.
694 */
Andy Greenab990e42010-10-31 12:42:52 +0000695
Andy Greenb45993c2010-12-18 15:13:50 +0000696const struct libwebsocket_protocols *
697libwebsockets_get_protocol(struct libwebsocket *wsi)
698{
699 return wsi->protocol;
700}
701
702/**
703 * libwebsockets_broadcast() - Sends a buffer to rthe callback for all active
704 * connections of the given protocol.
705 * @protocol: pointer to the protocol you will broadcast to all members of
706 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
707 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
708 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
709 * case you are calling this function from callback context.
710 * @len: length of payload data in buf, starting from buf.
711 *
712 * This function allows bulk sending of a packet to every connection using
713 * the given protocol. It does not send the data directly; instead it calls
714 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
715 * wants to actually send the data for that connection, the callback itself
716 * should call libwebsocket_write().
717 *
718 * libwebsockets_broadcast() can be called from another fork context without
719 * having to take any care about data visibility between the processes, it'll
720 * "just work".
721 */
722
723
724int
725libwebsockets_broadcast(const struct libwebsocket_protocols * protocol,
726 unsigned char *buf, size_t len)
727{
728 struct libwebsocket_context * this = protocol->owning_server;
729 int n;
730
731 if (!protocol->broadcast_socket_user_fd) {
732 /*
733 * we are being called from poll thread context
734 * eg, from a callback. In that case don't use sockets for
735 * broadcast IPC (since we can't open a socket connection to
736 * a socket listening on our own thread) but directly do the
737 * send action.
738 *
739 * Locking is not needed because we are by definition being
740 * called in the poll thread context and are serialized.
741 */
742
743 for (n = this->count_protocols + 1; n < this->fds_count; n++) {
744
745 if ((unsigned long)this->wsi[n] < LWS_MAX_PROTOCOLS)
746 continue;
747
748 /* never broadcast to non-established connection */
749
750 if (this->wsi[n]->state != WSI_STATE_ESTABLISHED)
751 continue;
752
753 /* only broadcast to guys using requested protocol */
754
755 if (this->wsi[n]->protocol != protocol)
756 continue;
757
758 this->wsi[n]->protocol-> callback(this->wsi[n],
759 LWS_CALLBACK_BROADCAST,
760 this->wsi[n]->user_space,
761 buf, len);
762 }
763
764 return 0;
765 }
766
767 n = send(protocol->broadcast_socket_user_fd, buf, len, 0);
768
769 return n;
770}