2
0

testwebsock2.c 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * Copyright (c) 2018-2019 SignalWire, Inc
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in all
  12. * copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. /*
  23. ./testwebsock2 wss://echo.websocket.org/echo
  24. ./testwebsock2 ws://laml:9393/websocket
  25. */
  26. #include "libks/ks.h"
  27. #include <tap.h>
  28. #ifdef _WINDOWS_
  29. #undef unlink
  30. #define unlink _unlink
  31. #endif
  32. #define SHA1_HASH_SIZE 20
  33. #define WEBSOCKET_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  34. #define B64BUFFLEN 1024
  35. #define LISTEN_PORT 8090
  36. #define __MSG "\"welcome\""
  37. static const char c64[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  38. struct tcp_data {
  39. ks_socket_t sock;
  40. ks_sockaddr_t addr;
  41. int ready;
  42. char *ip;
  43. };
  44. static int b64encode(unsigned char *in, size_t ilen, unsigned char *out, size_t olen)
  45. {
  46. int y=0,bytes=0;
  47. size_t x=0;
  48. unsigned int b=0,l=0;
  49. if(olen) {
  50. }
  51. for(x=0;x<ilen;x++) {
  52. b = (b<<8) + in[x];
  53. l += 8;
  54. while (l >= 6) {
  55. out[bytes++] = c64[(b>>(l-=6))%64];
  56. if(++y!=72) {
  57. continue;
  58. }
  59. //out[bytes++] = '\n';
  60. y=0;
  61. }
  62. }
  63. if (l > 0) {
  64. out[bytes++] = c64[((b%16)<<(6-l))%64];
  65. }
  66. if (l != 0) while (l < 6) {
  67. out[bytes++] = '=', l += 2;
  68. }
  69. return 0;
  70. }
  71. #ifdef NO_OPENSSL
  72. static void sha1_digest(char *digest, unsigned char *in)
  73. {
  74. SHA1Context sha;
  75. char *p;
  76. int x;
  77. SHA1Init(&sha);
  78. SHA1Update(&sha, in, strlen(in));
  79. SHA1Final(&sha, digest);
  80. }
  81. #else
  82. static void sha1_digest(unsigned char *digest, char *in)
  83. {
  84. SHA_CTX sha;
  85. SHA1_Init(&sha);
  86. SHA1_Update(&sha, in, strlen(in));
  87. SHA1_Final(digest, &sha);
  88. }
  89. #endif
  90. static uint64_t hton64(uint64_t val)
  91. {
  92. if (__BYTE_ORDER == __BIG_ENDIAN) return (val);
  93. else return __bswap_64(val);
  94. }
  95. static uint64_t ntoh64(uint64_t val)
  96. {
  97. if (__BYTE_ORDER == __BIG_ENDIAN) return (val);
  98. else return __bswap_64(val);
  99. }
  100. static ssize_t append_text_frame(void *bp)
  101. {
  102. uint8_t hdr[14] = { 0 };
  103. size_t hlen = 2;
  104. ssize_t raw_ret = 0;
  105. char *data = __MSG;
  106. size_t bytes = strlen(data);
  107. hdr[0] = (uint8_t)(WSOC_TEXT | 0x80);
  108. if (bytes < 126) {
  109. hdr[1] = (uint8_t)bytes;
  110. } else if (bytes < 0x10000) {
  111. uint16_t *u16;
  112. hdr[1] = 126;
  113. hlen += 2;
  114. u16 = (uint16_t *) &hdr[2];
  115. *u16 = htons((uint16_t) bytes);
  116. } else {
  117. uint64_t *u64;
  118. hdr[1] = 127;
  119. hlen += 8;
  120. u64 = (uint64_t *) &hdr[2];
  121. *u64 = hton64(bytes);
  122. }
  123. memcpy(bp, (void *) &hdr[0], hlen);
  124. memcpy(bp + hlen, data, bytes);
  125. *(uint8_t *)(bp + hlen + bytes) = '\0';
  126. return hlen + bytes;
  127. }
  128. static void server_callback(ks_socket_t server_sock, ks_socket_t client_sock, ks_sockaddr_t *addr, void *user_data)
  129. {
  130. //struct tcp_data *tcp_data = (struct tcp_data *) user_data;
  131. char buf[8192] = "";
  132. ks_status_t status;
  133. ks_size_t bytes;
  134. char key[1024] = "";
  135. char input[512] = "";
  136. unsigned char output[SHA1_HASH_SIZE] = "";
  137. char b64[256] = "";
  138. printf("TCP SERVER SOCK %d connection from %s:%u\n", (int)server_sock, addr->host, addr->port);
  139. do {
  140. bytes = sizeof(buf);;
  141. status = ks_socket_recv(client_sock, buf, &bytes);
  142. if (status != KS_STATUS_SUCCESS) {
  143. printf("TCP SERVER BAIL %s\n", strerror(ks_errno()));
  144. break;
  145. }
  146. printf("TCP SERVER READ %ld bytes [%s]\n", (long)bytes, buf);
  147. } while(ks_zstr_buf(buf) || !strstr(buf, "\r\n\r\n"));
  148. char *k = strstr(buf, "Sec-WebSocket-Key:");
  149. ks_assert(k);
  150. k += strlen("Sec-WebSocket-Key:");
  151. if (*k == ' ') k++;
  152. char *p = strchr(k, '\r');
  153. ks_assert(p);
  154. *p++ = '\0';
  155. strncpy(key, k, sizeof(key));
  156. snprintf(input, sizeof(input), "%s%s", key, WEBSOCKET_GUID);
  157. sha1_digest(output, input);
  158. b64encode((unsigned char *)output, SHA1_HASH_SIZE, (unsigned char *)b64, sizeof(b64));
  159. snprintf(buf, sizeof(buf),
  160. "HTTP/1.1 101 Switching Protocols\r\n"
  161. "Upgrade: websocket\r\n"
  162. "Connection: Upgrade\r\n"
  163. "Sec-WebSocket-Accept: %s\r\n\r\n",
  164. b64);
  165. bytes = strlen(buf);
  166. bytes += append_text_frame(buf + strlen(buf));
  167. printf("%s\n", buf);
  168. ks_socket_send(client_sock, buf, &bytes);
  169. printf("TCP SERVER WRITE %ld bytes\n", (long)bytes);
  170. ks_socket_close(&client_sock);
  171. printf("TCP SERVER COMPLETE\n");
  172. }
  173. static void *tcp_sock_server(ks_thread_t *thread, void *thread_data)
  174. {
  175. struct tcp_data *tcp_data = (struct tcp_data *) thread_data;
  176. tcp_data->ready = 1;
  177. ks_listen_sock(tcp_data->sock, &tcp_data->addr, 0, server_callback, tcp_data);
  178. printf("TCP THREAD DONE\n");
  179. return NULL;
  180. }
  181. static int test_ws(char *url);
  182. static int start_tcp_server_and_test_ws(char *ip)
  183. {
  184. ks_thread_t *thread_p = NULL;
  185. ks_pool_t *pool;
  186. ks_sockaddr_t addr;
  187. int family = AF_INET;
  188. ks_socket_t cl_sock = KS_SOCK_INVALID;
  189. char buf[8192] = "";
  190. struct tcp_data tcp_data = { 0 };
  191. int sanity = 100;
  192. ks_pool_open(&pool);
  193. if (ks_addr_set(&tcp_data.addr, ip, LISTEN_PORT, family) != KS_STATUS_SUCCESS) {
  194. printf("TCP CLIENT Can't set ADDR\n");
  195. goto end;
  196. }
  197. if ((tcp_data.sock = socket(family, SOCK_STREAM, IPPROTO_TCP)) == KS_SOCK_INVALID) {
  198. printf("TCP CLIENT Can't create sock family %d\n", family);
  199. goto end;
  200. }
  201. ks_socket_option(tcp_data.sock, SO_REUSEADDR, KS_TRUE);
  202. ks_socket_option(tcp_data.sock, TCP_NODELAY, KS_TRUE);
  203. tcp_data.ip = ip;
  204. ks_thread_create(&thread_p, tcp_sock_server, &tcp_data, pool);
  205. while(!tcp_data.ready && --sanity > 0) {
  206. ks_sleep(10000);
  207. }
  208. char url[1024];
  209. snprintf(url, sizeof(url), "ws://127.0.0.1:%d/test", LISTEN_PORT);
  210. test_ws(url);
  211. end:
  212. if (tcp_data.sock != KS_SOCK_INVALID) {
  213. ks_socket_shutdown(tcp_data.sock, 2);
  214. ks_socket_close(&tcp_data.sock);
  215. }
  216. if (thread_p) {
  217. ks_thread_join(thread_p);
  218. }
  219. ks_socket_close(&cl_sock);
  220. ks_pool_close(&pool);
  221. }
  222. static int test_ws(char *url)
  223. {
  224. kws_t *kws = NULL;
  225. ks_pool_t *pool;
  226. kws_opcode_t oc;
  227. uint8_t *rdata;
  228. ks_ssize_t ret;
  229. ks_json_t *req = ks_json_create_object();
  230. ks_json_add_string_to_object(req, "url", url);
  231. ks_global_set_default_logger(7);
  232. ks_pool_open(&pool);
  233. ks_assert(pool);
  234. ok(kws_connect_ex(&kws, req, KWS_BLOCK | KWS_CLOSE_SOCK, pool, NULL, 3000) == KS_STATUS_SUCCESS);
  235. printf("websocket connected to [%s]\n", url);
  236. ks_json_delete(&req);
  237. ks_ssize_t bytes;
  238. kws_write_frame(kws, WSOC_TEXT, __MSG, strlen(__MSG));
  239. int32_t poll_flags = 0;
  240. while (1) {
  241. poll_flags = kws_wait_sock(kws, 50, KS_POLL_READ | KS_POLL_ERROR);
  242. if (poll_flags == KS_POLL_READ) break;
  243. }
  244. bytes = kws_read_frame(kws, &oc, &rdata);
  245. printf("read bytes=%d oc=%d [%s]\n", bytes, oc, (char *)rdata);
  246. ok(oc == WSOC_TEXT);
  247. if (bytes < 0 || oc != WSOC_TEXT || !rdata || !strstr((char *)rdata, "\"welcome\"")) {
  248. printf("read bytes=%d oc=%d [%s]\n", bytes, oc, (char *)rdata);
  249. }
  250. ok(rdata != NULL && strstr((char *)rdata, __MSG) != NULL);
  251. kws_destroy(&kws);
  252. ks_pool_close(&pool);
  253. return 1;
  254. }
  255. int main(int argc, char *argv[])
  256. {
  257. char *url = NULL;
  258. ks_init();
  259. plan(3);
  260. if (argc > 1 && strstr(argv[1], "ws") == argv[1]) {
  261. url = argv[1];
  262. test_ws(url);
  263. } else {
  264. start_tcp_server_and_test_ws("127.0.0.1");
  265. }
  266. ks_shutdown();
  267. done_testing();
  268. }