testwebsock2.c 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /*
  2. * Copyright (c) 2018-2023 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 inline uint64_t BSwap64(uint64_t x) {
  91. #if defined(__x86_64__)
  92. uint64_t swapped_bytes;
  93. __asm__ volatile("bswapq %0" : "=r"(swapped_bytes) : "0"(x));
  94. return swapped_bytes;
  95. #elif defined(_MSC_VER)
  96. return (uint64_t)_byteswap_uint64(x);
  97. #else // generic code for swapping 64-bit values (suggested by bdb@)
  98. x = ((x & 0xffffffff00000000ull) >> 32) | ((x & 0x00000000ffffffffull) << 32);
  99. x = ((x & 0xffff0000ffff0000ull) >> 16) | ((x & 0x0000ffff0000ffffull) << 16);
  100. x = ((x & 0xff00ff00ff00ff00ull) >> 8) | ((x & 0x00ff00ff00ff00ffull) << 8);
  101. return x;
  102. #endif
  103. }
  104. static uint64_t hton64(uint64_t val)
  105. {
  106. if (KS_BIG_ENDIAN) return (val);
  107. else return BSwap64(val);
  108. }
  109. static uint64_t ntoh64(uint64_t val)
  110. {
  111. if (KS_BIG_ENDIAN) return (val);
  112. else return BSwap64(val);
  113. }
  114. static ssize_t append_text_frame(void *bp)
  115. {
  116. uint8_t hdr[14] = { 0 };
  117. size_t hlen = 2;
  118. ssize_t raw_ret = 0;
  119. char *data = __MSG;
  120. size_t bytes = strlen(data);
  121. hdr[0] = (uint8_t)(WSOC_TEXT | 0x80);
  122. if (bytes < 126) {
  123. hdr[1] = (uint8_t)bytes;
  124. } else if (bytes < 0x10000) {
  125. uint16_t *u16;
  126. hdr[1] = 126;
  127. hlen += 2;
  128. u16 = (uint16_t *) &hdr[2];
  129. *u16 = htons((uint16_t) bytes);
  130. } else {
  131. uint64_t *u64;
  132. hdr[1] = 127;
  133. hlen += 8;
  134. u64 = (uint64_t *) &hdr[2];
  135. *u64 = hton64(bytes);
  136. }
  137. memcpy(bp, (void *) &hdr[0], hlen);
  138. memcpy((unsigned char *)bp + hlen, data, bytes);
  139. *(uint8_t *)((unsigned char *)bp + hlen + bytes) = '\0';
  140. return hlen + bytes;
  141. }
  142. static void server_callback(ks_socket_t server_sock, ks_socket_t client_sock, ks_sockaddr_t *addr, void *user_data)
  143. {
  144. //struct tcp_data *tcp_data = (struct tcp_data *) user_data;
  145. char buf[8192] = "";
  146. ks_status_t status;
  147. ks_size_t bytes;
  148. char key[1024] = "";
  149. char input[512] = "";
  150. unsigned char output[SHA1_HASH_SIZE] = "";
  151. char b64[256] = "";
  152. printf("TCP SERVER SOCK %d connection from %s:%u\n", (int)server_sock, addr->host, addr->port);
  153. do {
  154. bytes = sizeof(buf);;
  155. status = ks_socket_recv(client_sock, buf, &bytes);
  156. if (status != KS_STATUS_SUCCESS) {
  157. printf("TCP SERVER BAIL %s\n", strerror(ks_errno()));
  158. break;
  159. }
  160. printf("TCP SERVER READ %ld bytes [%s]\n", (long)bytes, buf);
  161. } while(ks_zstr_buf(buf) || !strstr(buf, "\r\n\r\n"));
  162. char *k = strstr(buf, "Sec-WebSocket-Key:");
  163. ks_assert(k);
  164. k += strlen("Sec-WebSocket-Key:");
  165. if (*k == ' ') k++;
  166. char *p = strchr(k, '\r');
  167. ks_assert(p);
  168. *p++ = '\0';
  169. strncpy(key, k, sizeof(key));
  170. snprintf(input, sizeof(input), "%s%s", key, WEBSOCKET_GUID);
  171. sha1_digest(output, input);
  172. b64encode((unsigned char *)output, SHA1_HASH_SIZE, (unsigned char *)b64, sizeof(b64));
  173. snprintf(buf, sizeof(buf),
  174. "HTTP/1.1 101 Switching Protocols\r\n"
  175. "Upgrade: websocket\r\n"
  176. "Connection: Upgrade\r\n"
  177. "Sec-WebSocket-Accept: %s\r\n\r\n",
  178. b64);
  179. bytes = strlen(buf);
  180. bytes += append_text_frame(buf + strlen(buf));
  181. printf("%s\n", buf);
  182. ks_socket_send(client_sock, buf, &bytes);
  183. printf("TCP SERVER WRITE %ld bytes\n", (long)bytes);
  184. ks_socket_close(&client_sock);
  185. printf("TCP SERVER COMPLETE\n");
  186. }
  187. static void *tcp_sock_server(ks_thread_t *thread, void *thread_data)
  188. {
  189. struct tcp_data *tcp_data = (struct tcp_data *) thread_data;
  190. tcp_data->ready = 1;
  191. ks_listen_sock(tcp_data->sock, &tcp_data->addr, 0, server_callback, tcp_data);
  192. printf("TCP THREAD DONE\n");
  193. return NULL;
  194. }
  195. static int test_ws(char *url);
  196. static void start_tcp_server_and_test_ws(char *ip)
  197. {
  198. ks_thread_t *thread_p = NULL;
  199. ks_pool_t *pool;
  200. int family = AF_INET;
  201. ks_socket_t cl_sock = KS_SOCK_INVALID;
  202. char buf[8192] = "";
  203. struct tcp_data tcp_data = { 0 };
  204. int sanity = 100;
  205. ks_pool_open(&pool);
  206. if (ks_addr_set(&tcp_data.addr, ip, LISTEN_PORT, family) != KS_STATUS_SUCCESS) {
  207. printf("TCP CLIENT Can't set ADDR\n");
  208. goto end;
  209. }
  210. if ((tcp_data.sock = socket(family, SOCK_STREAM, IPPROTO_TCP)) == KS_SOCK_INVALID) {
  211. printf("TCP CLIENT Can't create sock family %d\n", family);
  212. goto end;
  213. }
  214. ks_socket_option(tcp_data.sock, SO_REUSEADDR, KS_TRUE);
  215. ks_socket_option(tcp_data.sock, TCP_NODELAY, KS_TRUE);
  216. tcp_data.ip = ip;
  217. ks_thread_create(&thread_p, tcp_sock_server, &tcp_data, pool);
  218. while(!tcp_data.ready && --sanity > 0) {
  219. ks_sleep(10000);
  220. }
  221. char url[1024];
  222. snprintf(url, sizeof(url), "ws://127.0.0.1:%d/test", LISTEN_PORT);
  223. test_ws(url);
  224. end:
  225. if (tcp_data.sock != KS_SOCK_INVALID) {
  226. ks_socket_shutdown(tcp_data.sock, 2);
  227. ks_socket_close(&tcp_data.sock);
  228. }
  229. if (thread_p) {
  230. ks_thread_join(thread_p);
  231. }
  232. ks_socket_close(&cl_sock);
  233. ks_pool_close(&pool);
  234. }
  235. static int test_ws(char *url)
  236. {
  237. kws_t *kws = NULL;
  238. ks_pool_t *pool;
  239. kws_opcode_t oc;
  240. uint8_t *rdata;
  241. ks_json_t *req = ks_json_create_object();
  242. ks_json_add_string_to_object(req, "url", url);
  243. ks_json_t *headers = ks_json_create_array();
  244. ks_json_add_item_to_object(req, "headers", headers);
  245. ks_json_t *param = ks_json_create_object();
  246. ks_json_add_string_to_object(param, "key", "X-Auth-Token");
  247. ks_json_add_string_to_object(param, "value", "xxxx");
  248. ks_json_add_item_to_array(headers, param);
  249. param = ks_json_create_object();
  250. ks_json_add_string_to_object(param, "key", "Agent");
  251. ks_json_add_string_to_object(param, "value", "libks");
  252. ks_json_add_item_to_array(headers, param);
  253. ks_global_set_log_level(7);
  254. ks_pool_open(&pool);
  255. ks_assert(pool);
  256. ok(kws_connect_ex(&kws, req, KWS_BLOCK | KWS_CLOSE_SOCK, pool, NULL, 3000) == KS_STATUS_SUCCESS);
  257. printf("websocket connected to [%s]\n", url);
  258. ks_json_delete(&req);
  259. ks_ssize_t bytes;
  260. kws_write_frame(kws, WSOC_TEXT, __MSG, strlen(__MSG));
  261. int32_t poll_flags = 0;
  262. while (1) {
  263. poll_flags = kws_wait_sock(kws, 50, KS_POLL_READ | KS_POLL_ERROR);
  264. if (poll_flags == KS_POLL_READ) break;
  265. }
  266. bytes = kws_read_frame(kws, &oc, &rdata);
  267. printf("read bytes=%d oc=%d [%s]\n", (int)bytes, oc, (char *)rdata);
  268. ok(oc == WSOC_TEXT);
  269. if (bytes < 0 || oc != WSOC_TEXT || !rdata || !strstr((char *)rdata, "\"welcome\"")) {
  270. printf("read bytes=%d oc=%d [%s]\n", (int)bytes, oc, (char *)rdata);
  271. }
  272. ok(rdata != NULL && strstr((char *)rdata, __MSG) != NULL);
  273. kws_destroy(&kws);
  274. ks_pool_close(&pool);
  275. return 1;
  276. }
  277. int main(int argc, char *argv[])
  278. {
  279. char *url = NULL;
  280. ks_init();
  281. ks_log_jsonify();
  282. plan(3);
  283. if (argc > 1 && strstr(argv[1], "ws") == argv[1]) {
  284. url = argv[1];
  285. test_ws(url);
  286. } else {
  287. start_tcp_server_and_test_ws("127.0.0.1");
  288. }
  289. ks_shutdown();
  290. done_testing();
  291. }