2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010 Andy Green <andy@warmcat.com>
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.
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.
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,
22 #include "private-libwebsockets.h"
24 #ifdef LWS_OPENSSL_SUPPORT
31 libwebsocket_read(struct libwebsocket *wsi, unsigned char * buf, size_t len);
34 /* document the generic callback (it's a fake prototype under this) */
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
43 * This callback is the way the user controls what is served. All the
44 * protocol detail is hidden and handled by the library.
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.
50 * You get an opportunity to initialize user data when called back with
51 * LWS_CALLBACK_ESTABLISHED reason.
53 * LWS_CALLBACK_ESTABLISHED: after successful websocket handshake
55 * LWS_CALLBACK_CLOSED: when the websocket session ends
57 * LWS_CALLBACK_BROADCAST: signal to send to client (you would use
58 * 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
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.
72 extern int callback(struct libwebsocket * wsi,
73 enum libwebsocket_callback_reasons reason, void * user,
74 void *in, size_t len);
78 libwebsocket_close_and_free_session(struct libwebsocket *wsi)
82 if ((unsigned long)wsi < LWS_MAX_PROTOCOLS)
87 wsi->state = WSI_STATE_DEAD_SOCKET;
89 if (wsi->protocol->callback && n == WSI_STATE_ESTABLISHED)
90 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
91 wsi->user_space, NULL, 0);
93 for (n = 0; n < WSI_TOKEN_COUNT; n++)
94 if (wsi->utf8_token[n].token)
95 free(wsi->utf8_token[n].token);
97 // fprintf(stderr, "closing fd=%d\n", wsi->sock);
99 #ifdef LWS_OPENSSL_SUPPORT
101 n = SSL_get_fd(wsi->ssl);
102 SSL_shutdown(wsi->ssl);
107 shutdown(wsi->sock, SHUT_RDWR);
109 #ifdef LWS_OPENSSL_SUPPORT
113 free(wsi->user_space);
119 libwebsocket_poll_connections(struct libwebsocket_context *this)
121 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
122 LWS_SEND_BUFFER_POST_PADDING];
127 /* check for activity on client sockets */
129 for (client = this->count_protocols + 1; client < this->fds_count;
132 /* handle session socket closed */
134 if (this->fds[client].revents & (POLLERR | POLLHUP)) {
136 debug("Session Socket %d %p (fd=%d) dead\n",
137 client, this->wsi[client], this->fds[client]);
139 libwebsocket_close_and_free_session(this->wsi[client]);
143 /* any incoming data ready? */
145 if (!(this->fds[client].revents & POLLIN))
150 if ((unsigned long)this->wsi[client] < LWS_MAX_PROTOCOLS) {
152 len = read(this->fds[client].fd,
153 buf + LWS_SEND_BUFFER_PRE_PADDING,
154 MAX_BROADCAST_PAYLOAD);
156 fprintf(stderr, "Error receiving broadcast payload\n");
160 /* broadcast it to all guys with this protocol index */
162 for (n = this->count_protocols + 1;
163 n < this->fds_count; n++) {
165 if ((unsigned long)this->wsi[n] <
170 * never broadcast to non-established
174 if (this->wsi[n]->state != WSI_STATE_ESTABLISHED)
178 * only broadcast to connections using
179 * the requested protocol
182 if (this->wsi[n]->protocol->protocol_index !=
183 (unsigned long)this->wsi[client])
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);
195 #ifdef LWS_OPENSSL_SUPPORT
197 n = SSL_read(this->wsi[client]->ssl, buf, sizeof buf);
200 n = recv(this->fds[client].fd, buf, sizeof buf, 0);
203 fprintf(stderr, "Socket read returned %d\n", n);
207 // fprintf(stderr, "POLLIN with 0 len waiting\n");
208 libwebsocket_close_and_free_session(
214 /* service incoming data */
216 if (libwebsocket_read(this->wsi[client], buf, n) >= 0)
220 * it closed and nuked wsi[client], so remove the
221 * socket handle and wsi from our service list
225 debug("nuking wsi %p, fsd_count = %d\n",
226 this->wsi[client], this->fds_count - 1);
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];
242 * libwebsocket_create_server() - Create the listening websockets server
243 * @port: Port to listen on
244 * @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.
247 * It's not const because we write the owning_server member
248 * @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,
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.
256 * This function creates the listening socket and takes care
257 * of all initialization in one step.
259 * 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.
264 * The protocol callback functions are called for a handful of events
265 * including http requests coming in, websocket connections becoming
266 * established, and data arriving; it's also called periodically to allow
267 * async transmission.
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.
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.
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.
281 int libwebsocket_create_server(int port,
282 struct libwebsocket_protocols *protocols,
283 const char * ssl_cert_filepath,
284 const char * ssl_private_key_filepath,
292 struct sockaddr_in serv_addr, cli_addr;
294 struct libwebsocket_context * this = NULL;
297 #ifdef LWS_OPENSSL_SUPPORT
299 char ssl_err_buf[512];
301 use_ssl = ssl_cert_filepath != NULL && ssl_private_key_filepath != NULL;
303 fprintf(stderr, " Compiled with SSL support, using it\n");
305 fprintf(stderr, " Compiled with SSL support, not using it\n");
308 if (ssl_cert_filepath != NULL && ssl_private_key_filepath != NULL) {
309 fprintf(stderr, " Not compiled for OpenSSl support!\n");
312 fprintf(stderr, " Compiled without SSL support, serving unencrypted\n");
315 #ifdef LWS_OPENSSL_SUPPORT
319 OpenSSL_add_all_algorithms();
320 SSL_load_error_strings();
322 // Firefox insists on SSLv23 not SSLv3
323 // Konq disables SSLv2 by default now, SSLv23 works
325 method = (SSL_METHOD *)SSLv23_server_method();
327 fprintf(stderr, "problem creating ssl method: %s\n",
328 ERR_error_string(ERR_get_error(), ssl_err_buf));
331 ssl_ctx = SSL_CTX_new(method); /* create context */
333 printf("problem creating ssl context: %s\n",
334 ERR_error_string(ERR_get_error(), ssl_err_buf));
337 /* set the local certificate from CertFile */
338 n = SSL_CTX_use_certificate_file(ssl_ctx,
339 ssl_cert_filepath, SSL_FILETYPE_PEM);
341 fprintf(stderr, "problem getting cert '%s': %s\n",
343 ERR_error_string(ERR_get_error(), ssl_err_buf));
346 /* set the private key from KeyFile */
347 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));
355 /* verify private key */
356 if (!SSL_CTX_check_private_key(ssl_ctx)) {
357 fprintf(stderr, "Private SSL key doesn't match cert\n");
361 /* SSL is happy and has a cert it's content with */
365 this = malloc(sizeof (struct libwebsocket_context));
367 /* set up our external listening socket we serve on */
369 sockfd = socket(AF_INET, SOCK_STREAM, 0);
371 fprintf(stderr, "ERROR opening socket");
375 /* allow us to restart even if old sockets in TIME_WAIT */
376 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
378 bzero((char *) &serv_addr, sizeof(serv_addr));
379 serv_addr.sin_family = AF_INET;
380 serv_addr.sin_addr.s_addr = INADDR_ANY;
381 serv_addr.sin_port = htons(port);
383 n = bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
385 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n", port, n,
390 /* drop any root privs for this process */
394 fprintf(stderr, "setgid: %s\n", strerror(errno));
397 fprintf(stderr, "setuid: %s\n", strerror(errno));
400 * prepare the poll() fd array... it's like this
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
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;
416 fprintf(stderr, " Listening on port %d\n", port);
418 /* set up our internal broadcast trigger sockets per-protocol */
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;
426 fd = socket(AF_INET, SOCK_STREAM, 0);
428 fprintf(stderr, "ERROR opening socket");
432 /* allow us to restart even if old sockets in TIME_WAIT */
433 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
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 */
440 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
442 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
447 slen = sizeof cli_addr;
448 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
450 fprintf(stderr, "getsockname failed\n");
453 protocols[this->count_protocols].broadcast_socket_port =
454 ntohs(cli_addr.sin_port);
457 debug(" Protocol %s broadcast socket %d\n",
458 protocols[this->count_protocols].name,
459 ntohs(cli_addr.sin_port));
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;
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
476 fprintf(stderr, "Failed to fork websocket poll loop\n");
480 /* original process context */
483 * before we return to caller, we set up per-protocol
484 * broadcast sockets connected to the server ready to use
487 /* give server fork a chance to start up */
490 for (client = 1; client < this->count_protocols + 1; client++) {
491 fd = socket(AF_INET, SOCK_STREAM, 0);
493 fprintf(stderr,"Unable to create socket\n");
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,
503 fprintf(stderr, "Unable to connect to "
504 "broadcast socket %d, %s\n",
505 client, strerror(errno));
509 protocols[client - 1].broadcast_socket_user_fd = fd;
512 fprintf(stderr, "libwebsocket poll process forked\n");
517 /* we want a SIGHUP when our parent goes down */
518 prctl(PR_SET_PDEATHSIG, SIGHUP);
520 /* in this forked process, sit and service websocket connections */
524 n = poll(this->fds, this->fds_count, 1000);
526 if (n < 0 || this->fds[0].revents & (POLLERR | POLLHUP)) {
527 fprintf(stderr, "Listen Socket dead\n");
530 if (n == 0) /* poll timeout */
533 /* handle accept on listening socket? */
535 for (client = 0; client < this->count_protocols + 1; client++) {
537 if (!this->fds[client].revents & POLLIN)
540 /* listen socket got an unencrypted connection... */
542 clilen = sizeof(cli_addr);
543 fd = accept(this->fds[client].fd,
544 (struct sockaddr *)&cli_addr, &clilen);
546 fprintf(stderr, "ERROR on accept");
550 if (this->fds_count >= MAX_CLIENTS) {
551 fprintf(stderr, "too busy");
558 * accepting a connection to broadcast socket
559 * set wsi to be protocol index not pointer
562 this->wsi[this->fds_count] =
563 (struct libwebsocket *)(long)(client - 1);
568 /* accepting connection to main listener */
570 this->wsi[this->fds_count] =
571 malloc(sizeof(struct libwebsocket));
572 if (!this->wsi[this->fds_count])
575 #ifdef LWS_OPENSSL_SUPPORT
578 this->wsi[this->fds_count]->ssl =
580 if (this->wsi[this->fds_count]->ssl == NULL) {
581 fprintf(stderr, "SSL_new failed: %s\n",
582 ERR_error_string(SSL_get_error(
583 this->wsi[this->fds_count]->ssl, 0),
585 free(this->wsi[this->fds_count]);
589 SSL_set_fd(this->wsi[this->fds_count]->ssl, fd);
591 n = SSL_accept(this->wsi[this->fds_count]->ssl);
594 * browsers seem to probe with various
595 * ssl params which fail then retry
598 debug("SSL_accept failed skt %u: %s\n",
600 ERR_error_string(SSL_get_error(
601 this->wsi[this->fds_count]->ssl,
604 this->wsi[this->fds_count]->ssl);
605 free(this->wsi[this->fds_count]);
608 debug("accepted new SSL conn "
609 "port %u on fd=%d SSL ver %s\n",
610 ntohs(cli_addr.sin_port), fd,
611 SSL_get_version(this->wsi[
612 this->fds_count]->ssl));
616 debug("accepted new conn port %u on fd=%d\n",
617 ntohs(cli_addr.sin_port), fd);
619 /* intialize the instance struct */
621 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;
625 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
626 this->wsi[this->fds_count]->
627 utf8_token[n].token = NULL;
628 this->wsi[this->fds_count]->
629 utf8_token[n].token_len = 0;
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
638 this->wsi[this->fds_count]->protocol = protocols;
639 this->wsi[this->fds_count]->user_space = NULL;
642 * Default protocol is 76
643 * After 76, there's a header specified to inform which
644 * draft the client wants, when that's seen we modify
645 * the individual connection's spec revision accordingly
647 this->wsi[this->fds_count]->ietf_spec_revision = 76;
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! )
656 this->fds[this->fds_count].revents = 0;
658 this->fds[this->fds_count].events = POLLIN;
659 this->fds[this->fds_count++].fd = fd;
664 /* service anything incoming on websocket connection */
666 libwebsocket_poll_connections(this);
671 /* close listening skt and per-protocol broadcast sockets */
672 for (client = 0; client < this->fds_count; client++)
673 close(this->fds[0].fd);
675 #ifdef LWS_OPENSSL_SUPPORT
676 SSL_CTX_free(ssl_ctx);
687 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
689 * @wsi: pointer to struct websocket you want to know the protocol of
692 * This is useful to get the protocol to broadcast back to from inside
696 const struct libwebsocket_protocols *
697 libwebsockets_get_protocol(struct libwebsocket *wsi)
699 return wsi->protocol;
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.
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().
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
725 libwebsockets_broadcast(const struct libwebsocket_protocols * protocol,
726 unsigned char *buf, size_t len)
728 struct libwebsocket_context * this = protocol->owning_server;
731 if (!protocol->broadcast_socket_user_fd) {
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
739 * Locking is not needed because we are by definition being
740 * called in the poll thread context and are serialized.
743 for (n = this->count_protocols + 1; n < this->fds_count; n++) {
745 if ((unsigned long)this->wsi[n] < LWS_MAX_PROTOCOLS)
748 /* never broadcast to non-established connection */
750 if (this->wsi[n]->state != WSI_STATE_ESTABLISHED)
753 /* only broadcast to guys using requested protocol */
755 if (this->wsi[n]->protocol != protocol)
758 this->wsi[n]->protocol-> callback(this->wsi[n],
759 LWS_CALLBACK_BROADCAST,
760 this->wsi[n]->user_space,
767 n = send(protocol->broadcast_socket_user_fd, buf, len, 0);