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"
30 #include <sys/socket.h>
34 #ifdef LWS_OPENSSL_SUPPORT
35 int openssl_websocket_private_data_index;
39 #include "../win32port/win32helpers/websock-w32.c"
42 #include "../win32port/win32helpers/websock-w32.c"
47 * In-place str to lower case
59 /* file descriptor hash management */
62 wsi_from_fd(struct libwebsocket_context *context, int fd)
64 int h = LWS_FD_HASH(fd);
67 for (n = 0; n < context->fd_hashtable[h].length; n++)
68 if (context->fd_hashtable[h].wsi[n]->sock == fd)
69 return context->fd_hashtable[h].wsi[n];
75 insert_wsi(struct libwebsocket_context *context, struct libwebsocket *wsi)
77 int h = LWS_FD_HASH(wsi->sock);
79 if (context->fd_hashtable[h].length == MAX_CLIENTS - 1) {
80 fprintf(stderr, "hash table overflow\n");
84 context->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;
90 delete_from_fd(struct libwebsocket_context *context, int fd)
92 int h = LWS_FD_HASH(fd);
95 for (n = 0; n < context->fd_hashtable[h].length; n++)
96 if (context->fd_hashtable[h].wsi[n]->sock == fd) {
97 while (n < context->fd_hashtable[h].length) {
98 context->fd_hashtable[h].wsi[n] =
99 context->fd_hashtable[h].wsi[n + 1];
102 context->fd_hashtable[h].length--;
107 fprintf(stderr, "Failed to find fd %d requested for "
108 "delete in hashtable\n", fd);
112 #ifdef LWS_OPENSSL_SUPPORT
114 libwebsockets_decode_ssl_error(void)
119 while ((err = ERR_get_error()) != 0) {
120 ERR_error_string_n(err, buf, sizeof(buf));
121 fprintf(stderr, "*** %s\n", buf);
128 interface_to_sa(const char *ifname, struct sockaddr_in *addr, size_t addrlen)
136 struct sockaddr_in *sin;
139 for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
140 if (strcmp(ifc->ifa_name, ifname))
142 if (ifc->ifa_addr == NULL)
144 sin = (struct sockaddr_in *)ifc->ifa_addr;
145 if (sin->sin_family != AF_INET)
147 memcpy(addr, sin, addrlen);
157 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
158 struct libwebsocket *wsi, enum lws_close_status reason)
162 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
163 LWS_SEND_BUFFER_POST_PADDING];
166 struct lws_tokens eff_buf;
167 struct libwebsocket_extension *ext;
172 old_state = wsi->state;
174 if (old_state == WSI_STATE_DEAD_SOCKET)
177 wsi->close_reason = reason;
180 * are his extensions okay with him closing? Eg he might be a mux
181 * parent and just his ch1 aspect is closing?
185 for (n = 0; n < wsi->count_active_extensions; n++) {
186 if (!wsi->active_extensions[n]->callback)
189 m = wsi->active_extensions[n]->callback(context,
190 wsi->active_extensions[n], wsi,
191 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
192 wsi->active_extensions_user[n], NULL, 0);
195 * if somebody vetoed actually closing him at this time....
196 * up to the extension to track the attempted close, let's
201 debug("extension vetoed close\n");
209 * flush any tx pending from extensions, since we may send close packet
210 * if there are problems with send, just nuke the connection
216 /* default to nobody has more to spill */
219 eff_buf.token = NULL;
220 eff_buf.token_len = 0;
222 /* show every extension the new incoming data */
224 for (n = 0; n < wsi->count_active_extensions; n++) {
225 m = wsi->active_extensions[n]->callback(
226 wsi->protocol->owning_server,
227 wsi->active_extensions[n], wsi,
228 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
229 wsi->active_extensions_user[n], &eff_buf, 0);
231 fprintf(stderr, "Extension reports "
233 goto just_kill_connection;
237 * at least one extension told us he has more
238 * to spill, so we will go around again after
243 /* assuming they left us something to send, send it */
245 if (eff_buf.token_len)
246 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
248 goto just_kill_connection;
252 * signal we are closing, libsocket_write will
253 * add any necessary version-specific stuff. If the write fails,
254 * no worries we are closing anyway. If we didn't initiate this
255 * close, then our state has been changed to
256 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
258 * Likewise if it's a second call to close this connection after we
259 * sent the close indication to the peer already, we are in state
260 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
263 if (old_state == WSI_STATE_ESTABLISHED &&
264 reason != LWS_CLOSE_STATUS_NOSTATUS) {
266 debug("sending close indication...\n");
268 n = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
272 * we have sent a nice protocol level indication we
273 * now wish to close, we should not send anything more
276 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
278 /* and we should wait for a reply for a bit */
280 libwebsocket_set_timeout(wsi,
281 PENDING_TIMEOUT_CLOSE_ACK, AWAITING_TIMEOUT);
283 debug("sent close indication, awaiting ack\n");
288 /* else, the send failed and we should just hang up */
291 just_kill_connection:
293 debug("libwebsocket_close_and_free_session: just_kill_connection\n");
296 * we won't be servicing or receiving anything further from this guy
297 * remove this fd from wsi mapping hashtable
301 delete_from_fd(context, wsi->sock);
303 /* delete it from the internal poll list if still present */
305 for (n = 0; n < context->fds_count; n++) {
306 if (context->fds[n].fd != wsi->sock)
308 while (n < context->fds_count - 1) {
309 context->fds[n] = context->fds[n + 1];
312 context->fds_count--;
313 /* we only have to deal with one */
314 n = context->fds_count;
317 /* remove also from external POLL support via protocol 0 */
319 context->protocols[0].callback(context, wsi,
320 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
322 wsi->state = WSI_STATE_DEAD_SOCKET;
324 /* tell the user it's all over for this guy */
326 if (wsi->protocol && wsi->protocol->callback &&
327 ((old_state == WSI_STATE_ESTABLISHED) ||
328 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
329 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
330 debug("calling back CLOSED\n");
331 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
332 wsi->user_space, NULL, 0);
334 debug("not calling back closed, old_state=%d\n", old_state);
336 /* deallocate any active extension contexts */
338 for (n = 0; n < wsi->count_active_extensions; n++) {
339 if (!wsi->active_extensions[n]->callback)
342 wsi->active_extensions[n]->callback(context,
343 wsi->active_extensions[n], wsi,
344 LWS_EXT_CALLBACK_DESTROY,
345 wsi->active_extensions_user[n], NULL, 0);
347 free(wsi->active_extensions_user[n]);
351 * inform all extensions in case they tracked this guy out of band
352 * even though not active on him specifically
355 ext = context->extensions;
356 while (ext && ext->callback) {
357 ext->callback(context, ext, wsi,
358 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
363 /* free up his parsing allocations */
365 for (n = 0; n < WSI_TOKEN_COUNT; n++)
366 if (wsi->utf8_token[n].token)
367 free(wsi->utf8_token[n].token);
370 free(wsi->c_address);
372 /* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
374 #ifdef LWS_OPENSSL_SUPPORT
376 n = SSL_get_fd(wsi->ssl);
377 SSL_shutdown(wsi->ssl);
386 shutdown(wsi->sock, SHUT_RDWR);
389 closesocket(wsi->sock);
394 #ifdef LWS_OPENSSL_SUPPORT
397 if (wsi->protocol && wsi->protocol->per_session_data_size && wsi->user_space) /* user code may own */
398 free(wsi->user_space);
404 * libwebsockets_hangup_on_client() - Server calls to terminate client
406 * @context: libwebsockets context
407 * @fd: Connection socket descriptor
411 libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
413 struct libwebsocket *wsi = wsi_from_fd(context, fd);
418 libwebsocket_close_and_free_session(context, wsi,
419 LWS_CLOSE_STATUS_NOSTATUS);
424 * libwebsockets_get_peer_addresses() - Get client address information
425 * @fd: Connection socket descriptor
426 * @name: Buffer to take client address name
427 * @name_len: Length of client address name buffer
428 * @rip: Buffer to take client address IP qotted quad
429 * @rip_len: Length of client address IP buffer
431 * This function fills in @name and @rip with the name and IP of
432 * the client connected with socket descriptor @fd. Names may be
433 * truncated if there is not enough room. If either cannot be
434 * determined, they will be returned as valid zero-length strings.
438 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
439 char *rip, int rip_len)
442 struct sockaddr_in sin;
443 struct hostent *host;
444 struct hostent *host1;
449 struct sockaddr_un *un;
456 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
457 perror("getpeername");
461 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
464 perror("gethostbyaddr");
468 strncpy(name, host->h_name, name_len);
469 name[name_len - 1] = '\0';
471 host1 = gethostbyname(host->h_name);
474 p = (unsigned char *)host1;
477 p = (unsigned char *)host1->h_addr_list[n++];
480 if ((host1->h_addrtype != AF_INET)
482 && (host1->h_addrtype != AF_LOCAL)
487 if (host1->h_addrtype == AF_INET)
488 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
491 un = (struct sockaddr_un *)p;
492 strncpy(ip, un->sun_path, sizeof(ip) - 1);
493 ip[sizeof(ip) - 1] = '\0';
497 strncpy(rip, ip, rip_len);
498 rip[rip_len - 1] = '\0';
502 int libwebsockets_get_random(struct libwebsocket_context *context,
509 for (n = 0; n < len; n++)
510 p[n] = (unsigned char)rand();
512 n = read(context->fd_random, p, len);
519 libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md)
521 return SHA1(d, n, md);
524 void libwebsockets_00_spaceout(char *key, int spaces, int seed)
530 if (*key && (seed & 1))
534 p = key + strlen(key);
543 void libwebsockets_00_spam(char *key, int count, int seed)
550 if (*key && (seed & 1))
554 p = key + strlen(key);
559 *key++ = 0x21 + ((seed & 0xffff) % 15);
560 /* 4 would use it up too fast.. not like it matters */
565 int lws_send_pipe_choked(struct libwebsocket *wsi)
570 fds.events = POLLOUT;
573 if (poll(&fds, 1, 0) != 1)
576 if ((fds.revents & POLLOUT) == 0)
579 /* okay to send another packet without blocking */
585 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
586 struct libwebsocket *wsi, struct pollfd *pollfd)
588 struct lws_tokens eff_buf;
594 for (n = 0; n < wsi->count_active_extensions; n++) {
595 if (!wsi->active_extensions[n]->callback)
598 m = wsi->active_extensions[n]->callback(context,
599 wsi->active_extensions[n], wsi,
600 LWS_EXT_CALLBACK_IS_WRITEABLE,
601 wsi->active_extensions_user[n], NULL, 0);
609 if (!wsi->extension_data_pending || handled == 2)
613 * check in on the active extensions, see if they
614 * had pending stuff to spill... they need to get the
615 * first look-in otherwise sequence will be disordered
617 * NULL, zero-length eff_buf means just spill pending
623 /* default to nobody has more to spill */
626 eff_buf.token = NULL;
627 eff_buf.token_len = 0;
629 /* give every extension a chance to spill */
631 for (n = 0; n < wsi->count_active_extensions; n++) {
632 m = wsi->active_extensions[n]->callback(
633 wsi->protocol->owning_server,
634 wsi->active_extensions[n], wsi,
635 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
636 wsi->active_extensions_user[n], &eff_buf, 0);
638 fprintf(stderr, "ext reports fatal error\n");
643 * at least one extension told us he has more
644 * to spill, so we will go around again after
649 /* assuming they gave us something to send, send it */
651 if (eff_buf.token_len) {
652 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
658 /* no extension has more to spill */
664 * There's more to spill from an extension, but we just sent
665 * something... did that leave the pipe choked?
668 if (!lws_send_pipe_choked(wsi))
669 /* no we could add more */
672 debug("choked in POLLOUT service\n");
675 * Yes, he's choked. Leave the POLLOUT masked on so we will
676 * come back here when he is unchoked. Don't call the user
677 * callback to enforce ordering of spilling, he'll get called
678 * when we come back here and there's nothing more to spill.
684 wsi->extension_data_pending = 0;
690 pollfd->events &= ~POLLOUT;
692 /* external POLL support via protocol 0 */
693 context->protocols[0].callback(context, wsi,
694 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
695 (void *)(long)wsi->sock, NULL, POLLOUT);
700 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
701 n = LWS_CALLBACK_CLIENT_WRITEABLE;
703 n = LWS_CALLBACK_SERVER_WRITEABLE;
705 wsi->protocol->callback(context, wsi, n, wsi->user_space, NULL, 0);
713 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
714 struct libwebsocket *wsi, unsigned int sec)
719 * if extensions want in on it (eg, we are a mux parent)
720 * give them a chance to service child timeouts
723 for (n = 0; n < wsi->count_active_extensions; n++)
724 wsi->active_extensions[n]->callback(
725 context, wsi->active_extensions[n],
726 wsi, LWS_EXT_CALLBACK_1HZ,
727 wsi->active_extensions_user[n], NULL, sec);
729 if (!wsi->pending_timeout)
733 * if we went beyond the allowed time, kill the
737 if (sec > wsi->pending_timeout_limit) {
738 debug("TIMEDOUT WAITING\n");
739 libwebsocket_close_and_free_session(context,
740 wsi, LWS_CLOSE_STATUS_NOSTATUS);
744 struct libwebsocket *
745 libwebsocket_create_new_server_wsi(struct libwebsocket_context *context)
747 struct libwebsocket *new_wsi;
750 new_wsi = malloc(sizeof(struct libwebsocket));
751 if (new_wsi == NULL) {
752 fprintf(stderr, "Out of memory for new connection\n");
756 memset(new_wsi, 0, sizeof(struct libwebsocket));
757 new_wsi->count_active_extensions = 0;
758 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
760 /* intialize the instance struct */
762 new_wsi->state = WSI_STATE_HTTP;
763 new_wsi->name_buffer_pos = 0;
764 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
766 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
767 new_wsi->utf8_token[n].token = NULL;
768 new_wsi->utf8_token[n].token_len = 0;
772 * these can only be set once the protocol is known
773 * we set an unestablished connection's protocol pointer
774 * to the start of the supported list, so it can look
775 * for matching ones during the handshake
777 new_wsi->protocol = context->protocols;
778 new_wsi->user_space = NULL;
781 * Default protocol is 76 / 00
782 * After 76, there's a header specified to inform which
783 * draft the client wants, when that's seen we modify
784 * the individual connection's spec revision accordingly
786 new_wsi->ietf_spec_revision = 0;
792 libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
793 struct libwebsocket *wsi, char *pkt)
798 struct libwebsocket_extension *ext;
799 struct libwebsocket_extension *ext1;
801 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
802 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
803 static const char magic_websocket_guid[] =
804 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
807 * create the random key
810 n = libwebsockets_get_random(context, hash, 16);
812 fprintf(stderr, "Unable to read from random dev %s\n",
813 SYSTEM_RANDOM_FILEPATH);
819 free(wsi->c_protocol);
820 libwebsocket_close_and_free_session(context, wsi,
821 LWS_CLOSE_STATUS_NOSTATUS);
825 lws_b64_encode_string(hash, 16, wsi->key_b64,
826 sizeof wsi->key_b64);
829 * 00 example client handshake
831 * GET /socket.io/websocket HTTP/1.1
833 * Connection: Upgrade
834 * Host: 127.0.0.1:9999
835 * Origin: http://127.0.0.1
836 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7 92 ^
837 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
838 * Cookie: socketio=websocket
842 * 04 example client handshake
845 * Host: server.example.com
847 * Connection: Upgrade
848 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
849 * Sec-WebSocket-Origin: http://example.com
850 * Sec-WebSocket-Protocol: chat, superchat
851 * Sec-WebSocket-Version: 4
854 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
856 if (wsi->ietf_spec_revision == 0) {
857 unsigned char spaces_1, spaces_2;
858 unsigned int max_1, max_2;
859 unsigned int num_1, num_2;
860 unsigned long product_1, product_2;
867 libwebsockets_get_random(context, &spaces_1, sizeof(char));
868 libwebsockets_get_random(context, &spaces_2, sizeof(char));
870 spaces_1 = (spaces_1 % 12) + 1;
871 spaces_2 = (spaces_2 % 12) + 1;
873 max_1 = 4294967295 / spaces_1;
874 max_2 = 4294967295 / spaces_2;
876 libwebsockets_get_random(context, &num_1, sizeof(int));
877 libwebsockets_get_random(context, &num_2, sizeof(int));
879 num_1 = (num_1 % max_1);
880 num_2 = (num_2 % max_2);
882 challenge[0] = num_1 >> 24;
883 challenge[1] = num_1 >> 16;
884 challenge[2] = num_1 >> 8;
885 challenge[3] = num_1;
886 challenge[4] = num_2 >> 24;
887 challenge[5] = num_2 >> 16;
888 challenge[6] = num_2 >> 8;
889 challenge[7] = num_2;
891 product_1 = num_1 * spaces_1;
892 product_2 = num_2 * spaces_2;
894 sprintf(key_1, "%lu", product_1);
895 sprintf(key_2, "%lu", product_2);
897 libwebsockets_get_random(context, &seed, sizeof(int));
898 libwebsockets_get_random(context, &count, sizeof(int));
900 libwebsockets_00_spam(key_1, (count % 12) + 1, seed);
902 libwebsockets_get_random(context, &seed, sizeof(int));
903 libwebsockets_get_random(context, &count, sizeof(int));
905 libwebsockets_00_spam(key_2, (count % 12) + 1, seed);
907 libwebsockets_get_random(context, &seed, sizeof(int));
909 libwebsockets_00_spaceout(key_1, spaces_1, seed);
910 libwebsockets_00_spaceout(key_2, spaces_2, seed >> 16);
912 p += sprintf(p, "Upgrade: WebSocket\x0d\x0a"
913 "Connection: Upgrade\x0d\x0aHost: %s\x0d\x0a",
916 p += sprintf(p, "Origin: %s\x0d\x0a", wsi->c_origin);
919 p += sprintf(p, "Sec-WebSocket-Protocol: %s"
920 "\x0d\x0a", wsi->c_protocol);
922 p += sprintf(p, "Sec-WebSocket-Key1: %s\x0d\x0a", key_1);
923 p += sprintf(p, "Sec-WebSocket-Key2: %s\x0d\x0a", key_2);
925 /* give userland a chance to append, eg, cookies */
927 context->protocols[0].callback(context, wsi,
928 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
929 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
931 p += sprintf(p, "\x0d\x0a");
933 if (libwebsockets_get_random(context, p, 8) != 8)
935 memcpy(&challenge[8], p, 8);
938 /* precompute what we want to see from the server */
940 MD5((unsigned char *)challenge, 16,
941 (unsigned char *)wsi->initial_handshake_hash_base64);
946 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
947 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
948 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
949 "Sec-WebSocket-Key: ");
950 strcpy(p, wsi->key_b64);
951 p += strlen(wsi->key_b64);
952 p += sprintf(p, "\x0d\x0a");
954 if (wsi->ietf_spec_revision == 13) {
955 p += sprintf(p, "Origin: %s\x0d\x0a",
959 p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
964 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
967 /* tell the server what extensions we could support */
969 p += sprintf(p, "Sec-WebSocket-Extensions: ");
971 ext = context->extensions;
972 while (ext && ext->callback) {
975 ext1 = context->extensions;
977 while (ext1 && ext1->callback) {
978 n |= ext1->callback(context, ext1, wsi,
979 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
980 NULL, (char *)ext->name, 0);
985 if (n) { /* an extension vetos us */
986 debug("ext %s vetoed\n", (char *)ext->name);
991 n = context->protocols[0].callback(context, wsi,
992 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
993 wsi->user_space, (char *)ext->name, 0);
996 * zero return from callback means
997 * go ahead and allow the extension,
998 * it's what we get if the callback is
1011 p += sprintf(p, "%s", ext->name);
1017 p += sprintf(p, "\x0d\x0a");
1019 if (wsi->ietf_spec_revision)
1020 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1021 wsi->ietf_spec_revision);
1023 /* give userland a chance to append, eg, cookies */
1025 context->protocols[0].callback(context, wsi,
1026 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1027 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
1029 p += sprintf(p, "\x0d\x0a");
1031 /* prepare the expected server accept response */
1033 strcpy((char *)buf, wsi->key_b64);
1034 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
1036 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
1038 lws_b64_encode_string(hash, 20,
1039 wsi->initial_handshake_hash_base64,
1040 sizeof wsi->initial_handshake_hash_base64);
1048 /* done with these now */
1053 free(wsi->c_origin);
1059 lws_client_interpret_server_handshake(struct libwebsocket_context *context,
1060 struct libwebsocket *wsi)
1062 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
1063 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
1071 struct libwebsocket_extension *ext;
1075 static const char magic_websocket_04_masking_guid[] =
1076 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
1081 * HTTP/1.1 101 WebSocket Protocol Handshake
1082 * Upgrade: WebSocket
1083 * Connection: Upgrade
1084 * Sec-WebSocket-Origin: http://127.0.0.1
1085 * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1090 if (wsi->ietf_spec_revision == 0) {
1091 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1092 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1093 !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1094 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1095 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1096 wsi->c_protocol != NULL)) {
1097 debug("libwebsocket_client_handshake "
1098 "missing required header(s)\n");
1104 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1105 if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
1106 fprintf(stderr, "libwebsocket_client_handshake "
1107 "server sent bad HTTP response '%s'\n",
1108 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1112 if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len < 16) {
1113 fprintf(stderr, "libwebsocket_client_handshake "
1114 "challenge reply too short %d\n",
1116 WSI_TOKEN_CHALLENGE].token_len);
1123 goto select_protocol;
1127 * well, what the server sent looked reasonable for syntax.
1128 * Now let's confirm it sent all the necessary headers
1131 fprintf(stderr, "WSI_TOKEN_HTTP: %d\n",
1132 wsi->utf8_token[WSI_TOKEN_HTTP].token_len);
1133 fprintf(stderr, "WSI_TOKEN_UPGRADE: %d\n",
1134 wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len);
1135 fprintf(stderr, "WSI_TOKEN_CONNECTION: %d\n",
1136 wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len);
1137 fprintf(stderr, "WSI_TOKEN_ACCEPT: %d\n",
1138 wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len);
1139 fprintf(stderr, "WSI_TOKEN_NONCE: %d\n",
1140 wsi->utf8_token[WSI_TOKEN_NONCE].token_len);
1141 fprintf(stderr, "WSI_TOKEN_PROTOCOL: %d\n",
1142 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
1144 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1145 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1146 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1147 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
1148 (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
1149 wsi->ietf_spec_revision == 4) ||
1150 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1151 wsi->c_protocol != NULL)) {
1152 debug("libwebsocket_client_handshake "
1153 "missing required header(s)\n");
1160 * Everything seems to be there, now take a closer look at what
1164 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1165 if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
1166 fprintf(stderr, "libwebsocket_client_handshake "
1167 "server sent bad HTTP response '%s'\n",
1168 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1172 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1173 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1175 fprintf(stderr, "libwebsocket_client_handshake server "
1176 "sent bad Upgrade header '%s'\n",
1177 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1181 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1182 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1184 fprintf(stderr, "libwebsocket_client_handshake server "
1185 "sent bad Connection hdr '%s'\n",
1186 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1191 pc = wsi->c_protocol;
1193 fprintf(stderr, "lws_client_interpret_server_handshake: "
1194 "NULL c_protocol\n");
1196 debug("lws_client_interpret_server_handshake: "
1197 "cPprotocol='%s'\n", pc);
1200 * confirm the protocol the server wants to talk was in the list
1201 * of protocols we offered
1204 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1206 fprintf(stderr, "lws_client_interpret_server_handshake "
1207 "WSI_TOKEN_PROTOCOL is null\n");
1209 * no protocol name to work from,
1210 * default to first protocol
1212 wsi->protocol = &context->protocols[0];
1213 wsi->c_callback = wsi->protocol->callback;
1214 free(wsi->c_protocol);
1216 goto check_extensions;
1219 while (*pc && !okay) {
1220 if ((!strncmp(pc, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1221 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
1222 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
1223 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
1227 while (*pc && *pc != ',')
1229 while (*pc && *pc != ' ')
1233 /* done with him now */
1235 if (wsi->c_protocol)
1236 free(wsi->c_protocol);
1239 fprintf(stderr, "libwebsocket_client_handshake server "
1240 "sent bad protocol '%s'\n",
1241 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1246 * identify the selected protocol struct and set it
1249 wsi->protocol = NULL;
1250 while (context->protocols[n].callback && !wsi->protocol) { /* Stop after finding first one?? */
1251 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1252 context->protocols[n].name) == 0) {
1253 wsi->protocol = &context->protocols[n];
1254 wsi->c_callback = wsi->protocol->callback;
1259 if (wsi->protocol == NULL) {
1260 fprintf(stderr, "libwebsocket_client_handshake server "
1261 "requested protocol '%s', which we "
1262 "said we supported but we don't!\n",
1263 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1270 /* instantiate the accepted extensions */
1272 if (!wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
1273 debug("no client extenstions allowed by server\n");
1278 * break down the list of server accepted extensions
1279 * and go through matching them or identifying bogons
1282 c = wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token;
1286 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
1288 if (n < sizeof(ext_name) - 1)
1301 /* check we actually support it */
1303 debug("checking client ext %s\n", ext_name);
1306 ext = wsi->protocol->owning_server->extensions;
1307 while (ext && ext->callback) {
1309 if (strcmp(ext_name, ext->name)) {
1316 debug("instantiating client ext %s\n", ext_name);
1318 /* instantiate the extension on this conn */
1320 wsi->active_extensions_user[
1321 wsi->count_active_extensions] =
1322 malloc(ext->per_session_data_size);
1323 memset(wsi->active_extensions_user[
1324 wsi->count_active_extensions], 0,
1325 ext->per_session_data_size);
1326 wsi->active_extensions[
1327 wsi->count_active_extensions] = ext;
1329 /* allow him to construct his context */
1331 ext->callback(wsi->protocol->owning_server,
1333 LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
1334 wsi->active_extensions_user[
1335 wsi->count_active_extensions],
1338 wsi->count_active_extensions++;
1344 fprintf(stderr, "Server said we should use"
1345 "an unknown extension '%s'!\n", ext_name);
1355 if (wsi->ietf_spec_revision == 0) {
1357 if (memcmp(wsi->initial_handshake_hash_base64,
1358 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
1359 fprintf(stderr, "libwebsocket_client_handshake "
1360 "failed 00 challenge compare\n");
1362 fprintf(stderr, "%s", pkt);
1370 * Confirm his accept token is the one we precomputed
1373 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1374 wsi->initial_handshake_hash_base64)) {
1375 fprintf(stderr, "libwebsocket_client_handshake server "
1376 "sent bad ACCEPT '%s' vs computed '%s'\n",
1377 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1378 wsi->initial_handshake_hash_base64);
1382 if (wsi->ietf_spec_revision == 4) {
1384 * Calculate the 04 masking key to use when
1385 * sending data to server
1388 strcpy((char *)buf, wsi->key_b64);
1389 p = (char *)buf + strlen(wsi->key_b64);
1390 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1391 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1392 strcpy(p, magic_websocket_04_masking_guid);
1393 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1397 /* allocate the per-connection user memory (if any) */
1398 if (wsi->protocol->per_session_data_size &&
1399 !libwebsocket_ensure_user_space(wsi))
1402 /* clear his proxy connection timeout */
1404 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1406 /* mark him as being alive */
1408 wsi->state = WSI_STATE_ESTABLISHED;
1409 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1411 debug("handshake OK for protocol %s\n", wsi->protocol->name);
1413 /* call him back to inform him he is up */
1415 wsi->protocol->callback(context, wsi,
1416 LWS_CALLBACK_CLIENT_ESTABLISHED,
1417 wsi->user_space, NULL, 0);
1420 * inform all extensions, not just active ones since they
1424 ext = context->extensions;
1426 while (ext && ext->callback) {
1428 for (n = 0; n < wsi->count_active_extensions; n++)
1429 if (wsi->active_extensions[n] == ext)
1430 v = wsi->active_extensions_user[n];
1432 ext->callback(context, ext, wsi,
1433 LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
1440 if (wsi->c_protocol)
1441 free(wsi->c_protocol);
1444 if (wsi->c_callback) wsi->c_callback(context, wsi,
1445 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
1448 libwebsocket_close_and_free_session(context, wsi,
1449 LWS_CLOSE_STATUS_NOSTATUS); // But this should be LWS_CLOSE_STATUS_PROTOCOL_ERR
1457 * libwebsocket_service_fd() - Service polled socket with something waiting
1458 * @context: Websocket context
1459 * @pollfd: The pollfd entry describing the socket fd and which events
1462 * This function closes any active connections and then frees the
1463 * context. After calling this, any further use of the context is
1468 libwebsocket_service_fd(struct libwebsocket_context *context,
1469 struct pollfd *pollfd)
1471 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
1472 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
1473 struct libwebsocket *wsi;
1474 struct libwebsocket *new_wsi;
1479 unsigned int clilen;
1480 struct sockaddr_in cli_addr;
1485 struct lws_tokens eff_buf;
1489 #ifdef LWS_OPENSSL_SUPPORT
1490 char ssl_err_buf[512];
1493 * you can call us with pollfd = NULL to just allow the once-per-second
1494 * global timeout checks; if less than a second since the last check
1495 * it returns immediately then.
1498 gettimeofday(&tv, NULL);
1500 if (context->last_timeout_check_s != tv.tv_sec) {
1501 context->last_timeout_check_s = tv.tv_sec;
1503 /* global timeout check once per second */
1505 for (n = 0; n < context->fds_count; n++) {
1506 wsi = wsi_from_fd(context, context->fds[n].fd);
1508 libwebsocket_service_timeout_check(context, wsi,
1513 /* just here for timeout management? */
1518 /* no, here to service a socket descriptor */
1520 wsi = wsi_from_fd(context, pollfd->fd);
1525 switch (wsi->mode) {
1526 case LWS_CONNMODE_SERVER_LISTENER:
1528 /* pollin means a client has connected to us then */
1530 if (!(pollfd->revents & POLLIN))
1533 if (context->fds_count >= MAX_CLIENTS) {
1534 fprintf(stderr, "too busy to accept new client\n");
1538 /* listen socket got an unencrypted connection... */
1540 clilen = sizeof(cli_addr);
1541 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1543 if (accept_fd < 0) {
1544 debug("ERROR on accept\n");
1550 setsockopt(accept_fd, IPPROTO_TCP, TCP_NODELAY,
1551 (const void *)&opt, sizeof(opt));
1554 * look at who we connected to and give user code a chance
1555 * to reject based on client IP. There's no protocol selected
1556 * yet so we issue this to protocols[0]
1559 if ((context->protocols[0].callback)(context, wsi,
1560 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1561 (void *)(long)accept_fd, NULL, 0)) {
1562 debug("Callback denied network connection\n");
1564 closesocket(accept_fd);
1571 /* accepting connection to main listener */
1573 new_wsi = libwebsocket_create_new_server_wsi(context);
1574 if (new_wsi == NULL)
1577 new_wsi->sock = accept_fd;
1580 #ifdef LWS_OPENSSL_SUPPORT
1581 new_wsi->ssl = NULL;
1583 if (context->use_ssl) {
1585 new_wsi->ssl = SSL_new(context->ssl_ctx);
1586 if (new_wsi->ssl == NULL) {
1587 fprintf(stderr, "SSL_new failed: %s\n",
1588 ERR_error_string(SSL_get_error(
1589 new_wsi->ssl, 0), NULL));
1590 libwebsockets_decode_ssl_error();
1595 SSL_set_fd(new_wsi->ssl, accept_fd);
1597 n = SSL_accept(new_wsi->ssl);
1600 * browsers seem to probe with various
1601 * ssl params which fail then retry
1604 debug("SSL_accept failed skt %u: %s\n",
1606 ERR_error_string(SSL_get_error(
1607 new_wsi->ssl, n), NULL));
1614 debug("accepted new SSL conn "
1615 "port %u on fd=%d SSL ver %s\n",
1616 ntohs(cli_addr.sin_port), accept_fd,
1617 SSL_get_version(new_wsi->ssl));
1621 debug("accepted new conn port %u on fd=%d\n",
1622 ntohs(cli_addr.sin_port), accept_fd);
1624 insert_wsi(context, new_wsi);
1627 * make sure NO events are seen yet on this new socket
1628 * (otherwise we inherit old fds[client].revents from
1629 * previous socket there and die mysteriously! )
1631 context->fds[context->fds_count].revents = 0;
1633 context->fds[context->fds_count].events = POLLIN;
1634 context->fds[context->fds_count++].fd = accept_fd;
1636 /* external POLL support via protocol 0 */
1637 context->protocols[0].callback(context, new_wsi,
1638 LWS_CALLBACK_ADD_POLL_FD,
1639 (void *)(long)accept_fd, NULL, POLLIN);
1643 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
1645 /* as we are listening, POLLIN means accept() is needed */
1647 if (!(pollfd->revents & POLLIN))
1650 /* listen socket got an unencrypted connection... */
1652 clilen = sizeof(cli_addr);
1653 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1655 if (accept_fd < 0) {
1656 debug("ERROR on accept\n");
1660 if (context->fds_count >= MAX_CLIENTS) {
1661 fprintf(stderr, "too busy to accept new broadcast "
1664 closesocket(accept_fd);
1671 /* create a dummy wsi for the connection and add it */
1673 new_wsi = malloc(sizeof(struct libwebsocket));
1674 memset(new_wsi, 0, sizeof(struct libwebsocket));
1675 new_wsi->sock = accept_fd;
1676 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
1677 new_wsi->state = WSI_STATE_ESTABLISHED;
1678 new_wsi->count_active_extensions = 0;
1679 /* note which protocol we are proxying */
1680 new_wsi->protocol_index_for_broadcast_proxy =
1681 wsi->protocol_index_for_broadcast_proxy;
1682 insert_wsi(context, new_wsi);
1684 /* add connected socket to internal poll array */
1686 context->fds[context->fds_count].revents = 0;
1687 context->fds[context->fds_count].events = POLLIN;
1688 context->fds[context->fds_count++].fd = accept_fd;
1690 /* external POLL support via protocol 0 */
1691 context->protocols[0].callback(context, new_wsi,
1692 LWS_CALLBACK_ADD_POLL_FD,
1693 (void *)(long)accept_fd, NULL, POLLIN);
1697 case LWS_CONNMODE_BROADCAST_PROXY:
1699 /* handle session socket closed */
1701 if (pollfd->revents & (POLLERR | POLLHUP)) {
1703 debug("Session Socket %p (fd=%d) dead\n",
1704 (void *)wsi, pollfd->fd);
1706 libwebsocket_close_and_free_session(context, wsi,
1707 LWS_CLOSE_STATUS_NORMAL);
1712 * either extension code with stuff to spill, or the user code,
1713 * requested a callback when it was OK to write
1716 if (pollfd->revents & POLLOUT)
1717 if (lws_handle_POLLOUT_event(context, wsi,
1719 libwebsocket_close_and_free_session(
1720 context, wsi, LWS_CLOSE_STATUS_NORMAL);
1724 /* any incoming data ready? */
1726 if (!(pollfd->revents & POLLIN))
1729 /* get the issued broadcast payload from the socket */
1731 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
1732 MAX_BROADCAST_PAYLOAD);
1734 fprintf(stderr, "Error reading broadcast payload\n");
1738 /* broadcast it to all guys with this protocol index */
1740 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1742 for (m = 0; m < context->fd_hashtable[n].length; m++) {
1744 new_wsi = context->fd_hashtable[n].wsi[m];
1746 /* only to clients we are serving to */
1748 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
1752 * never broadcast to non-established
1756 if (new_wsi->state != WSI_STATE_ESTABLISHED)
1760 * only broadcast to connections using
1761 * the requested protocol
1764 if (new_wsi->protocol->protocol_index !=
1765 wsi->protocol_index_for_broadcast_proxy)
1768 /* broadcast it to this connection */
1770 new_wsi->protocol->callback(context, new_wsi,
1771 LWS_CALLBACK_BROADCAST,
1772 new_wsi->user_space,
1773 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
1778 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
1780 /* handle proxy hung up on us */
1782 if (pollfd->revents & (POLLERR | POLLHUP)) {
1784 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
1785 (void *)wsi, pollfd->fd);
1787 libwebsocket_close_and_free_session(context, wsi,
1788 LWS_CLOSE_STATUS_NOSTATUS);
1792 n = recv(wsi->sock, pkt, sizeof pkt, 0);
1794 libwebsocket_close_and_free_session(context, wsi,
1795 LWS_CLOSE_STATUS_NOSTATUS);
1796 fprintf(stderr, "ERROR reading from proxy socket\n");
1801 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
1802 libwebsocket_close_and_free_session(context, wsi,
1803 LWS_CLOSE_STATUS_NOSTATUS);
1804 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
1808 /* clear his proxy connection timeout */
1810 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1814 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
1816 #ifdef LWS_OPENSSL_SUPPORT
1817 if (wsi->use_ssl && !wsi->ssl) {
1819 wsi->ssl = SSL_new(context->ssl_client_ctx);
1820 wsi->client_bio = BIO_new_socket(wsi->sock,
1822 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
1824 SSL_set_ex_data(wsi->ssl,
1825 openssl_websocket_private_data_index,
1830 if (SSL_connect(wsi->ssl) <= 0) {
1833 * retry if new data comes until we
1834 * run into the connection timeout or win
1837 fprintf(stderr, "SSL connect error %s\n",
1838 ERR_error_string(ERR_get_error(),
1843 n = SSL_get_verify_result(wsi->ssl);
1844 if ((n != X509_V_OK) && (
1845 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
1846 wsi->use_ssl != 2)) {
1848 fprintf(stderr, "server's cert didn't "
1849 "look good %d\n", n);
1850 libwebsocket_close_and_free_session(context,
1851 wsi, LWS_CLOSE_STATUS_NOSTATUS);
1858 p = libwebsockets_generate_client_handshake(context, wsi, p);
1862 /* send our request to the server */
1864 #ifdef LWS_OPENSSL_SUPPORT
1866 n = SSL_write(wsi->ssl, pkt, p - pkt);
1869 n = send(wsi->sock, pkt, p - pkt, 0);
1872 fprintf(stderr, "ERROR writing to client socket\n");
1873 libwebsocket_close_and_free_session(context, wsi,
1874 LWS_CLOSE_STATUS_NOSTATUS);
1878 wsi->parser_state = WSI_TOKEN_NAME_PART;
1879 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
1880 libwebsocket_set_timeout(wsi,
1881 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, AWAITING_TIMEOUT);
1885 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
1887 /* handle server hung up on us */
1889 if (pollfd->revents & (POLLERR | POLLHUP)) {
1891 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
1892 (void *)wsi, pollfd->fd);
1898 /* interpret the server response */
1901 * HTTP/1.1 101 Switching Protocols
1902 * Upgrade: websocket
1903 * Connection: Upgrade
1904 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
1905 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
1906 * Sec-WebSocket-Protocol: chat
1910 * we have to take some care here to only take from the
1911 * socket bytewise. The browser may (and has been seen to
1912 * in the case that onopen() performs websocket traffic)
1913 * coalesce both handshake response and websocket traffic
1914 * in one packet, since at that point the connection is
1915 * definitively ready from browser pov.
1919 while (wsi->parser_state != WSI_PARSING_COMPLETE && len > 0) {
1920 #ifdef LWS_OPENSSL_SUPPORT
1922 len = SSL_read(wsi->ssl, &c, 1);
1925 len = recv(wsi->sock, &c, 1, 0);
1927 libwebsocket_parse(wsi, c);
1931 * hs may also be coming in multiple packets, there is a 5-sec
1932 * libwebsocket timeout still active here too, so if parsing did
1933 * not complete just wait for next packet coming in this state
1936 if (wsi->parser_state != WSI_PARSING_COMPLETE)
1940 * otherwise deal with the handshake. If there's any
1941 * packet traffic already arrived we'll trigger poll() again
1942 * right away and deal with it that way
1945 return lws_client_interpret_server_handshake(context, wsi);
1948 if (wsi->c_protocol)
1949 free(wsi->c_protocol);
1950 libwebsocket_close_and_free_session(context, wsi,
1951 LWS_CLOSE_STATUS_NOSTATUS);
1954 case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
1956 "LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT\n");
1959 case LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD:
1961 "LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD\n");
1965 case LWS_CONNMODE_WS_SERVING:
1966 case LWS_CONNMODE_WS_CLIENT:
1968 /* handle session socket closed */
1970 if (pollfd->revents & (POLLERR | POLLHUP)) {
1972 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1973 (void *)wsi, pollfd->fd);
1975 libwebsocket_close_and_free_session(context, wsi,
1976 LWS_CLOSE_STATUS_NOSTATUS);
1980 /* the guy requested a callback when it was OK to write */
1982 if ((pollfd->revents & POLLOUT) &&
1983 wsi->state == WSI_STATE_ESTABLISHED)
1984 if (lws_handle_POLLOUT_event(context, wsi,
1986 libwebsocket_close_and_free_session(
1987 context, wsi, LWS_CLOSE_STATUS_NORMAL);
1992 /* any incoming data ready? */
1994 if (!(pollfd->revents & POLLIN))
1997 #ifdef LWS_OPENSSL_SUPPORT
1999 eff_buf.token_len = SSL_read(wsi->ssl, buf, sizeof buf);
2003 recv(pollfd->fd, buf, sizeof buf, 0);
2005 if (eff_buf.token_len < 0) {
2006 fprintf(stderr, "Socket read returned %d\n",
2008 if (errno != EINTR && errno != EAGAIN)
2009 libwebsocket_close_and_free_session(context,
2010 wsi, LWS_CLOSE_STATUS_NOSTATUS);
2013 if (!eff_buf.token_len) {
2014 libwebsocket_close_and_free_session(context, wsi,
2015 LWS_CLOSE_STATUS_NOSTATUS);
2020 * give any active extensions a chance to munge the buffer
2021 * before parse. We pass in a pointer to an lws_tokens struct
2022 * prepared with the default buffer and content length that's in
2023 * there. Rather than rewrite the default buffer, extensions
2024 * that expect to grow the buffer can adapt .token to
2025 * point to their own per-connection buffer in the extension
2026 * user allocation. By default with no extensions or no
2027 * extension callback handling, just the normal input buffer is
2028 * used then so it is efficient.
2031 eff_buf.token = (char *)buf;
2038 for (n = 0; n < wsi->count_active_extensions; n++) {
2039 m = wsi->active_extensions[n]->callback(context,
2040 wsi->active_extensions[n], wsi,
2041 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
2042 wsi->active_extensions_user[n],
2046 "Extension reports fatal error\n");
2047 libwebsocket_close_and_free_session(
2049 LWS_CLOSE_STATUS_NOSTATUS);
2056 /* service incoming data */
2058 if (eff_buf.token_len) {
2059 n = libwebsocket_read(context, wsi,
2060 (unsigned char *)eff_buf.token,
2067 eff_buf.token = NULL;
2068 eff_buf.token_len = 0;
2078 * libwebsocket_context_destroy() - Destroy the websocket context
2079 * @context: Websocket context
2081 * This function closes any active connections and then frees the
2082 * context. After calling this, any further use of the context is
2086 libwebsocket_context_destroy(struct libwebsocket_context *context)
2090 struct libwebsocket *wsi;
2091 struct libwebsocket_extension *ext;
2093 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
2094 for (m = 0; m < context->fd_hashtable[n].length; m++) {
2095 wsi = context->fd_hashtable[n].wsi[m];
2096 libwebsocket_close_and_free_session(context, wsi,
2097 LWS_CLOSE_STATUS_GOINGAWAY);
2101 * give all extensions a chance to clean up any per-context
2102 * allocations they might have made
2105 ext = context->extensions;
2106 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
2107 if (context->listen_port)
2108 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
2109 while (ext && ext->callback) {
2110 ext->callback(context, ext, NULL, m, NULL, NULL, 0);
2116 close(context->fd_random);
2119 #ifdef LWS_OPENSSL_SUPPORT
2120 if (context->ssl_ctx)
2121 SSL_CTX_free(context->ssl_ctx);
2122 if (context->ssl_client_ctx)
2123 SSL_CTX_free(context->ssl_client_ctx);
2134 libwebsocket_context_user(struct libwebsocket_context *context)
2136 return context->user_space;
2140 * libwebsocket_service() - Service any pending websocket activity
2141 * @context: Websocket context
2142 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2143 * service otherwise block and service immediately, returning
2144 * after the timeout if nothing needed service.
2146 * This function deals with any pending websocket traffic, for three
2147 * kinds of event. It handles these events on both server and client
2148 * types of connection the same.
2150 * 1) Accept new connections to our context's server
2152 * 2) Perform pending broadcast writes initiated from other forked
2153 * processes (effectively serializing asynchronous broadcasts)
2155 * 3) Call the receive callback for incoming frame data received by
2156 * server or client connections.
2158 * You need to call this service function periodically to all the above
2159 * functions to happen; if your application is single-threaded you can
2160 * just call it in your main event loop.
2162 * Alternatively you can fork a new process that asynchronously handles
2163 * calling this service in a loop. In that case you are happy if this
2164 * call blocks your thread until it needs to take care of something and
2165 * would call it with a large nonzero timeout. Your loop then takes no
2166 * CPU while there is nothing happening.
2168 * If you are calling it in a single-threaded app, you don't want it to
2169 * wait around blocking other things in your loop from happening, so you
2170 * would call it with a timeout_ms of 0, so it returns immediately if
2171 * nothing is pending, or as soon as it services whatever was pending.
2176 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
2180 /* stay dead once we are dead */
2182 if (context == NULL)
2185 /* wait for something to need service */
2187 n = poll(context->fds, context->fds_count, timeout_ms);
2188 if (n == 0) /* poll timeout */
2193 fprintf(stderr, "Listen Socket dead\n");
2198 /* handle accept on listening socket? */
2200 for (n = 0; n < context->fds_count; n++)
2201 if (context->fds[n].revents)
2202 if (libwebsocket_service_fd(context,
2203 &context->fds[n]) < 0)
2209 lws_any_extension_handled(struct libwebsocket_context *context,
2210 struct libwebsocket *wsi,
2211 enum libwebsocket_extension_callback_reasons r,
2212 void *v, size_t len)
2217 /* maybe an extension will take care of it for us */
2219 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
2220 if (!wsi->active_extensions[n]->callback)
2223 handled |= wsi->active_extensions[n]->callback(context,
2224 wsi->active_extensions[n], wsi,
2225 r, wsi->active_extensions_user[n], v, len);
2233 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
2234 struct libwebsocket_extension *ext)
2241 while (n < wsi->count_active_extensions) {
2242 if (wsi->active_extensions[n] != ext) {
2246 return wsi->active_extensions_user[n];
2253 * libwebsocket_callback_on_writable() - Request a callback when this socket
2254 * becomes able to be written to without
2257 * @context: libwebsockets context
2258 * @wsi: Websocket connection instance to get callback for
2262 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
2263 struct libwebsocket *wsi)
2268 /* maybe an extension will take care of it for us */
2270 for (n = 0; n < wsi->count_active_extensions; n++) {
2271 if (!wsi->active_extensions[n]->callback)
2274 handled |= wsi->active_extensions[n]->callback(context,
2275 wsi->active_extensions[n], wsi,
2276 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
2277 wsi->active_extensions_user[n], NULL, 0);
2283 for (n = 0; n < context->fds_count; n++)
2284 if (context->fds[n].fd == wsi->sock) {
2285 context->fds[n].events |= POLLOUT;
2286 n = context->fds_count + 1;
2289 if (n == context->fds_count)
2290 fprintf(stderr, "libwebsocket_callback_on_writable: "
2291 "failed to find socket %d\n", wsi->sock);
2293 /* external POLL support via protocol 0 */
2294 context->protocols[0].callback(context, wsi,
2295 LWS_CALLBACK_SET_MODE_POLL_FD,
2296 (void *)(long)wsi->sock, NULL, POLLOUT);
2302 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
2303 * all connections using the given protocol when it
2304 * becomes possible to write to each socket without
2307 * @protocol: Protocol whose connections will get callbacks
2311 libwebsocket_callback_on_writable_all_protocol(
2312 const struct libwebsocket_protocols *protocol)
2314 struct libwebsocket_context *context = protocol->owning_server;
2317 struct libwebsocket *wsi;
2319 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
2321 for (m = 0; m < context->fd_hashtable[n].length; m++) {
2323 wsi = context->fd_hashtable[n].wsi[m];
2325 if (wsi->protocol == protocol)
2326 libwebsocket_callback_on_writable(context, wsi);
2334 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
2336 * You will not need this unless you are doing something special
2338 * @wsi: Websocket connection instance
2339 * @reason: timeout reason
2340 * @secs: how many seconds
2344 libwebsocket_set_timeout(struct libwebsocket *wsi,
2345 enum pending_timeout reason, int secs)
2349 gettimeofday(&tv, NULL);
2351 wsi->pending_timeout_limit = tv.tv_sec + secs;
2352 wsi->pending_timeout = reason;
2357 * libwebsocket_get_socket_fd() - returns the socket file descriptor
2359 * You will not need this unless you are doing something special
2361 * @wsi: Websocket connection instance
2365 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
2371 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
2372 * receieved packets.
2374 * If the output side of a server process becomes choked, this allows flow
2375 * control for the input side.
2377 * @wsi: Websocket connection instance to get callback for
2378 * @enable: 0 = disable read servicing for this connection, 1 = enable
2382 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
2384 struct libwebsocket_context *context = wsi->protocol->owning_server;
2387 for (n = 0; n < context->fds_count; n++)
2388 if (context->fds[n].fd == wsi->sock) {
2390 context->fds[n].events |= POLLIN;
2392 context->fds[n].events &= ~POLLIN;
2398 /* external POLL support via protocol 0 */
2399 context->protocols[0].callback(context, wsi,
2400 LWS_CALLBACK_SET_MODE_POLL_FD,
2401 (void *)(long)wsi->sock, NULL, POLLIN);
2403 /* external POLL support via protocol 0 */
2404 context->protocols[0].callback(context, wsi,
2405 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
2406 (void *)(long)wsi->sock, NULL, POLLIN);
2409 fprintf(stderr, "libwebsocket_rx_flow_control "
2410 "unable to find socket\n");
2416 * libwebsocket_canonical_hostname() - returns this host's hostname
2418 * This is typically used by client code to fill in the host parameter
2419 * when making a client connection. You can only call it after the context
2422 * @context: Websocket context
2427 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
2429 return (const char *)context->canonical_hostname;
2433 static void sigpipe_handler(int x)
2437 #ifdef LWS_OPENSSL_SUPPORT
2439 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
2444 struct libwebsocket_context *context;
2446 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
2447 SSL_get_ex_data_X509_STORE_CTX_idx());
2450 * !!! nasty openssl requires the index to come as a library-scope
2453 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
2455 n = context->protocols[0].callback(NULL, NULL,
2456 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
2457 x509_ctx, ssl, preverify_ok);
2459 /* convert return code from 0 = OK to 1 = OK */
2472 * libwebsocket_create_context() - Create the websocket handler
2473 * @port: Port to listen on... you can use 0 to suppress listening on
2474 * any port, that's what you want if you are not running a
2475 * websocket server at all but just using it as a client
2476 * @interf: NULL to bind the listen socket to all interfaces, or the
2477 * interface name, eg, "eth2"
2478 * @protocols: Array of structures listing supported protocols and a protocol-
2479 * specific callback for each one. The list is ended with an
2480 * entry that has a NULL callback pointer.
2481 * It's not const because we write the owning_server member
2482 * @extensions: NULL or array of libwebsocket_extension structs listing the
2483 * extensions this context supports
2484 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
2485 * to listen using SSL, set to the filepath to fetch the
2486 * server cert from, otherwise NULL for unencrypted
2487 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
2489 * @ssl_ca_filepath: CA certificate filepath or NULL
2490 * @gid: group id to change to after setting listen socket, or -1.
2491 * @uid: user id to change to after setting listen socket, or -1.
2492 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
2493 * @user: optional user pointer that can be recovered via the context
2494 * pointer using libwebsocket_context_user
2496 * This function creates the listening socket and takes care
2497 * of all initialization in one step.
2499 * After initialization, it returns a struct libwebsocket_context * that
2500 * represents this server. After calling, user code needs to take care
2501 * of calling libwebsocket_service() with the context pointer to get the
2502 * server's sockets serviced. This can be done in the same process context
2503 * or a forked process, or another thread,
2505 * The protocol callback functions are called for a handful of events
2506 * including http requests coming in, websocket connections becoming
2507 * established, and data arriving; it's also called periodically to allow
2508 * async transmission.
2510 * HTTP requests are sent always to the FIRST protocol in @protocol, since
2511 * at that time websocket protocol has not been negotiated. Other
2512 * protocols after the first one never see any HTTP callack activity.
2514 * The server created is a simple http server by default; part of the
2515 * websocket standard is upgrading this http connection to a websocket one.
2517 * This allows the same server to provide files like scripts and favicon /
2518 * images or whatever over http and dynamic data over websockets all in
2519 * one place; they're all handled in the user callback.
2522 struct libwebsocket_context *
2523 libwebsocket_create_context(int port, const char *interf,
2524 struct libwebsocket_protocols *protocols,
2525 struct libwebsocket_extension *extensions,
2526 const char *ssl_cert_filepath,
2527 const char *ssl_private_key_filepath,
2528 const char *ssl_ca_filepath,
2529 int gid, int uid, unsigned int options,
2536 struct sockaddr_in serv_addr, cli_addr;
2538 struct libwebsocket_context *context = NULL;
2541 char hostname[1024] = "";
2542 // struct hostent *he;
2543 struct libwebsocket *wsi;
2546 #ifdef LWS_OPENSSL_SUPPORT
2548 char ssl_err_buf[512];
2553 WORD wVersionRequested;
2558 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
2559 wVersionRequested = MAKEWORD(2, 2);
2561 err = WSAStartup(wVersionRequested, &wsaData);
2563 /* Tell the user that we could not find a usable */
2565 fprintf(stderr, "WSAStartup failed with error: %d\n",
2570 /* default to a poll() made out of select() */
2571 poll = emulated_poll;
2573 /* if windows socket lib available, use his WSAPoll */
2574 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
2576 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
2581 context = malloc(sizeof(struct libwebsocket_context));
2583 fprintf(stderr, "No memory for websocket context\n");
2586 context->protocols = protocols;
2587 context->listen_port = port;
2588 context->http_proxy_port = 0;
2589 context->http_proxy_address[0] = '\0';
2590 context->options = options;
2591 context->fds_count = 0;
2592 context->extensions = extensions;
2593 context->last_timeout_check_s = 0;
2594 context->user_space = user;
2597 context->fd_random = 0;
2599 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
2600 if (context->fd_random < 0) {
2601 fprintf(stderr, "Unable to open random device %s %d\n",
2602 SYSTEM_RANDOM_FILEPATH, context->fd_random);
2607 #ifdef LWS_OPENSSL_SUPPORT
2608 context->use_ssl = 0;
2609 context->ssl_ctx = NULL;
2610 context->ssl_client_ctx = NULL;
2611 openssl_websocket_private_data_index = 0;
2614 if (options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME) {
2616 strcpy(context->canonical_hostname, "unknown");
2620 /* find canonical hostname */
2622 hostname[(sizeof hostname) - 1] = '\0';
2623 memset(&sa, 0, sizeof(sa));
2624 sa.sa_family = AF_INET;
2625 sa.sa_data[(sizeof sa.sa_data) - 1] = '\0';
2626 gethostname(hostname, (sizeof hostname) - 1);
2630 if (strlen(hostname) < sizeof(sa.sa_data) - 1) {
2631 strcpy(sa.sa_data, hostname);
2632 // fprintf(stderr, "my host name is %s\n", sa.sa_data);
2633 n = getnameinfo(&sa, sizeof(sa), hostname,
2634 (sizeof hostname) - 1, NULL, 0, 0);
2638 strncpy(context->canonical_hostname, hostname,
2639 sizeof context->canonical_hostname - 1);
2640 context->canonical_hostname[
2641 sizeof context->canonical_hostname - 1] = '\0';
2643 strncpy(context->canonical_hostname, hostname,
2644 sizeof context->canonical_hostname - 1);
2646 // fprintf(stderr, "context->canonical_hostname = %s\n",
2647 // context->canonical_hostname);
2650 /* split the proxy ads:port if given */
2652 p = getenv("http_proxy");
2654 strncpy(context->http_proxy_address, p,
2655 sizeof context->http_proxy_address - 1);
2656 context->http_proxy_address[
2657 sizeof context->http_proxy_address - 1] = '\0';
2659 p = strchr(context->http_proxy_address, ':');
2661 fprintf(stderr, "http_proxy needs to be ads:port\n");
2665 context->http_proxy_port = atoi(p + 1);
2667 fprintf(stderr, "Using proxy %s:%u\n",
2668 context->http_proxy_address,
2669 context->http_proxy_port);
2674 #ifdef LWS_OPENSSL_SUPPORT
2675 context->use_ssl = ssl_cert_filepath != NULL &&
2676 ssl_private_key_filepath != NULL;
2677 if (context->use_ssl)
2678 fprintf(stderr, " Compiled with SSL support, "
2681 fprintf(stderr, " Compiled with SSL support, "
2685 if (ssl_cert_filepath != NULL &&
2686 ssl_private_key_filepath != NULL) {
2687 fprintf(stderr, " Not compiled for OpenSSl support!\n");
2690 fprintf(stderr, " Compiled without SSL support, "
2691 "serving unencrypted\n");
2695 /* ignore SIGPIPE */
2698 signal(SIGPIPE, sigpipe_handler);
2702 #ifdef LWS_OPENSSL_SUPPORT
2704 /* basic openssl init */
2708 OpenSSL_add_all_algorithms();
2709 SSL_load_error_strings();
2711 openssl_websocket_private_data_index =
2712 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
2715 * Firefox insists on SSLv23 not SSLv3
2716 * Konq disables SSLv2 by default now, SSLv23 works
2719 method = (SSL_METHOD *)SSLv23_server_method();
2721 fprintf(stderr, "problem creating ssl method: %s\n",
2722 ERR_error_string(ERR_get_error(), ssl_err_buf));
2725 context->ssl_ctx = SSL_CTX_new(method); /* create context */
2726 if (!context->ssl_ctx) {
2727 fprintf(stderr, "problem creating ssl context: %s\n",
2728 ERR_error_string(ERR_get_error(), ssl_err_buf));
2732 #ifdef SSL_OP_NO_COMPRESSION
2733 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
2735 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
2736 SSL_CTX_set_cipher_list(context->ssl_ctx, CIPHERS_LIST_STRING);
2738 /* client context */
2740 if (port == CONTEXT_PORT_NO_LISTEN) {
2741 method = (SSL_METHOD *)SSLv23_client_method();
2743 fprintf(stderr, "problem creating ssl method: %s\n",
2744 ERR_error_string(ERR_get_error(), ssl_err_buf));
2747 /* create context */
2748 context->ssl_client_ctx = SSL_CTX_new(method);
2749 if (!context->ssl_client_ctx) {
2750 fprintf(stderr, "problem creating ssl context: %s\n",
2751 ERR_error_string(ERR_get_error(), ssl_err_buf));
2755 #ifdef SSL_OP_NO_COMPRESSION
2756 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_NO_COMPRESSION);
2758 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
2759 SSL_CTX_set_cipher_list(context->ssl_client_ctx, CIPHERS_LIST_STRING);
2761 /* openssl init for cert verification (for client sockets) */
2762 if (!ssl_ca_filepath) {
2763 if (!SSL_CTX_load_verify_locations(
2764 context->ssl_client_ctx, NULL,
2765 LWS_OPENSSL_CLIENT_CERTS))
2767 "Unable to load SSL Client certs from %s "
2768 "(set by --with-client-cert-dir= in configure) -- "
2769 " client ssl isn't going to work",
2770 LWS_OPENSSL_CLIENT_CERTS);
2772 if (!SSL_CTX_load_verify_locations(
2773 context->ssl_client_ctx, ssl_ca_filepath,
2776 "Unable to load SSL Client certs "
2777 "file from %s -- client ssl isn't "
2778 "going to work", ssl_ca_filepath);
2781 * callback allowing user code to load extra verification certs
2782 * helping the client to verify server identity
2785 context->protocols[0].callback(context, NULL,
2786 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
2787 context->ssl_client_ctx, NULL, 0);
2790 /* as a server, are we requiring clients to identify themselves? */
2792 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
2794 /* absolutely require the client cert */
2796 SSL_CTX_set_verify(context->ssl_ctx,
2797 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2798 OpenSSL_verify_callback);
2801 * give user code a chance to load certs into the server
2802 * allowing it to verify incoming client certs
2805 context->protocols[0].callback(context, NULL,
2806 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
2807 context->ssl_ctx, NULL, 0);
2810 if (context->use_ssl) {
2812 /* openssl init for server sockets */
2814 /* set the local certificate from CertFile */
2815 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
2818 fprintf(stderr, "problem getting cert '%s': %s\n",
2820 ERR_error_string(ERR_get_error(), ssl_err_buf));
2823 /* set the private key from KeyFile */
2824 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2825 ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
2826 fprintf(stderr, "ssl problem getting key '%s': %s\n",
2827 ssl_private_key_filepath,
2828 ERR_error_string(ERR_get_error(), ssl_err_buf));
2831 /* verify private key */
2832 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
2833 fprintf(stderr, "Private SSL key doesn't match cert\n");
2837 /* SSL is happy and has a cert it's content with */
2843 if (lws_b64_selftest())
2846 /* fd hashtable init */
2848 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
2849 context->fd_hashtable[n].length = 0;
2851 /* set up our external listening socket we serve on */
2855 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2857 fprintf(stderr, "ERROR opening socket");
2861 /* allow us to restart even if old sockets in TIME_WAIT */
2862 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2863 (const void *)&opt, sizeof(opt));
2867 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2868 (const void *)&opt, sizeof(opt));
2870 bzero((char *) &serv_addr, sizeof(serv_addr));
2871 serv_addr.sin_family = AF_INET;
2873 serv_addr.sin_addr.s_addr = INADDR_ANY;
2875 interface_to_sa(interf, &serv_addr,
2877 serv_addr.sin_port = htons(port);
2879 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2882 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2887 wsi = malloc(sizeof(struct libwebsocket));
2888 memset(wsi, 0, sizeof(struct libwebsocket));
2890 wsi->count_active_extensions = 0;
2891 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2892 insert_wsi(context, wsi);
2894 listen(sockfd, SOMAXCONN);
2895 fprintf(stderr, " Listening on port %d\n", port);
2897 /* list in the internal poll array */
2899 context->fds[context->fds_count].fd = sockfd;
2900 context->fds[context->fds_count++].events = POLLIN;
2902 /* external POLL support via protocol 0 */
2903 context->protocols[0].callback(context, wsi,
2904 LWS_CALLBACK_ADD_POLL_FD,
2905 (void *)(long)sockfd, NULL, POLLIN);
2910 * drop any root privs for this process
2911 * to listen on port < 1023 we would have needed root, but now we are
2912 * listening, we don't want the power for anything else
2918 fprintf(stderr, "setgid: %s\n", strerror(errno));
2921 fprintf(stderr, "setuid: %s\n", strerror(errno));
2924 /* set up our internal broadcast trigger sockets per-protocol */
2926 for (context->count_protocols = 0;
2927 protocols[context->count_protocols].callback;
2928 context->count_protocols++) {
2930 debug(" Protocol: %s\n", protocols[context->count_protocols].name);
2932 protocols[context->count_protocols].owning_server = context;
2933 protocols[context->count_protocols].protocol_index =
2934 context->count_protocols;
2936 fd = socket(AF_INET, SOCK_STREAM, 0);
2938 fprintf(stderr, "ERROR opening socket");
2942 /* allow us to restart even if old sockets in TIME_WAIT */
2943 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt,
2946 bzero((char *) &serv_addr, sizeof(serv_addr));
2947 serv_addr.sin_family = AF_INET;
2948 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2949 serv_addr.sin_port = 0; /* pick the port for us */
2951 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2953 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2958 slen = sizeof cli_addr;
2959 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2961 fprintf(stderr, "getsockname failed\n");
2964 protocols[context->count_protocols].broadcast_socket_port =
2965 ntohs(cli_addr.sin_port);
2968 debug(" Protocol %s broadcast socket %d\n",
2969 protocols[context->count_protocols].name,
2970 ntohs(cli_addr.sin_port));
2972 /* dummy wsi per broadcast proxy socket */
2974 wsi = malloc(sizeof(struct libwebsocket));
2975 memset(wsi, 0, sizeof(struct libwebsocket));
2977 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
2978 wsi->count_active_extensions = 0;
2979 /* note which protocol we are proxying */
2980 wsi->protocol_index_for_broadcast_proxy =
2981 context->count_protocols;
2982 insert_wsi(context, wsi);
2984 /* list in internal poll array */
2986 context->fds[context->fds_count].fd = fd;
2987 context->fds[context->fds_count].events = POLLIN;
2988 context->fds[context->fds_count].revents = 0;
2989 context->fds_count++;
2991 /* external POLL support via protocol 0 */
2992 context->protocols[0].callback(context, wsi,
2993 LWS_CALLBACK_ADD_POLL_FD,
2994 (void *)(long)fd, NULL, POLLIN);
2998 * give all extensions a chance to create any per-context
2999 * allocations they need
3002 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
3004 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
3007 while (extensions->callback) {
3008 debug(" Extension: %s\n", extensions->name);
3009 extensions->callback(context, extensions,
3010 NULL, m, NULL, NULL, 0);
3022 * libwebsockets_fork_service_loop() - Optional helper function forks off
3023 * a process for the websocket server loop.
3024 * You don't have to use this but if not, you
3025 * have to make sure you are calling
3026 * libwebsocket_service periodically to service
3027 * the websocket traffic
3028 * @context: server context returned by creation function
3032 libwebsockets_fork_service_loop(struct libwebsocket_context *context)
3035 struct sockaddr_in cli_addr;
3045 /* main process context */
3048 * set up the proxy sockets to allow broadcast from
3049 * service process context
3052 for (p = 0; p < context->count_protocols; p++) {
3053 fd = socket(AF_INET, SOCK_STREAM, 0);
3055 fprintf(stderr, "Unable to create socket\n");
3058 cli_addr.sin_family = AF_INET;
3059 cli_addr.sin_port = htons(
3060 context->protocols[p].broadcast_socket_port);
3061 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
3062 n = connect(fd, (struct sockaddr *)&cli_addr,
3065 fprintf(stderr, "Unable to connect to "
3066 "broadcast socket %d, %s\n",
3067 n, strerror(errno));
3071 context->protocols[p].broadcast_socket_user_fd = fd;
3077 #ifdef HAVE_SYS_PRCTL_H
3078 /* we want a SIGHUP when our parent goes down */
3079 prctl(PR_SET_PDEATHSIG, SIGHUP);
3082 /* in this forked process, sit and service websocket connections */
3085 if (libwebsocket_service(context, 1000))
3087 //#ifndef HAVE_SYS_PRCTL_H
3089 * on systems without prctl() (i.e. anything but linux) we can notice that our
3090 * parent is dead if getppid() returns 1. FIXME apparently this is not true for
3091 * solaris, could remember ppid right after fork and wait for it to change.
3106 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
3108 * @wsi: pointer to struct websocket you want to know the protocol of
3111 * This is useful to get the protocol to broadcast back to from inside
3115 const struct libwebsocket_protocols *
3116 libwebsockets_get_protocol(struct libwebsocket *wsi)
3118 return wsi->protocol;
3122 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
3123 * connections of the given protocol.
3124 * @protocol: pointer to the protocol you will broadcast to all members of
3125 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
3126 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
3127 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
3128 * case you are calling this function from callback context.
3129 * @len: length of payload data in buf, starting from buf.
3131 * This function allows bulk sending of a packet to every connection using
3132 * the given protocol. It does not send the data directly; instead it calls
3133 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
3134 * wants to actually send the data for that connection, the callback itself
3135 * should call libwebsocket_write().
3137 * libwebsockets_broadcast() can be called from another fork context without
3138 * having to take any care about data visibility between the processes, it'll
3144 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
3145 unsigned char *buf, size_t len)
3147 struct libwebsocket_context *context = protocol->owning_server;
3150 struct libwebsocket *wsi;
3152 if (!protocol->broadcast_socket_user_fd) {
3154 * We are either running unforked / flat, or we are being
3155 * called from poll thread context
3156 * eg, from a callback. In that case don't use sockets for
3157 * broadcast IPC (since we can't open a socket connection to
3158 * a socket listening on our own thread) but directly do the
3161 * Locking is not needed because we are by definition being
3162 * called in the poll thread context and are serialized.
3165 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
3167 for (m = 0; m < context->fd_hashtable[n].length; m++) {
3169 wsi = context->fd_hashtable[n].wsi[m];
3171 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
3175 * never broadcast to
3176 * non-established connections
3178 if (wsi->state != WSI_STATE_ESTABLISHED)
3181 /* only broadcast to guys using
3182 * requested protocol
3184 if (wsi->protocol != protocol)
3187 wsi->protocol->callback(context, wsi,
3188 LWS_CALLBACK_BROADCAST,
3198 * We're being called from a different process context than the server
3199 * loop. Instead of broadcasting directly, we send our
3200 * payload on a socket to do the IPC; the server process will serialize
3201 * the broadcast action in its main poll() loop.
3203 * There's one broadcast socket listening for each protocol supported
3204 * set up when the websocket server initializes
3207 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
3213 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
3219 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
3225 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
3227 /* allocate the per-connection user memory (if any) */
3229 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
3230 wsi->user_space = malloc(
3231 wsi->protocol->per_session_data_size);
3232 if (wsi->user_space == NULL) {
3233 fprintf(stderr, "Out of memory for "
3234 "conn user space\n");
3237 memset(wsi->user_space, 0,
3238 wsi->protocol->per_session_data_size);
3240 return wsi->user_space;