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"
29 #include <sys/socket.h>
33 #ifdef LWS_OPENSSL_SUPPORT
34 int openssl_websocket_private_data_index;
38 #include "../win32port/win32helpers/websock-w32.c"
41 #include "../win32port/win32helpers/websock-w32.c"
46 * In-place str to lower case
58 /* file descriptor hash management */
61 wsi_from_fd(struct libwebsocket_context *context, int fd)
63 int h = LWS_FD_HASH(fd);
66 for (n = 0; n < context->fd_hashtable[h].length; n++)
67 if (context->fd_hashtable[h].wsi[n]->sock == fd)
68 return context->fd_hashtable[h].wsi[n];
74 insert_wsi(struct libwebsocket_context *context, struct libwebsocket *wsi)
76 int h = LWS_FD_HASH(wsi->sock);
78 if (context->fd_hashtable[h].length == MAX_CLIENTS - 1) {
79 fprintf(stderr, "hash table overflow\n");
83 context->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;
89 delete_from_fd(struct libwebsocket_context *context, int fd)
91 int h = LWS_FD_HASH(fd);
94 for (n = 0; n < context->fd_hashtable[h].length; n++)
95 if (context->fd_hashtable[h].wsi[n]->sock == fd) {
96 while (n < context->fd_hashtable[h].length) {
97 context->fd_hashtable[h].wsi[n] =
98 context->fd_hashtable[h].wsi[n + 1];
101 context->fd_hashtable[h].length--;
106 fprintf(stderr, "Failed to find fd %d requested for "
107 "delete in hashtable\n", fd);
111 #ifdef LWS_OPENSSL_SUPPORT
113 libwebsockets_decode_ssl_error(void)
118 while ((err = ERR_get_error()) != 0) {
119 ERR_error_string_n(err, buf, sizeof(buf));
120 fprintf(stderr, "*** %s\n", buf);
127 interface_to_sa(const char *ifname, struct sockaddr_in *addr, size_t addrlen)
135 struct sockaddr_in *sin;
138 for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
139 if (strcmp(ifc->ifa_name, ifname))
141 if (ifc->ifa_addr == NULL)
143 sin = (struct sockaddr_in *)ifc->ifa_addr;
144 if (sin->sin_family != AF_INET)
146 memcpy(addr, sin, addrlen);
156 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
157 struct libwebsocket *wsi, enum lws_close_status reason)
161 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
162 LWS_SEND_BUFFER_POST_PADDING];
165 struct lws_tokens eff_buf;
166 struct libwebsocket_extension *ext;
171 old_state = wsi->state;
173 if (old_state == WSI_STATE_DEAD_SOCKET)
176 wsi->close_reason = reason;
179 * are his extensions okay with him closing? Eg he might be a mux
180 * parent and just his ch1 aspect is closing?
184 for (n = 0; n < wsi->count_active_extensions; n++) {
185 if (!wsi->active_extensions[n]->callback)
188 m = wsi->active_extensions[n]->callback(context,
189 wsi->active_extensions[n], wsi,
190 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
191 wsi->active_extensions_user[n], NULL, 0);
194 * if somebody vetoed actually closing him at this time....
195 * up to the extension to track the attempted close, let's
200 debug("extension vetoed close\n");
208 * flush any tx pending from extensions, since we may send close packet
209 * if there are problems with send, just nuke the connection
215 /* default to nobody has more to spill */
218 eff_buf.token = NULL;
219 eff_buf.token_len = 0;
221 /* show every extension the new incoming data */
223 for (n = 0; n < wsi->count_active_extensions; n++) {
224 m = wsi->active_extensions[n]->callback(
225 wsi->protocol->owning_server,
226 wsi->active_extensions[n], wsi,
227 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
228 wsi->active_extensions_user[n], &eff_buf, 0);
230 fprintf(stderr, "Extension reports "
232 goto just_kill_connection;
236 * at least one extension told us he has more
237 * to spill, so we will go around again after
242 /* assuming they left us something to send, send it */
244 if (eff_buf.token_len)
245 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
247 goto just_kill_connection;
251 * signal we are closing, libsocket_write will
252 * add any necessary version-specific stuff. If the write fails,
253 * no worries we are closing anyway. If we didn't initiate this
254 * close, then our state has been changed to
255 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
257 * Likewise if it's a second call to close this connection after we
258 * sent the close indication to the peer already, we are in state
259 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
262 if (old_state == WSI_STATE_ESTABLISHED &&
263 reason != LWS_CLOSE_STATUS_NOSTATUS) {
265 debug("sending close indication...\n");
267 n = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
271 * we have sent a nice protocol level indication we
272 * now wish to close, we should not send anything more
275 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
277 /* and we should wait for a reply for a bit */
279 libwebsocket_set_timeout(wsi,
280 PENDING_TIMEOUT_CLOSE_ACK, 5);
282 debug("sent close indication, awaiting ack\n");
287 /* else, the send failed and we should just hang up */
290 just_kill_connection:
292 debug("libwebsocket_close_and_free_session: just_kill_connection\n");
295 * we won't be servicing or receiving anything further from this guy
296 * remove this fd from wsi mapping hashtable
300 delete_from_fd(context, wsi->sock);
302 /* delete it from the internal poll list if still present */
304 for (n = 0; n < context->fds_count; n++) {
305 if (context->fds[n].fd != wsi->sock)
307 while (n < context->fds_count - 1) {
308 context->fds[n] = context->fds[n + 1];
311 context->fds_count--;
312 /* we only have to deal with one */
313 n = context->fds_count;
316 /* remove also from external POLL support via protocol 0 */
318 context->protocols[0].callback(context, wsi,
319 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
321 wsi->state = WSI_STATE_DEAD_SOCKET;
323 /* tell the user it's all over for this guy */
325 if (wsi->protocol && wsi->protocol->callback &&
326 ((old_state == WSI_STATE_ESTABLISHED) ||
327 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
328 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
329 debug("calling back CLOSED\n");
330 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
331 wsi->user_space, NULL, 0);
333 debug("not calling back closed, old_state=%d\n", old_state);
335 /* deallocate any active extension contexts */
337 for (n = 0; n < wsi->count_active_extensions; n++) {
338 if (!wsi->active_extensions[n]->callback)
341 wsi->active_extensions[n]->callback(context,
342 wsi->active_extensions[n], wsi,
343 LWS_EXT_CALLBACK_DESTROY,
344 wsi->active_extensions_user[n], NULL, 0);
346 free(wsi->active_extensions_user[n]);
350 * inform all extensions in case they tracked this guy out of band
351 * even though not active on him specifically
354 ext = context->extensions;
355 while (ext && ext->callback) {
356 ext->callback(context, ext, wsi,
357 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
362 /* free up his parsing allocations */
364 for (n = 0; n < WSI_TOKEN_COUNT; n++)
365 if (wsi->utf8_token[n].token)
366 free(wsi->utf8_token[n].token);
369 free(wsi->c_address);
371 /* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
373 #ifdef LWS_OPENSSL_SUPPORT
375 n = SSL_get_fd(wsi->ssl);
376 SSL_shutdown(wsi->ssl);
385 shutdown(wsi->sock, SHUT_RDWR);
388 closesocket(wsi->sock);
393 #ifdef LWS_OPENSSL_SUPPORT
396 if (wsi->protocol && wsi->protocol->per_session_data_size && wsi->user_space) /* user code may own */
397 free(wsi->user_space);
403 * libwebsockets_hangup_on_client() - Server calls to terminate client
405 * @context: libwebsockets context
406 * @fd: Connection socket descriptor
410 libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
412 struct libwebsocket *wsi = wsi_from_fd(context, fd);
417 libwebsocket_close_and_free_session(context, wsi,
418 LWS_CLOSE_STATUS_NOSTATUS);
423 * libwebsockets_get_peer_addresses() - Get client address information
424 * @fd: Connection socket descriptor
425 * @name: Buffer to take client address name
426 * @name_len: Length of client address name buffer
427 * @rip: Buffer to take client address IP qotted quad
428 * @rip_len: Length of client address IP buffer
430 * This function fills in @name and @rip with the name and IP of
431 * the client connected with socket descriptor @fd. Names may be
432 * truncated if there is not enough room. If either cannot be
433 * determined, they will be returned as valid zero-length strings.
437 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
438 char *rip, int rip_len)
441 struct sockaddr_in sin;
442 struct hostent *host;
443 struct hostent *host1;
447 struct sockaddr_un *un;
453 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
454 perror("getpeername");
458 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
461 perror("gethostbyaddr");
465 strncpy(name, host->h_name, name_len);
466 name[name_len - 1] = '\0';
468 host1 = gethostbyname(host->h_name);
471 p = (unsigned char *)host1;
474 p = (unsigned char *)host1->h_addr_list[n++];
477 if ((host1->h_addrtype != AF_INET)
479 && (host1->h_addrtype != AF_LOCAL)
484 if (host1->h_addrtype == AF_INET)
485 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
488 un = (struct sockaddr_un *)p;
489 strncpy(ip, un->sun_path, sizeof(ip) - 1);
490 ip[sizeof(ip) - 1] = '\0';
494 strncpy(rip, ip, rip_len);
495 rip[rip_len - 1] = '\0';
499 int libwebsockets_get_random(struct libwebsocket_context *context,
506 for (n = 0; n < len; n++)
507 p[n] = (unsigned char)rand();
509 n = read(context->fd_random, p, len);
516 libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md)
518 return SHA1(d, n, md);
521 void libwebsockets_00_spaceout(char *key, int spaces, int seed)
527 if (*key && (seed & 1))
531 p = key + strlen(key);
540 void libwebsockets_00_spam(char *key, int count, int seed)
547 if (*key && (seed & 1))
551 p = key + strlen(key);
556 *key++ = 0x21 + ((seed & 0xffff) % 15);
557 /* 4 would use it up too fast.. not like it matters */
562 int lws_send_pipe_choked(struct libwebsocket *wsi)
567 fds.events = POLLOUT;
570 if (poll(&fds, 1, 0) != 1)
573 if ((fds.revents & POLLOUT) == 0)
576 /* okay to send another packet without blocking */
582 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
583 struct libwebsocket *wsi, struct pollfd *pollfd)
585 struct lws_tokens eff_buf;
591 for (n = 0; n < wsi->count_active_extensions; n++) {
592 if (!wsi->active_extensions[n]->callback)
595 m = wsi->active_extensions[n]->callback(context,
596 wsi->active_extensions[n], wsi,
597 LWS_EXT_CALLBACK_IS_WRITEABLE,
598 wsi->active_extensions_user[n], NULL, 0);
606 if (!wsi->extension_data_pending || handled == 2)
610 * check in on the active extensions, see if they
611 * had pending stuff to spill... they need to get the
612 * first look-in otherwise sequence will be disordered
614 * NULL, zero-length eff_buf means just spill pending
620 /* default to nobody has more to spill */
623 eff_buf.token = NULL;
624 eff_buf.token_len = 0;
626 /* give every extension a chance to spill */
628 for (n = 0; n < wsi->count_active_extensions; n++) {
629 m = wsi->active_extensions[n]->callback(
630 wsi->protocol->owning_server,
631 wsi->active_extensions[n], wsi,
632 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
633 wsi->active_extensions_user[n], &eff_buf, 0);
635 fprintf(stderr, "ext reports fatal error\n");
640 * at least one extension told us he has more
641 * to spill, so we will go around again after
646 /* assuming they gave us something to send, send it */
648 if (eff_buf.token_len) {
649 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
655 /* no extension has more to spill */
661 * There's more to spill from an extension, but we just sent
662 * something... did that leave the pipe choked?
665 if (!lws_send_pipe_choked(wsi))
666 /* no we could add more */
669 debug("choked in POLLOUT service\n");
672 * Yes, he's choked. Leave the POLLOUT masked on so we will
673 * come back here when he is unchoked. Don't call the user
674 * callback to enforce ordering of spilling, he'll get called
675 * when we come back here and there's nothing more to spill.
681 wsi->extension_data_pending = 0;
687 pollfd->events &= ~POLLOUT;
689 /* external POLL support via protocol 0 */
690 context->protocols[0].callback(context, wsi,
691 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
692 (void *)(long)wsi->sock, NULL, POLLOUT);
697 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
698 n = LWS_CALLBACK_CLIENT_WRITEABLE;
700 n = LWS_CALLBACK_SERVER_WRITEABLE;
702 wsi->protocol->callback(context, wsi, n, wsi->user_space, NULL, 0);
710 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
711 struct libwebsocket *wsi, unsigned int sec)
716 * if extensions want in on it (eg, we are a mux parent)
717 * give them a chance to service child timeouts
720 for (n = 0; n < wsi->count_active_extensions; n++)
721 wsi->active_extensions[n]->callback(
722 context, wsi->active_extensions[n],
723 wsi, LWS_EXT_CALLBACK_1HZ,
724 wsi->active_extensions_user[n], NULL, sec);
726 if (!wsi->pending_timeout)
730 * if we went beyond the allowed time, kill the
734 if (sec > wsi->pending_timeout_limit) {
735 debug("TIMEDOUT WAITING\n");
736 libwebsocket_close_and_free_session(context,
737 wsi, LWS_CLOSE_STATUS_NOSTATUS);
741 struct libwebsocket *
742 libwebsocket_create_new_server_wsi(struct libwebsocket_context *context)
744 struct libwebsocket *new_wsi;
747 new_wsi = malloc(sizeof(struct libwebsocket));
748 if (new_wsi == NULL) {
749 fprintf(stderr, "Out of memory for new connection\n");
753 memset(new_wsi, 0, sizeof(struct libwebsocket));
754 new_wsi->count_active_extensions = 0;
755 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
757 /* intialize the instance struct */
759 new_wsi->state = WSI_STATE_HTTP;
760 new_wsi->name_buffer_pos = 0;
761 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
763 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
764 new_wsi->utf8_token[n].token = NULL;
765 new_wsi->utf8_token[n].token_len = 0;
769 * these can only be set once the protocol is known
770 * we set an unestablished connection's protocol pointer
771 * to the start of the supported list, so it can look
772 * for matching ones during the handshake
774 new_wsi->protocol = context->protocols;
775 new_wsi->user_space = NULL;
778 * Default protocol is 76 / 00
779 * After 76, there's a header specified to inform which
780 * draft the client wants, when that's seen we modify
781 * the individual connection's spec revision accordingly
783 new_wsi->ietf_spec_revision = 0;
789 libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
790 struct libwebsocket *wsi, char *pkt)
795 struct libwebsocket_extension *ext;
796 struct libwebsocket_extension *ext1;
798 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
799 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
800 static const char magic_websocket_guid[] =
801 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
804 * create the random key
807 n = libwebsockets_get_random(context, hash, 16);
809 fprintf(stderr, "Unable to read from random dev %s\n",
810 SYSTEM_RANDOM_FILEPATH);
816 free(wsi->c_protocol);
817 libwebsocket_close_and_free_session(context, wsi,
818 LWS_CLOSE_STATUS_NOSTATUS);
822 lws_b64_encode_string(hash, 16, wsi->key_b64,
823 sizeof wsi->key_b64);
826 * 00 example client handshake
828 * GET /socket.io/websocket HTTP/1.1
830 * Connection: Upgrade
831 * Host: 127.0.0.1:9999
832 * Origin: http://127.0.0.1
833 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7 92 ^
834 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
835 * Cookie: socketio=websocket
839 * 04 example client handshake
842 * Host: server.example.com
844 * Connection: Upgrade
845 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
846 * Sec-WebSocket-Origin: http://example.com
847 * Sec-WebSocket-Protocol: chat, superchat
848 * Sec-WebSocket-Version: 4
851 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
853 if (wsi->ietf_spec_revision == 0) {
854 unsigned char spaces_1, spaces_2;
855 unsigned int max_1, max_2;
856 unsigned int num_1, num_2;
857 unsigned long product_1, product_2;
864 libwebsockets_get_random(context, &spaces_1, sizeof(char));
865 libwebsockets_get_random(context, &spaces_2, sizeof(char));
867 spaces_1 = (spaces_1 % 12) + 1;
868 spaces_2 = (spaces_2 % 12) + 1;
870 max_1 = 4294967295 / spaces_1;
871 max_2 = 4294967295 / spaces_2;
873 libwebsockets_get_random(context, &num_1, sizeof(int));
874 libwebsockets_get_random(context, &num_2, sizeof(int));
876 num_1 = (num_1 % max_1);
877 num_2 = (num_2 % max_2);
879 challenge[0] = num_1 >> 24;
880 challenge[1] = num_1 >> 16;
881 challenge[2] = num_1 >> 8;
882 challenge[3] = num_1;
883 challenge[4] = num_2 >> 24;
884 challenge[5] = num_2 >> 16;
885 challenge[6] = num_2 >> 8;
886 challenge[7] = num_2;
888 product_1 = num_1 * spaces_1;
889 product_2 = num_2 * spaces_2;
891 sprintf(key_1, "%lu", product_1);
892 sprintf(key_2, "%lu", product_2);
894 libwebsockets_get_random(context, &seed, sizeof(int));
895 libwebsockets_get_random(context, &count, sizeof(int));
897 libwebsockets_00_spam(key_1, (count % 12) + 1, seed);
899 libwebsockets_get_random(context, &seed, sizeof(int));
900 libwebsockets_get_random(context, &count, sizeof(int));
902 libwebsockets_00_spam(key_2, (count % 12) + 1, seed);
904 libwebsockets_get_random(context, &seed, sizeof(int));
906 libwebsockets_00_spaceout(key_1, spaces_1, seed);
907 libwebsockets_00_spaceout(key_2, spaces_2, seed >> 16);
909 p += sprintf(p, "Upgrade: WebSocket\x0d\x0a"
910 "Connection: Upgrade\x0d\x0aHost: %s\x0d\x0a",
913 p += sprintf(p, "Origin: %s\x0d\x0a", wsi->c_origin);
916 p += sprintf(p, "Sec-WebSocket-Protocol: %s"
917 "\x0d\x0a", wsi->c_protocol);
919 p += sprintf(p, "Sec-WebSocket-Key1: %s\x0d\x0a", key_1);
920 p += sprintf(p, "Sec-WebSocket-Key2: %s\x0d\x0a", key_2);
922 /* give userland a chance to append, eg, cookies */
924 context->protocols[0].callback(context, wsi,
925 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
926 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
928 p += sprintf(p, "\x0d\x0a");
930 if (libwebsockets_get_random(context, p, 8) != 8)
932 memcpy(&challenge[8], p, 8);
935 /* precompute what we want to see from the server */
937 MD5((unsigned char *)challenge, 16,
938 (unsigned char *)wsi->initial_handshake_hash_base64);
943 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
944 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
945 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
946 "Sec-WebSocket-Key: ");
947 strcpy(p, wsi->key_b64);
948 p += strlen(wsi->key_b64);
949 p += sprintf(p, "\x0d\x0a");
951 p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
954 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
957 /* tell the server what extensions we could support */
959 p += sprintf(p, "Sec-WebSocket-Extensions: ");
961 ext = context->extensions;
962 while (ext && ext->callback) {
965 ext1 = context->extensions;
967 while (ext1 && ext1->callback) {
968 n |= ext1->callback(context, ext1, wsi,
969 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
970 NULL, (char *)ext->name, 0);
975 if (n) { /* an extension vetos us */
976 debug("ext %s vetoed\n", (char *)ext->name);
981 n = context->protocols[0].callback(context, wsi,
982 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
983 wsi->user_space, (char *)ext->name, 0);
986 * zero return from callback means
987 * go ahead and allow the extension,
988 * it's what we get if the callback is
1001 p += sprintf(p, "%s", ext->name);
1007 p += sprintf(p, "\x0d\x0a");
1009 if (wsi->ietf_spec_revision)
1010 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1011 wsi->ietf_spec_revision);
1013 /* give userland a chance to append, eg, cookies */
1015 context->protocols[0].callback(context, wsi,
1016 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1017 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
1019 p += sprintf(p, "\x0d\x0a");
1021 /* prepare the expected server accept response */
1023 strcpy((char *)buf, wsi->key_b64);
1024 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
1026 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
1028 lws_b64_encode_string(hash, 20,
1029 wsi->initial_handshake_hash_base64,
1030 sizeof wsi->initial_handshake_hash_base64);
1038 /* done with these now */
1043 free(wsi->c_origin);
1049 lws_client_interpret_server_handshake(struct libwebsocket_context *context,
1050 struct libwebsocket *wsi)
1052 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
1053 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
1061 struct libwebsocket_extension *ext;
1065 static const char magic_websocket_04_masking_guid[] =
1066 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
1071 * HTTP/1.1 101 WebSocket Protocol Handshake
1072 * Upgrade: WebSocket
1073 * Connection: Upgrade
1074 * Sec-WebSocket-Origin: http://127.0.0.1
1075 * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1080 if (wsi->ietf_spec_revision == 0) {
1081 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1082 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1083 !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1084 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1085 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1086 wsi->c_protocol != NULL)) {
1087 debug("libwebsocket_client_handshake "
1088 "missing required header(s)\n");
1094 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1095 if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
1096 fprintf(stderr, "libwebsocket_client_handshake "
1097 "server sent bad HTTP response '%s'\n",
1098 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1102 if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len < 16) {
1103 fprintf(stderr, "libwebsocket_client_handshake "
1104 "challenge reply too short %d\n",
1106 WSI_TOKEN_CHALLENGE].token_len);
1113 goto select_protocol;
1117 * well, what the server sent looked reasonable for syntax.
1118 * Now let's confirm it sent all the necessary headers
1121 fprintf(stderr, "WSI_TOKEN_HTTP: %d\n",
1122 wsi->utf8_token[WSI_TOKEN_HTTP].token_len);
1123 fprintf(stderr, "WSI_TOKEN_UPGRADE: %d\n",
1124 wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len);
1125 fprintf(stderr, "WSI_TOKEN_CONNECTION: %d\n",
1126 wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len);
1127 fprintf(stderr, "WSI_TOKEN_ACCEPT: %d\n",
1128 wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len);
1129 fprintf(stderr, "WSI_TOKEN_NONCE: %d\n",
1130 wsi->utf8_token[WSI_TOKEN_NONCE].token_len);
1131 fprintf(stderr, "WSI_TOKEN_PROTOCOL: %d\n",
1132 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
1134 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1135 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1136 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1137 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
1138 (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
1139 wsi->ietf_spec_revision == 4) ||
1140 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1141 wsi->c_protocol != NULL)) {
1142 debug("libwebsocket_client_handshake "
1143 "missing required header(s)\n");
1150 * Everything seems to be there, now take a closer look at what
1154 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1155 if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
1156 fprintf(stderr, "libwebsocket_client_handshake "
1157 "server sent bad HTTP response '%s'\n",
1158 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1162 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1163 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1165 fprintf(stderr, "libwebsocket_client_handshake server "
1166 "sent bad Upgrade header '%s'\n",
1167 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1171 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1172 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1174 fprintf(stderr, "libwebsocket_client_handshake server "
1175 "sent bad Connection hdr '%s'\n",
1176 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1181 pc = wsi->c_protocol;
1183 fprintf(stderr, "lws_client_interpret_server_handshake: "
1184 "NULL c_protocol\n");
1186 debug("lws_client_interpret_server_handshake: "
1187 "cPprotocol='%s'\n", pc);
1190 * confirm the protocol the server wants to talk was in the list
1191 * of protocols we offered
1194 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1196 fprintf(stderr, "lws_client_interpret_server_handshake "
1197 "WSI_TOKEN_PROTOCOL is null\n");
1199 * no protocol name to work from,
1200 * default to first protocol
1202 wsi->protocol = &context->protocols[0];
1203 wsi->c_callback = wsi->protocol->callback;
1204 free(wsi->c_protocol);
1209 while (*pc && !okay) {
1210 if ((!strncmp(pc, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1211 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
1212 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
1213 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
1217 while (*pc && *pc != ',')
1219 while (*pc && *pc != ' ')
1223 /* done with him now */
1225 if (wsi->c_protocol)
1226 free(wsi->c_protocol);
1229 fprintf(stderr, "libwebsocket_client_handshake server "
1230 "sent bad protocol '%s'\n",
1231 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1236 * identify the selected protocol struct and set it
1239 wsi->protocol = NULL;
1240 while (context->protocols[n].callback && !wsi->protocol) { /* Stop after finding first one?? */
1241 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1242 context->protocols[n].name) == 0) {
1243 wsi->protocol = &context->protocols[n];
1244 wsi->c_callback = wsi->protocol->callback;
1249 if (wsi->protocol == NULL) {
1250 fprintf(stderr, "libwebsocket_client_handshake server "
1251 "requested protocol '%s', which we "
1252 "said we supported but we don't!\n",
1253 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1258 /* instantiate the accepted extensions */
1260 if (!wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
1261 debug("no client extenstions allowed by server\n");
1266 * break down the list of server accepted extensions
1267 * and go through matching them or identifying bogons
1270 c = wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token;
1274 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
1276 if (n < sizeof(ext_name) - 1)
1289 /* check we actually support it */
1291 debug("checking client ext %s\n", ext_name);
1294 ext = wsi->protocol->owning_server->extensions;
1295 while (ext && ext->callback) {
1297 if (strcmp(ext_name, ext->name)) {
1304 debug("instantiating client ext %s\n", ext_name);
1306 /* instantiate the extension on this conn */
1308 wsi->active_extensions_user[
1309 wsi->count_active_extensions] =
1310 malloc(ext->per_session_data_size);
1311 memset(wsi->active_extensions_user[
1312 wsi->count_active_extensions], 0,
1313 ext->per_session_data_size);
1314 wsi->active_extensions[
1315 wsi->count_active_extensions] = ext;
1317 /* allow him to construct his context */
1319 ext->callback(wsi->protocol->owning_server,
1321 LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
1322 wsi->active_extensions_user[
1323 wsi->count_active_extensions],
1326 wsi->count_active_extensions++;
1332 fprintf(stderr, "Server said we should use"
1333 "an unknown extension '%s'!\n", ext_name);
1343 if (wsi->ietf_spec_revision == 0) {
1345 if (memcmp(wsi->initial_handshake_hash_base64,
1346 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
1347 fprintf(stderr, "libwebsocket_client_handshake "
1348 "failed 00 challenge compare\n");
1350 fprintf(stderr, "%s", pkt);
1358 * Confirm his accept token is the one we precomputed
1361 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1362 wsi->initial_handshake_hash_base64)) {
1363 fprintf(stderr, "libwebsocket_client_handshake server "
1364 "sent bad ACCEPT '%s' vs computed '%s'\n",
1365 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1366 wsi->initial_handshake_hash_base64);
1370 if (wsi->ietf_spec_revision == 4) {
1372 * Calculate the 04 masking key to use when
1373 * sending data to server
1376 strcpy((char *)buf, wsi->key_b64);
1377 p = (char *)buf + strlen(wsi->key_b64);
1378 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1379 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1380 strcpy(p, magic_websocket_04_masking_guid);
1381 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1385 /* allocate the per-connection user memory (if any) */
1386 if (wsi->protocol->per_session_data_size &&
1387 !libwebsocket_ensure_user_space(wsi))
1390 /* clear his proxy connection timeout */
1392 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1394 /* mark him as being alive */
1396 wsi->state = WSI_STATE_ESTABLISHED;
1397 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1399 debug("handshake OK for protocol %s\n", wsi->protocol->name);
1401 /* call him back to inform him he is up */
1403 wsi->protocol->callback(context, wsi,
1404 LWS_CALLBACK_CLIENT_ESTABLISHED,
1405 wsi->user_space, NULL, 0);
1408 * inform all extensions, not just active ones since they
1412 ext = context->extensions;
1414 while (ext && ext->callback) {
1416 for (n = 0; n < wsi->count_active_extensions; n++)
1417 if (wsi->active_extensions[n] == ext)
1418 v = wsi->active_extensions_user[n];
1420 ext->callback(context, ext, wsi,
1421 LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
1428 if (wsi->c_protocol)
1429 free(wsi->c_protocol);
1432 if (wsi->c_callback) wsi->c_callback(context, wsi,
1433 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
1436 libwebsocket_close_and_free_session(context, wsi,
1437 LWS_CLOSE_STATUS_NOSTATUS); // But this should be LWS_CLOSE_STATUS_PROTOCOL_ERR
1445 * libwebsocket_service_fd() - Service polled socket with something waiting
1446 * @context: Websocket context
1447 * @pollfd: The pollfd entry describing the socket fd and which events
1450 * This function closes any active connections and then frees the
1451 * context. After calling this, any further use of the context is
1456 libwebsocket_service_fd(struct libwebsocket_context *context,
1457 struct pollfd *pollfd)
1459 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
1460 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
1461 struct libwebsocket *wsi;
1462 struct libwebsocket *new_wsi;
1467 unsigned int clilen;
1468 struct sockaddr_in cli_addr;
1473 struct lws_tokens eff_buf;
1477 #ifdef LWS_OPENSSL_SUPPORT
1478 char ssl_err_buf[512];
1481 * you can call us with pollfd = NULL to just allow the once-per-second
1482 * global timeout checks; if less than a second since the last check
1483 * it returns immediately then.
1486 gettimeofday(&tv, NULL);
1488 if (context->last_timeout_check_s != tv.tv_sec) {
1489 context->last_timeout_check_s = tv.tv_sec;
1491 /* global timeout check once per second */
1493 for (n = 0; n < context->fds_count; n++) {
1494 wsi = wsi_from_fd(context, context->fds[n].fd);
1496 libwebsocket_service_timeout_check(context, wsi,
1501 /* just here for timeout management? */
1506 /* no, here to service a socket descriptor */
1508 wsi = wsi_from_fd(context, pollfd->fd);
1513 switch (wsi->mode) {
1514 case LWS_CONNMODE_SERVER_LISTENER:
1516 /* pollin means a client has connected to us then */
1518 if (!pollfd->revents & POLLIN)
1521 if (context->fds_count >= MAX_CLIENTS) {
1522 fprintf(stderr, "too busy to accept new client\n");
1526 /* listen socket got an unencrypted connection... */
1528 clilen = sizeof(cli_addr);
1529 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1531 if (accept_fd < 0) {
1532 debug("ERROR on accept\n");
1538 setsockopt(accept_fd, IPPROTO_TCP, TCP_NODELAY,
1539 (const void *)&opt, sizeof(opt));
1542 * look at who we connected to and give user code a chance
1543 * to reject based on client IP. There's no protocol selected
1544 * yet so we issue this to protocols[0]
1547 if ((context->protocols[0].callback)(context, wsi,
1548 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1549 (void *)(long)accept_fd, NULL, 0)) {
1550 debug("Callback denied network connection\n");
1552 closesocket(accept_fd);
1559 /* accepting connection to main listener */
1561 new_wsi = libwebsocket_create_new_server_wsi(context);
1562 if (new_wsi == NULL)
1565 new_wsi->sock = accept_fd;
1568 #ifdef LWS_OPENSSL_SUPPORT
1569 new_wsi->ssl = NULL;
1571 if (context->use_ssl) {
1573 new_wsi->ssl = SSL_new(context->ssl_ctx);
1574 if (new_wsi->ssl == NULL) {
1575 fprintf(stderr, "SSL_new failed: %s\n",
1576 ERR_error_string(SSL_get_error(
1577 new_wsi->ssl, 0), NULL));
1578 libwebsockets_decode_ssl_error();
1583 SSL_set_fd(new_wsi->ssl, accept_fd);
1585 n = SSL_accept(new_wsi->ssl);
1588 * browsers seem to probe with various
1589 * ssl params which fail then retry
1592 debug("SSL_accept failed skt %u: %s\n",
1594 ERR_error_string(SSL_get_error(
1595 new_wsi->ssl, n), NULL));
1602 debug("accepted new SSL conn "
1603 "port %u on fd=%d SSL ver %s\n",
1604 ntohs(cli_addr.sin_port), accept_fd,
1605 SSL_get_version(new_wsi->ssl));
1609 debug("accepted new conn port %u on fd=%d\n",
1610 ntohs(cli_addr.sin_port), accept_fd);
1612 insert_wsi(context, new_wsi);
1615 * make sure NO events are seen yet on this new socket
1616 * (otherwise we inherit old fds[client].revents from
1617 * previous socket there and die mysteriously! )
1619 context->fds[context->fds_count].revents = 0;
1621 context->fds[context->fds_count].events = POLLIN;
1622 context->fds[context->fds_count++].fd = accept_fd;
1624 /* external POLL support via protocol 0 */
1625 context->protocols[0].callback(context, new_wsi,
1626 LWS_CALLBACK_ADD_POLL_FD,
1627 (void *)(long)accept_fd, NULL, POLLIN);
1631 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
1633 /* as we are listening, POLLIN means accept() is needed */
1635 if (!pollfd->revents & POLLIN)
1638 /* listen socket got an unencrypted connection... */
1640 clilen = sizeof(cli_addr);
1641 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1643 if (accept_fd < 0) {
1644 debug("ERROR on accept\n");
1648 if (context->fds_count >= MAX_CLIENTS) {
1649 fprintf(stderr, "too busy to accept new broadcast "
1652 closesocket(accept_fd);
1659 /* create a dummy wsi for the connection and add it */
1661 new_wsi = malloc(sizeof(struct libwebsocket));
1662 memset(new_wsi, 0, sizeof(struct libwebsocket));
1663 new_wsi->sock = accept_fd;
1664 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
1665 new_wsi->state = WSI_STATE_ESTABLISHED;
1666 new_wsi->count_active_extensions = 0;
1667 /* note which protocol we are proxying */
1668 new_wsi->protocol_index_for_broadcast_proxy =
1669 wsi->protocol_index_for_broadcast_proxy;
1670 insert_wsi(context, new_wsi);
1672 /* add connected socket to internal poll array */
1674 context->fds[context->fds_count].revents = 0;
1675 context->fds[context->fds_count].events = POLLIN;
1676 context->fds[context->fds_count++].fd = accept_fd;
1678 /* external POLL support via protocol 0 */
1679 context->protocols[0].callback(context, new_wsi,
1680 LWS_CALLBACK_ADD_POLL_FD,
1681 (void *)(long)accept_fd, NULL, POLLIN);
1685 case LWS_CONNMODE_BROADCAST_PROXY:
1687 /* handle session socket closed */
1689 if (pollfd->revents & (POLLERR | POLLHUP)) {
1691 debug("Session Socket %p (fd=%d) dead\n",
1692 (void *)wsi, pollfd->fd);
1694 libwebsocket_close_and_free_session(context, wsi,
1695 LWS_CLOSE_STATUS_NORMAL);
1700 * either extension code with stuff to spill, or the user code,
1701 * requested a callback when it was OK to write
1704 if (pollfd->revents & POLLOUT)
1705 if (lws_handle_POLLOUT_event(context, wsi,
1707 libwebsocket_close_and_free_session(
1708 context, wsi, LWS_CLOSE_STATUS_NORMAL);
1712 /* any incoming data ready? */
1714 if (!(pollfd->revents & POLLIN))
1717 /* get the issued broadcast payload from the socket */
1719 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
1720 MAX_BROADCAST_PAYLOAD);
1722 fprintf(stderr, "Error reading broadcast payload\n");
1726 /* broadcast it to all guys with this protocol index */
1728 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1730 for (m = 0; m < context->fd_hashtable[n].length; m++) {
1732 new_wsi = context->fd_hashtable[n].wsi[m];
1734 /* only to clients we are serving to */
1736 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
1740 * never broadcast to non-established
1744 if (new_wsi->state != WSI_STATE_ESTABLISHED)
1748 * only broadcast to connections using
1749 * the requested protocol
1752 if (new_wsi->protocol->protocol_index !=
1753 wsi->protocol_index_for_broadcast_proxy)
1756 /* broadcast it to this connection */
1758 new_wsi->protocol->callback(context, new_wsi,
1759 LWS_CALLBACK_BROADCAST,
1760 new_wsi->user_space,
1761 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
1766 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
1768 /* handle proxy hung up on us */
1770 if (pollfd->revents & (POLLERR | POLLHUP)) {
1772 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
1773 (void *)wsi, pollfd->fd);
1775 libwebsocket_close_and_free_session(context, wsi,
1776 LWS_CLOSE_STATUS_NOSTATUS);
1780 n = recv(wsi->sock, pkt, sizeof pkt, 0);
1782 libwebsocket_close_and_free_session(context, wsi,
1783 LWS_CLOSE_STATUS_NOSTATUS);
1784 fprintf(stderr, "ERROR reading from proxy socket\n");
1789 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
1790 libwebsocket_close_and_free_session(context, wsi,
1791 LWS_CLOSE_STATUS_NOSTATUS);
1792 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
1796 /* clear his proxy connection timeout */
1798 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1802 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
1804 #ifdef LWS_OPENSSL_SUPPORT
1805 if (wsi->use_ssl && !wsi->ssl) {
1807 wsi->ssl = SSL_new(context->ssl_client_ctx);
1808 wsi->client_bio = BIO_new_socket(wsi->sock,
1810 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
1812 SSL_set_ex_data(wsi->ssl,
1813 openssl_websocket_private_data_index,
1818 if (SSL_connect(wsi->ssl) <= 0) {
1821 * retry if new data comes until we
1822 * run into the connection timeout or win
1825 fprintf(stderr, "SSL connect error %s\n",
1826 ERR_error_string(ERR_get_error(),
1831 n = SSL_get_verify_result(wsi->ssl);
1832 if ((n != X509_V_OK) && (
1833 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
1834 wsi->use_ssl != 2)) {
1836 fprintf(stderr, "server's cert didn't "
1837 "look good %d\n", n);
1838 libwebsocket_close_and_free_session(context,
1839 wsi, LWS_CLOSE_STATUS_NOSTATUS);
1846 p = libwebsockets_generate_client_handshake(context, wsi, p);
1850 /* send our request to the server */
1852 #ifdef LWS_OPENSSL_SUPPORT
1854 n = SSL_write(wsi->ssl, pkt, p - pkt);
1857 n = send(wsi->sock, pkt, p - pkt, 0);
1860 fprintf(stderr, "ERROR writing to client socket\n");
1861 libwebsocket_close_and_free_session(context, wsi,
1862 LWS_CLOSE_STATUS_NOSTATUS);
1866 wsi->parser_state = WSI_TOKEN_NAME_PART;
1867 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
1868 libwebsocket_set_timeout(wsi,
1869 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
1873 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
1875 /* handle server hung up on us */
1877 if (pollfd->revents & (POLLERR | POLLHUP)) {
1879 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
1880 (void *)wsi, pollfd->fd);
1886 /* interpret the server response */
1889 * HTTP/1.1 101 Switching Protocols
1890 * Upgrade: websocket
1891 * Connection: Upgrade
1892 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
1893 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
1894 * Sec-WebSocket-Protocol: chat
1898 * we have to take some care here to only take from the
1899 * socket bytewise. The browser may (and has been seen to
1900 * in the case that onopen() performs websocket traffic)
1901 * coalesce both handshake response and websocket traffic
1902 * in one packet, since at that point the connection is
1903 * definitively ready from browser pov.
1907 while (wsi->parser_state != WSI_PARSING_COMPLETE && len > 0) {
1908 #ifdef LWS_OPENSSL_SUPPORT
1910 len = SSL_read(wsi->ssl, &c, 1);
1913 len = recv(wsi->sock, &c, 1, 0);
1915 libwebsocket_parse(wsi, c);
1919 * hs may also be coming in multiple packets, there is a 5-sec
1920 * libwebsocket timeout still active here too, so if parsing did
1921 * not complete just wait for next packet coming in this state
1924 if (wsi->parser_state != WSI_PARSING_COMPLETE)
1928 * otherwise deal with the handshake. If there's any
1929 * packet traffic already arrived we'll trigger poll() again
1930 * right away and deal with it that way
1933 return lws_client_interpret_server_handshake(context, wsi);
1936 if (wsi->c_protocol)
1937 free(wsi->c_protocol);
1938 libwebsocket_close_and_free_session(context, wsi,
1939 LWS_CLOSE_STATUS_NOSTATUS);
1942 case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
1944 "LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT\n");
1947 case LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD:
1949 "LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD\n");
1953 case LWS_CONNMODE_WS_SERVING:
1954 case LWS_CONNMODE_WS_CLIENT:
1956 /* handle session socket closed */
1958 if (pollfd->revents & (POLLERR | POLLHUP)) {
1960 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1961 (void *)wsi, pollfd->fd);
1963 libwebsocket_close_and_free_session(context, wsi,
1964 LWS_CLOSE_STATUS_NOSTATUS);
1968 /* the guy requested a callback when it was OK to write */
1970 if ((pollfd->revents & POLLOUT) &&
1971 wsi->state == WSI_STATE_ESTABLISHED)
1972 if (lws_handle_POLLOUT_event(context, wsi,
1974 libwebsocket_close_and_free_session(
1975 context, wsi, LWS_CLOSE_STATUS_NORMAL);
1980 /* any incoming data ready? */
1982 if (!(pollfd->revents & POLLIN))
1985 #ifdef LWS_OPENSSL_SUPPORT
1987 eff_buf.token_len = SSL_read(wsi->ssl, buf, sizeof buf);
1991 recv(pollfd->fd, buf, sizeof buf, 0);
1993 if (eff_buf.token_len < 0) {
1994 fprintf(stderr, "Socket read returned %d\n",
1997 libwebsocket_close_and_free_session(context,
1998 wsi, LWS_CLOSE_STATUS_NOSTATUS);
2001 if (!eff_buf.token_len) {
2002 libwebsocket_close_and_free_session(context, wsi,
2003 LWS_CLOSE_STATUS_NOSTATUS);
2008 * give any active extensions a chance to munge the buffer
2009 * before parse. We pass in a pointer to an lws_tokens struct
2010 * prepared with the default buffer and content length that's in
2011 * there. Rather than rewrite the default buffer, extensions
2012 * that expect to grow the buffer can adapt .token to
2013 * point to their own per-connection buffer in the extension
2014 * user allocation. By default with no extensions or no
2015 * extension callback handling, just the normal input buffer is
2016 * used then so it is efficient.
2019 eff_buf.token = (char *)buf;
2026 for (n = 0; n < wsi->count_active_extensions; n++) {
2027 m = wsi->active_extensions[n]->callback(context,
2028 wsi->active_extensions[n], wsi,
2029 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
2030 wsi->active_extensions_user[n],
2034 "Extension reports fatal error\n");
2035 libwebsocket_close_and_free_session(
2037 LWS_CLOSE_STATUS_NOSTATUS);
2044 /* service incoming data */
2046 if (eff_buf.token_len) {
2047 n = libwebsocket_read(context, wsi,
2048 (unsigned char *)eff_buf.token,
2055 eff_buf.token = NULL;
2056 eff_buf.token_len = 0;
2066 * libwebsocket_context_destroy() - Destroy the websocket context
2067 * @context: Websocket context
2069 * This function closes any active connections and then frees the
2070 * context. After calling this, any further use of the context is
2074 libwebsocket_context_destroy(struct libwebsocket_context *context)
2078 struct libwebsocket *wsi;
2079 struct libwebsocket_extension *ext;
2081 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
2082 for (m = 0; m < context->fd_hashtable[n].length; m++) {
2083 wsi = context->fd_hashtable[n].wsi[m];
2084 libwebsocket_close_and_free_session(context, wsi,
2085 LWS_CLOSE_STATUS_GOINGAWAY);
2089 * give all extensions a chance to clean up any per-context
2090 * allocations they might have made
2093 ext = context->extensions;
2094 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
2095 if (context->listen_port)
2096 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
2097 while (ext && ext->callback) {
2098 ext->callback(context, ext, NULL, m, NULL, NULL, 0);
2104 close(context->fd_random);
2107 #ifdef LWS_OPENSSL_SUPPORT
2108 if (context->ssl_ctx)
2109 SSL_CTX_free(context->ssl_ctx);
2110 if (context->ssl_client_ctx)
2111 SSL_CTX_free(context->ssl_client_ctx);
2122 libwebsocket_context_user(struct libwebsocket_context *context)
2124 return context->user_space;
2128 * libwebsocket_service() - Service any pending websocket activity
2129 * @context: Websocket context
2130 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2131 * service otherwise block and service immediately, returning
2132 * after the timeout if nothing needed service.
2134 * This function deals with any pending websocket traffic, for three
2135 * kinds of event. It handles these events on both server and client
2136 * types of connection the same.
2138 * 1) Accept new connections to our context's server
2140 * 2) Perform pending broadcast writes initiated from other forked
2141 * processes (effectively serializing asynchronous broadcasts)
2143 * 3) Call the receive callback for incoming frame data received by
2144 * server or client connections.
2146 * You need to call this service function periodically to all the above
2147 * functions to happen; if your application is single-threaded you can
2148 * just call it in your main event loop.
2150 * Alternatively you can fork a new process that asynchronously handles
2151 * calling this service in a loop. In that case you are happy if this
2152 * call blocks your thread until it needs to take care of something and
2153 * would call it with a large nonzero timeout. Your loop then takes no
2154 * CPU while there is nothing happening.
2156 * If you are calling it in a single-threaded app, you don't want it to
2157 * wait around blocking other things in your loop from happening, so you
2158 * would call it with a timeout_ms of 0, so it returns immediately if
2159 * nothing is pending, or as soon as it services whatever was pending.
2164 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
2168 /* stay dead once we are dead */
2170 if (context == NULL)
2173 /* wait for something to need service */
2175 n = poll(context->fds, context->fds_count, timeout_ms);
2176 if (n == 0) /* poll timeout */
2181 fprintf(stderr, "Listen Socket dead\n");
2186 /* handle accept on listening socket? */
2188 for (n = 0; n < context->fds_count; n++)
2189 if (context->fds[n].revents)
2190 if (libwebsocket_service_fd(context,
2191 &context->fds[n]) < 0)
2197 lws_any_extension_handled(struct libwebsocket_context *context,
2198 struct libwebsocket *wsi,
2199 enum libwebsocket_extension_callback_reasons r,
2200 void *v, size_t len)
2205 /* maybe an extension will take care of it for us */
2207 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
2208 if (!wsi->active_extensions[n]->callback)
2211 handled |= wsi->active_extensions[n]->callback(context,
2212 wsi->active_extensions[n], wsi,
2213 r, wsi->active_extensions_user[n], v, len);
2221 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
2222 struct libwebsocket_extension *ext)
2229 while (n < wsi->count_active_extensions) {
2230 if (wsi->active_extensions[n] != ext) {
2234 return wsi->active_extensions_user[n];
2241 * libwebsocket_callback_on_writable() - Request a callback when this socket
2242 * becomes able to be written to without
2245 * @context: libwebsockets context
2246 * @wsi: Websocket connection instance to get callback for
2250 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
2251 struct libwebsocket *wsi)
2256 /* maybe an extension will take care of it for us */
2258 for (n = 0; n < wsi->count_active_extensions; n++) {
2259 if (!wsi->active_extensions[n]->callback)
2262 handled |= wsi->active_extensions[n]->callback(context,
2263 wsi->active_extensions[n], wsi,
2264 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
2265 wsi->active_extensions_user[n], NULL, 0);
2271 for (n = 0; n < context->fds_count; n++)
2272 if (context->fds[n].fd == wsi->sock) {
2273 context->fds[n].events |= POLLOUT;
2274 n = context->fds_count + 1;
2277 if (n == context->fds_count)
2278 fprintf(stderr, "libwebsocket_callback_on_writable: "
2279 "failed to find socket %d\n", wsi->sock);
2281 /* external POLL support via protocol 0 */
2282 context->protocols[0].callback(context, wsi,
2283 LWS_CALLBACK_SET_MODE_POLL_FD,
2284 (void *)(long)wsi->sock, NULL, POLLOUT);
2290 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
2291 * all connections using the given protocol when it
2292 * becomes possible to write to each socket without
2295 * @protocol: Protocol whose connections will get callbacks
2299 libwebsocket_callback_on_writable_all_protocol(
2300 const struct libwebsocket_protocols *protocol)
2302 struct libwebsocket_context *context = protocol->owning_server;
2305 struct libwebsocket *wsi;
2307 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
2309 for (m = 0; m < context->fd_hashtable[n].length; m++) {
2311 wsi = context->fd_hashtable[n].wsi[m];
2313 if (wsi->protocol == protocol)
2314 libwebsocket_callback_on_writable(context, wsi);
2322 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
2324 * You will not need this unless you are doing something special
2326 * @wsi: Websocket connection instance
2327 * @reason: timeout reason
2328 * @secs: how many seconds
2332 libwebsocket_set_timeout(struct libwebsocket *wsi,
2333 enum pending_timeout reason, int secs)
2337 gettimeofday(&tv, NULL);
2339 wsi->pending_timeout_limit = tv.tv_sec + secs;
2340 wsi->pending_timeout = reason;
2345 * libwebsocket_get_socket_fd() - returns the socket file descriptor
2347 * You will not need this unless you are doing something special
2349 * @wsi: Websocket connection instance
2353 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
2359 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
2360 * receieved packets.
2362 * If the output side of a server process becomes choked, this allows flow
2363 * control for the input side.
2365 * @wsi: Websocket connection instance to get callback for
2366 * @enable: 0 = disable read servicing for this connection, 1 = enable
2370 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
2372 struct libwebsocket_context *context = wsi->protocol->owning_server;
2375 for (n = 0; n < context->fds_count; n++)
2376 if (context->fds[n].fd == wsi->sock) {
2378 context->fds[n].events |= POLLIN;
2380 context->fds[n].events &= ~POLLIN;
2386 /* external POLL support via protocol 0 */
2387 context->protocols[0].callback(context, wsi,
2388 LWS_CALLBACK_SET_MODE_POLL_FD,
2389 (void *)(long)wsi->sock, NULL, POLLIN);
2391 /* external POLL support via protocol 0 */
2392 context->protocols[0].callback(context, wsi,
2393 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
2394 (void *)(long)wsi->sock, NULL, POLLIN);
2397 fprintf(stderr, "libwebsocket_rx_flow_control "
2398 "unable to find socket\n");
2404 * libwebsocket_canonical_hostname() - returns this host's hostname
2406 * This is typically used by client code to fill in the host parameter
2407 * when making a client connection. You can only call it after the context
2410 * @context: Websocket context
2415 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
2417 return (const char *)context->canonical_hostname;
2421 static void sigpipe_handler(int x)
2425 #ifdef LWS_OPENSSL_SUPPORT
2427 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
2432 struct libwebsocket_context *context;
2434 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
2435 SSL_get_ex_data_X509_STORE_CTX_idx());
2438 * !!! nasty openssl requires the index to come as a library-scope
2441 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
2443 n = context->protocols[0].callback(NULL, NULL,
2444 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
2445 x509_ctx, ssl, preverify_ok);
2447 /* convert return code from 0 = OK to 1 = OK */
2460 * libwebsocket_create_context() - Create the websocket handler
2461 * @port: Port to listen on... you can use 0 to suppress listening on
2462 * any port, that's what you want if you are not running a
2463 * websocket server at all but just using it as a client
2464 * @interf: NULL to bind the listen socket to all interfaces, or the
2465 * interface name, eg, "eth2"
2466 * @protocols: Array of structures listing supported protocols and a protocol-
2467 * specific callback for each one. The list is ended with an
2468 * entry that has a NULL callback pointer.
2469 * It's not const because we write the owning_server member
2470 * @extensions: NULL or array of libwebsocket_extension structs listing the
2471 * extensions this context supports
2472 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
2473 * to listen using SSL, set to the filepath to fetch the
2474 * server cert from, otherwise NULL for unencrypted
2475 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
2477 * @gid: group id to change to after setting listen socket, or -1.
2478 * @uid: user id to change to after setting listen socket, or -1.
2479 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
2481 * This function creates the listening socket and takes care
2482 * of all initialization in one step.
2484 * After initialization, it returns a struct libwebsocket_context * that
2485 * represents this server. After calling, user code needs to take care
2486 * of calling libwebsocket_service() with the context pointer to get the
2487 * server's sockets serviced. This can be done in the same process context
2488 * or a forked process, or another thread,
2490 * The protocol callback functions are called for a handful of events
2491 * including http requests coming in, websocket connections becoming
2492 * established, and data arriving; it's also called periodically to allow
2493 * async transmission.
2495 * HTTP requests are sent always to the FIRST protocol in @protocol, since
2496 * at that time websocket protocol has not been negotiated. Other
2497 * protocols after the first one never see any HTTP callack activity.
2499 * The server created is a simple http server by default; part of the
2500 * websocket standard is upgrading this http connection to a websocket one.
2502 * This allows the same server to provide files like scripts and favicon /
2503 * images or whatever over http and dynamic data over websockets all in
2504 * one place; they're all handled in the user callback.
2507 struct libwebsocket_context *
2508 libwebsocket_create_context(int port, const char *interf,
2509 struct libwebsocket_protocols *protocols,
2510 struct libwebsocket_extension *extensions,
2511 const char *ssl_cert_filepath,
2512 const char *ssl_private_key_filepath,
2513 int gid, int uid, unsigned int options,
2520 struct sockaddr_in serv_addr, cli_addr;
2522 struct libwebsocket_context *context = NULL;
2525 char hostname[1024] = "";
2526 // struct hostent *he;
2527 struct libwebsocket *wsi;
2530 #ifdef LWS_OPENSSL_SUPPORT
2532 char ssl_err_buf[512];
2537 WORD wVersionRequested;
2542 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
2543 wVersionRequested = MAKEWORD(2, 2);
2545 err = WSAStartup(wVersionRequested, &wsaData);
2547 /* Tell the user that we could not find a usable */
2549 fprintf(stderr, "WSAStartup failed with error: %d\n",
2554 /* default to a poll() made out of select() */
2555 poll = emulated_poll;
2557 /* if windows socket lib available, use his WSAPoll */
2558 wsdll = GetModuleHandle("Ws2_32.dll");
2560 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
2565 context = malloc(sizeof(struct libwebsocket_context));
2567 fprintf(stderr, "No memory for websocket context\n");
2570 context->protocols = protocols;
2571 context->listen_port = port;
2572 context->http_proxy_port = 0;
2573 context->http_proxy_address[0] = '\0';
2574 context->options = options;
2575 context->fds_count = 0;
2576 context->extensions = extensions;
2577 context->last_timeout_check_s = 0;
2578 context->user_space = user;
2581 context->fd_random = 0;
2583 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
2584 if (context->fd_random < 0) {
2585 fprintf(stderr, "Unable to open random device %s %d\n",
2586 SYSTEM_RANDOM_FILEPATH, context->fd_random);
2591 #ifdef LWS_OPENSSL_SUPPORT
2592 context->use_ssl = 0;
2593 context->ssl_ctx = NULL;
2594 context->ssl_client_ctx = NULL;
2595 openssl_websocket_private_data_index = 0;
2597 /* find canonical hostname */
2599 hostname[(sizeof hostname) - 1] = '\0';
2600 memset(&sa, 0, sizeof(sa));
2601 sa.sa_family = AF_INET;
2602 sa.sa_data[(sizeof sa.sa_data) - 1] = '\0';
2603 gethostname(hostname, (sizeof hostname) - 1);
2607 if (strlen(hostname) < sizeof(sa.sa_data) - 1) {
2608 strcpy(sa.sa_data, hostname);
2609 // fprintf(stderr, "my host name is %s\n", sa.sa_data);
2610 n = getnameinfo(&sa, sizeof(sa), hostname,
2611 (sizeof hostname) - 1, NULL, 0, 0);
2615 strncpy(context->canonical_hostname, hostname,
2616 sizeof context->canonical_hostname - 1);
2617 context->canonical_hostname[
2618 sizeof context->canonical_hostname - 1] = '\0';
2620 strncpy(context->canonical_hostname, hostname,
2621 sizeof context->canonical_hostname - 1);
2623 // fprintf(stderr, "context->canonical_hostname = %s\n",
2624 // context->canonical_hostname);
2626 /* split the proxy ads:port if given */
2628 p = getenv("http_proxy");
2630 strncpy(context->http_proxy_address, p,
2631 sizeof context->http_proxy_address - 1);
2632 context->http_proxy_address[
2633 sizeof context->http_proxy_address - 1] = '\0';
2635 p = strchr(context->http_proxy_address, ':');
2637 fprintf(stderr, "http_proxy needs to be ads:port\n");
2641 context->http_proxy_port = atoi(p + 1);
2643 fprintf(stderr, "Using proxy %s:%u\n",
2644 context->http_proxy_address,
2645 context->http_proxy_port);
2650 #ifdef LWS_OPENSSL_SUPPORT
2651 context->use_ssl = ssl_cert_filepath != NULL &&
2652 ssl_private_key_filepath != NULL;
2653 if (context->use_ssl)
2654 fprintf(stderr, " Compiled with SSL support, "
2657 fprintf(stderr, " Compiled with SSL support, "
2661 if (ssl_cert_filepath != NULL &&
2662 ssl_private_key_filepath != NULL) {
2663 fprintf(stderr, " Not compiled for OpenSSl support!\n");
2666 fprintf(stderr, " Compiled without SSL support, "
2667 "serving unencrypted\n");
2671 /* ignore SIGPIPE */
2674 signal(SIGPIPE, sigpipe_handler);
2678 #ifdef LWS_OPENSSL_SUPPORT
2680 /* basic openssl init */
2684 OpenSSL_add_all_algorithms();
2685 SSL_load_error_strings();
2687 openssl_websocket_private_data_index =
2688 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
2691 * Firefox insists on SSLv23 not SSLv3
2692 * Konq disables SSLv2 by default now, SSLv23 works
2695 method = (SSL_METHOD *)SSLv23_server_method();
2697 fprintf(stderr, "problem creating ssl method: %s\n",
2698 ERR_error_string(ERR_get_error(), ssl_err_buf));
2701 context->ssl_ctx = SSL_CTX_new(method); /* create context */
2702 if (!context->ssl_ctx) {
2703 fprintf(stderr, "problem creating ssl context: %s\n",
2704 ERR_error_string(ERR_get_error(), ssl_err_buf));
2708 /* client context */
2710 if (port == CONTEXT_PORT_NO_LISTEN) {
2711 method = (SSL_METHOD *)SSLv23_client_method();
2713 fprintf(stderr, "problem creating ssl method: %s\n",
2714 ERR_error_string(ERR_get_error(), ssl_err_buf));
2717 /* create context */
2718 context->ssl_client_ctx = SSL_CTX_new(method);
2719 if (!context->ssl_client_ctx) {
2720 fprintf(stderr, "problem creating ssl context: %s\n",
2721 ERR_error_string(ERR_get_error(), ssl_err_buf));
2725 /* openssl init for cert verification (for client sockets) */
2727 if (!SSL_CTX_load_verify_locations(
2728 context->ssl_client_ctx, NULL,
2729 LWS_OPENSSL_CLIENT_CERTS))
2731 "Unable to load SSL Client certs from %s "
2732 "(set by --with-client-cert-dir= in configure) -- "
2733 " client ssl isn't going to work",
2734 LWS_OPENSSL_CLIENT_CERTS);
2737 * callback allowing user code to load extra verification certs
2738 * helping the client to verify server identity
2741 context->protocols[0].callback(context, NULL,
2742 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
2743 context->ssl_client_ctx, NULL, 0);
2746 /* as a server, are we requiring clients to identify themselves? */
2748 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
2750 /* absolutely require the client cert */
2752 SSL_CTX_set_verify(context->ssl_ctx,
2753 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2754 OpenSSL_verify_callback);
2757 * give user code a chance to load certs into the server
2758 * allowing it to verify incoming client certs
2761 context->protocols[0].callback(context, NULL,
2762 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
2763 context->ssl_ctx, NULL, 0);
2766 if (context->use_ssl) {
2768 /* openssl init for server sockets */
2770 /* set the local certificate from CertFile */
2771 n = SSL_CTX_use_certificate_file(context->ssl_ctx,
2772 ssl_cert_filepath, SSL_FILETYPE_PEM);
2774 fprintf(stderr, "problem getting cert '%s': %s\n",
2776 ERR_error_string(ERR_get_error(), ssl_err_buf));
2779 /* set the private key from KeyFile */
2780 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2781 ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
2782 fprintf(stderr, "ssl problem getting key '%s': %s\n",
2783 ssl_private_key_filepath,
2784 ERR_error_string(ERR_get_error(), ssl_err_buf));
2787 /* verify private key */
2788 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
2789 fprintf(stderr, "Private SSL key doesn't match cert\n");
2793 /* SSL is happy and has a cert it's content with */
2799 if (lws_b64_selftest())
2802 /* fd hashtable init */
2804 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
2805 context->fd_hashtable[n].length = 0;
2807 /* set up our external listening socket we serve on */
2811 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2813 fprintf(stderr, "ERROR opening socket");
2817 /* allow us to restart even if old sockets in TIME_WAIT */
2818 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2819 (const void *)&opt, sizeof(opt));
2823 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2824 (const void *)&opt, sizeof(opt));
2826 bzero((char *) &serv_addr, sizeof(serv_addr));
2827 serv_addr.sin_family = AF_INET;
2829 serv_addr.sin_addr.s_addr = INADDR_ANY;
2831 interface_to_sa(interf, &serv_addr,
2833 serv_addr.sin_port = htons(port);
2835 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2838 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2843 wsi = malloc(sizeof(struct libwebsocket));
2844 memset(wsi, 0, sizeof(struct libwebsocket));
2846 wsi->count_active_extensions = 0;
2847 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2848 insert_wsi(context, wsi);
2851 fprintf(stderr, " Listening on port %d\n", port);
2853 /* list in the internal poll array */
2855 context->fds[context->fds_count].fd = sockfd;
2856 context->fds[context->fds_count++].events = POLLIN;
2858 /* external POLL support via protocol 0 */
2859 context->protocols[0].callback(context, wsi,
2860 LWS_CALLBACK_ADD_POLL_FD,
2861 (void *)(long)sockfd, NULL, POLLIN);
2866 * drop any root privs for this process
2867 * to listen on port < 1023 we would have needed root, but now we are
2868 * listening, we don't want the power for anything else
2874 fprintf(stderr, "setgid: %s\n", strerror(errno));
2877 fprintf(stderr, "setuid: %s\n", strerror(errno));
2880 /* set up our internal broadcast trigger sockets per-protocol */
2882 for (context->count_protocols = 0;
2883 protocols[context->count_protocols].callback;
2884 context->count_protocols++) {
2886 debug(" Protocol: %s\n", protocols[context->count_protocols].name);
2888 protocols[context->count_protocols].owning_server = context;
2889 protocols[context->count_protocols].protocol_index =
2890 context->count_protocols;
2892 fd = socket(AF_INET, SOCK_STREAM, 0);
2894 fprintf(stderr, "ERROR opening socket");
2898 /* allow us to restart even if old sockets in TIME_WAIT */
2899 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt,
2902 bzero((char *) &serv_addr, sizeof(serv_addr));
2903 serv_addr.sin_family = AF_INET;
2904 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2905 serv_addr.sin_port = 0; /* pick the port for us */
2907 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2909 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2914 slen = sizeof cli_addr;
2915 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2917 fprintf(stderr, "getsockname failed\n");
2920 protocols[context->count_protocols].broadcast_socket_port =
2921 ntohs(cli_addr.sin_port);
2924 debug(" Protocol %s broadcast socket %d\n",
2925 protocols[context->count_protocols].name,
2926 ntohs(cli_addr.sin_port));
2928 /* dummy wsi per broadcast proxy socket */
2930 wsi = malloc(sizeof(struct libwebsocket));
2931 memset(wsi, 0, sizeof(struct libwebsocket));
2933 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
2934 wsi->count_active_extensions = 0;
2935 /* note which protocol we are proxying */
2936 wsi->protocol_index_for_broadcast_proxy =
2937 context->count_protocols;
2938 insert_wsi(context, wsi);
2940 /* list in internal poll array */
2942 context->fds[context->fds_count].fd = fd;
2943 context->fds[context->fds_count].events = POLLIN;
2944 context->fds[context->fds_count].revents = 0;
2945 context->fds_count++;
2947 /* external POLL support via protocol 0 */
2948 context->protocols[0].callback(context, wsi,
2949 LWS_CALLBACK_ADD_POLL_FD,
2950 (void *)(long)fd, NULL, POLLIN);
2954 * give all extensions a chance to create any per-context
2955 * allocations they need
2958 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2960 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
2963 while (extensions->callback) {
2964 debug(" Extension: %s\n", extensions->name);
2965 extensions->callback(context, extensions,
2966 NULL, m, NULL, NULL, 0);
2978 * libwebsockets_fork_service_loop() - Optional helper function forks off
2979 * a process for the websocket server loop.
2980 * You don't have to use this but if not, you
2981 * have to make sure you are calling
2982 * libwebsocket_service periodically to service
2983 * the websocket traffic
2984 * @context: server context returned by creation function
2988 libwebsockets_fork_service_loop(struct libwebsocket_context *context)
2991 struct sockaddr_in cli_addr;
3001 /* main process context */
3004 * set up the proxy sockets to allow broadcast from
3005 * service process context
3008 for (p = 0; p < context->count_protocols; p++) {
3009 fd = socket(AF_INET, SOCK_STREAM, 0);
3011 fprintf(stderr, "Unable to create socket\n");
3014 cli_addr.sin_family = AF_INET;
3015 cli_addr.sin_port = htons(
3016 context->protocols[p].broadcast_socket_port);
3017 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
3018 n = connect(fd, (struct sockaddr *)&cli_addr,
3021 fprintf(stderr, "Unable to connect to "
3022 "broadcast socket %d, %s\n",
3023 n, strerror(errno));
3027 context->protocols[p].broadcast_socket_user_fd = fd;
3033 #ifdef HAVE_SYS_PRCTL_H
3034 /* we want a SIGHUP when our parent goes down */
3035 prctl(PR_SET_PDEATHSIG, SIGHUP);
3038 /* in this forked process, sit and service websocket connections */
3041 if (libwebsocket_service(context, 1000))
3043 //#ifndef HAVE_SYS_PRCTL_H
3045 * on systems without prctl() (i.e. anything but linux) we can notice that our
3046 * parent is dead if getppid() returns 1. FIXME apparently this is not true for
3047 * solaris, could remember ppid right after fork and wait for it to change.
3062 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
3064 * @wsi: pointer to struct websocket you want to know the protocol of
3067 * This is useful to get the protocol to broadcast back to from inside
3071 const struct libwebsocket_protocols *
3072 libwebsockets_get_protocol(struct libwebsocket *wsi)
3074 return wsi->protocol;
3078 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
3079 * connections of the given protocol.
3080 * @protocol: pointer to the protocol you will broadcast to all members of
3081 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
3082 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
3083 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
3084 * case you are calling this function from callback context.
3085 * @len: length of payload data in buf, starting from buf.
3087 * This function allows bulk sending of a packet to every connection using
3088 * the given protocol. It does not send the data directly; instead it calls
3089 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
3090 * wants to actually send the data for that connection, the callback itself
3091 * should call libwebsocket_write().
3093 * libwebsockets_broadcast() can be called from another fork context without
3094 * having to take any care about data visibility between the processes, it'll
3100 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
3101 unsigned char *buf, size_t len)
3103 struct libwebsocket_context *context = protocol->owning_server;
3106 struct libwebsocket *wsi;
3108 if (!protocol->broadcast_socket_user_fd) {
3110 * We are either running unforked / flat, or we are being
3111 * called from poll thread context
3112 * eg, from a callback. In that case don't use sockets for
3113 * broadcast IPC (since we can't open a socket connection to
3114 * a socket listening on our own thread) but directly do the
3117 * Locking is not needed because we are by definition being
3118 * called in the poll thread context and are serialized.
3121 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
3123 for (m = 0; m < context->fd_hashtable[n].length; m++) {
3125 wsi = context->fd_hashtable[n].wsi[m];
3127 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
3131 * never broadcast to
3132 * non-established connections
3134 if (wsi->state != WSI_STATE_ESTABLISHED)
3137 /* only broadcast to guys using
3138 * requested protocol
3140 if (wsi->protocol != protocol)
3143 wsi->protocol->callback(context, wsi,
3144 LWS_CALLBACK_BROADCAST,
3154 * We're being called from a different process context than the server
3155 * loop. Instead of broadcasting directly, we send our
3156 * payload on a socket to do the IPC; the server process will serialize
3157 * the broadcast action in its main poll() loop.
3159 * There's one broadcast socket listening for each protocol supported
3160 * set up when the websocket server initializes
3163 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
3169 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
3175 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
3177 /* allocate the per-connection user memory (if any) */
3179 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
3180 wsi->user_space = malloc(
3181 wsi->protocol->per_session_data_size);
3182 if (wsi->user_space == NULL) {
3183 fprintf(stderr, "Out of memory for "
3184 "conn user space\n");
3187 memset(wsi->user_space, 0,
3188 wsi->protocol->per_session_data_size);
3190 return wsi->user_space;