ws.c 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. #include <switch.h>
  2. #include "ws.h"
  3. #include <pthread.h>
  4. #ifndef _MSC_VER
  5. #include <fcntl.h>
  6. #endif
  7. #if defined(__linux__) || defined(__GLIBC__)
  8. #include <byteswap.h>
  9. #endif
  10. #ifndef _MSC_VER
  11. #define ms_sleep(x) usleep( x * 1000);
  12. #else
  13. #define ms_sleep(x) Sleep( x );
  14. #endif
  15. #ifdef _MSC_VER
  16. /* warning C4706: assignment within conditional expression*/
  17. #pragma warning(disable: 4706)
  18. #endif
  19. #define WS_BLOCK 10000 /* ms, blocks read operation for 10 seconds */
  20. #define WS_SOFT_BLOCK 1000 /* ms, blocks read operation for 1 second */
  21. #define WS_NOBLOCK 0
  22. #define WS_INIT_SANITY 5000
  23. #define WS_WRITE_SANITY 200
  24. #define SHA1_HASH_SIZE 20
  25. static struct ws_globals_s ws_globals;
  26. ssize_t ws_global_payload_size_max = 0;
  27. #ifndef WSS_STANDALONE
  28. void init_ssl(void)
  29. {
  30. // SSL_library_init();
  31. SSL_load_error_strings();
  32. }
  33. void deinit_ssl(void)
  34. {
  35. return;
  36. }
  37. #else
  38. static void pthreads_thread_id(CRYPTO_THREADID *id);
  39. static void pthreads_locking_callback(int mode, int type, const char *file, int line);
  40. static pthread_mutex_t *lock_cs;
  41. static long *lock_count;
  42. static void thread_setup(void)
  43. {
  44. int i;
  45. lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
  46. lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
  47. for (i = 0; i < CRYPTO_num_locks(); i++) {
  48. lock_count[i] = 0;
  49. pthread_mutex_init(&(lock_cs[i]), NULL);
  50. }
  51. CRYPTO_THREADID_set_callback(pthreads_thread_id);
  52. CRYPTO_set_locking_callback(pthreads_locking_callback);
  53. }
  54. static void thread_cleanup(void)
  55. {
  56. int i;
  57. CRYPTO_set_locking_callback(NULL);
  58. for (i=0; i<CRYPTO_num_locks(); i++) {
  59. pthread_mutex_destroy(&(lock_cs[i]));
  60. }
  61. OPENSSL_free(lock_cs);
  62. OPENSSL_free(lock_count);
  63. }
  64. static void pthreads_locking_callback(int mode, int type, const char *file, int line)
  65. {
  66. if (mode & CRYPTO_LOCK) {
  67. pthread_mutex_lock(&(lock_cs[type]));
  68. lock_count[type]++;
  69. } else {
  70. pthread_mutex_unlock(&(lock_cs[type]));
  71. }
  72. }
  73. static void pthreads_thread_id(CRYPTO_THREADID *id)
  74. {
  75. CRYPTO_THREADID_set_numeric(id, (unsigned long)pthread_self());
  76. }
  77. void init_ssl(void) {
  78. SSL_library_init();
  79. OpenSSL_add_all_algorithms(); /* load & register cryptos */
  80. SSL_load_error_strings(); /* load all error messages */
  81. ws_globals.ssl_method = SSLv23_server_method(); /* create server instance */
  82. ws_globals.ssl_ctx = SSL_CTX_new(ws_globals.ssl_method); /* create context */
  83. assert(ws_globals.ssl_ctx);
  84. /* Disable SSLv2 */
  85. SSL_CTX_set_options(ws_globals.ssl_ctx, SSL_OP_NO_SSLv2);
  86. /* Disable SSLv3 */
  87. SSL_CTX_set_options(ws_globals.ssl_ctx, SSL_OP_NO_SSLv3);
  88. /* Disable TLSv1 */
  89. SSL_CTX_set_options(ws_globals.ssl_ctx, SSL_OP_NO_TLSv1);
  90. /* Disable Compression CRIME (Compression Ratio Info-leak Made Easy) */
  91. SSL_CTX_set_options(ws_globals.ssl_ctx, SSL_OP_NO_COMPRESSION);
  92. /* set the local certificate from CertFile */
  93. SSL_CTX_use_certificate_file(ws_globals.ssl_ctx, ws_globals.cert, SSL_FILETYPE_PEM);
  94. /* set the private key from KeyFile */
  95. SSL_CTX_use_PrivateKey_file(ws_globals.ssl_ctx, ws_globals.key, SSL_FILETYPE_PEM);
  96. /* verify private key */
  97. if ( !SSL_CTX_check_private_key(ws_globals.ssl_ctx) ) {
  98. abort();
  99. }
  100. SSL_CTX_set_cipher_list(ws_globals.ssl_ctx, "HIGH:!DSS:!aNULL@STRENGTH");
  101. thread_setup();
  102. }
  103. void deinit_ssl(void) {
  104. thread_cleanup();
  105. }
  106. #endif
  107. static const char c64[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  108. static int cheezy_get_var(char *data, char *name, char *buf, size_t buflen)
  109. {
  110. char *p=data;
  111. /* the old way didnt make sure that variable values were used for the name hunt
  112. * and didnt ensure that only a full match of the variable name was used
  113. */
  114. do {
  115. if(!strncasecmp(p,name,strlen(name)) && *(p+strlen(name))==':') break;
  116. } while((p = (strstr(p,"\n")+1))!=(char *)1);
  117. if (p && p != (char *)1 && *p!='\0') {
  118. char *v, *e = 0;
  119. v = strchr(p, ':');
  120. if (v) {
  121. v++;
  122. while(v && *v == ' ') {
  123. v++;
  124. }
  125. if (v) {
  126. e = strchr(v, '\r');
  127. if (!e) {
  128. e = strchr(v, '\n');
  129. }
  130. }
  131. if (v && e) {
  132. int cplen;
  133. size_t len = e - v;
  134. if (len > buflen - 1) {
  135. cplen = buflen -1;
  136. } else {
  137. cplen = len;
  138. }
  139. strncpy(buf, v, cplen);
  140. *(buf+cplen) = '\0';
  141. return 1;
  142. }
  143. }
  144. }
  145. return 0;
  146. }
  147. static int b64encode(unsigned char *in, size_t ilen, unsigned char *out, size_t olen)
  148. {
  149. int y=0,bytes=0;
  150. size_t x=0;
  151. unsigned int b=0,l=0;
  152. if(olen) {
  153. }
  154. for(x=0;x<ilen;x++) {
  155. b = (b<<8) + in[x];
  156. l += 8;
  157. while (l >= 6) {
  158. out[bytes++] = c64[(b>>(l-=6))%64];
  159. if(++y!=72) {
  160. continue;
  161. }
  162. //out[bytes++] = '\n';
  163. y=0;
  164. }
  165. }
  166. if (l > 0) {
  167. out[bytes++] = c64[((b%16)<<(6-l))%64];
  168. }
  169. if (l != 0) while (l < 6) {
  170. out[bytes++] = '=', l += 2;
  171. }
  172. return 0;
  173. }
  174. #ifdef NO_OPENSSL
  175. static void sha1_digest(char *digest, unsigned char *in)
  176. {
  177. SHA1Context sha;
  178. char *p;
  179. int x;
  180. SHA1Init(&sha);
  181. SHA1Update(&sha, in, strlen(in));
  182. SHA1Final(&sha, digest);
  183. }
  184. #else
  185. static void sha1_digest(unsigned char *digest, char *in)
  186. {
  187. SHA_CTX sha;
  188. SHA1_Init(&sha);
  189. SHA1_Update(&sha, in, strlen(in));
  190. SHA1_Final(digest, &sha);
  191. }
  192. #endif
  193. int ws_handshake(wsh_t *wsh)
  194. {
  195. char key[256] = "";
  196. char version[5] = "";
  197. char proto[256] = "";
  198. char proto_buf[384] = "";
  199. char input[512] = "";
  200. unsigned char output[SHA1_HASH_SIZE] = "";
  201. char b64[256] = "";
  202. char respond[1024] = "";
  203. ssize_t bytes;
  204. char *p, *e = 0;
  205. if (wsh->sock == ws_sock_invalid) {
  206. return -3;
  207. }
  208. while((bytes = ws_raw_read(wsh, wsh->buffer + wsh->datalen, wsh->buflen - wsh->datalen, WS_NOBLOCK)) > 0) {
  209. wsh->datalen += bytes;
  210. if (strstr(wsh->buffer, "\r\n\r\n") || strstr(wsh->buffer, "\n\n")) {
  211. break;
  212. }
  213. }
  214. if (bytes < 0 || bytes > wsh->buflen -1) {
  215. goto err;
  216. }
  217. *(wsh->buffer + wsh->datalen) = '\0';
  218. if (strncasecmp(wsh->buffer, "GET ", 4)) {
  219. goto err;
  220. }
  221. p = wsh->buffer + 4;
  222. e = strchr(p, ' ');
  223. if (!e) {
  224. goto err;
  225. }
  226. wsh->uri = malloc((e-p) + 1);
  227. if (!wsh->uri) goto err;
  228. strncpy(wsh->uri, p, e-p);
  229. *(wsh->uri + (e-p)) = '\0';
  230. cheezy_get_var(wsh->buffer, "Sec-WebSocket-Key", key, sizeof(key));
  231. cheezy_get_var(wsh->buffer, "Sec-WebSocket-Version", version, sizeof(version));
  232. cheezy_get_var(wsh->buffer, "Sec-WebSocket-Protocol", proto, sizeof(proto));
  233. if (!*key) {
  234. goto err;
  235. }
  236. snprintf(input, sizeof(input), "%s%s", key, WEBSOCKET_GUID);
  237. sha1_digest(output, input);
  238. b64encode((unsigned char *)output, SHA1_HASH_SIZE, (unsigned char *)b64, sizeof(b64));
  239. if (*proto) {
  240. snprintf(proto_buf, sizeof(proto_buf), "Sec-WebSocket-Protocol: %s\r\n", proto);
  241. }
  242. snprintf(respond, sizeof(respond),
  243. "HTTP/1.1 101 Switching Protocols\r\n"
  244. "Upgrade: websocket\r\n"
  245. "Connection: Upgrade\r\n"
  246. "Sec-WebSocket-Accept: %s\r\n"
  247. "%s\r\n",
  248. b64,
  249. proto_buf);
  250. respond[511] = 0;
  251. if (ws_raw_write(wsh, respond, strlen(respond)) != (ssize_t)strlen(respond)) {
  252. goto err;
  253. }
  254. wsh->handshake = 1;
  255. return 0;
  256. err:
  257. if (!wsh->stay_open) {
  258. if (bytes > 0) {
  259. snprintf(respond, sizeof(respond), "HTTP/1.1 400 Bad Request\r\n"
  260. "Sec-WebSocket-Version: 13\r\n\r\n");
  261. respond[511] = 0;
  262. ws_raw_write(wsh, respond, strlen(respond));
  263. }
  264. if (bytes == -2) {
  265. return 0;
  266. }
  267. ws_close(wsh, WS_NONE);
  268. }
  269. return -1;
  270. }
  271. #define SSL_IO_ERROR(err) (err == SSL_ERROR_SYSCALL || err == SSL_ERROR_SSL)
  272. #define SSL_WANT_READ_WRITE(err) (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE)
  273. int wss_error(wsh_t *wsh, int ssl_err, char const *who);
  274. ssize_t ws_raw_read(wsh_t *wsh, void *data, size_t bytes, int block)
  275. {
  276. ssize_t r;
  277. int ssl_err = 0;
  278. int block_n = block / 10;
  279. wsh->x++;
  280. if (wsh->x > 250) ms_sleep(1);
  281. if (wsh->ssl) {
  282. do {
  283. //ERR_clear_error();
  284. r = SSL_read(wsh->ssl, data, bytes);
  285. if (r <= 0) {
  286. ssl_err = SSL_get_error(wsh->ssl, r);
  287. if (SSL_WANT_READ_WRITE(ssl_err)) {
  288. if (!block) {
  289. r = -2;
  290. goto end;
  291. }
  292. wsh->x++;
  293. ms_sleep(10);
  294. } else {
  295. wss_error(wsh, ssl_err, "ws_raw_read: SSL_read");
  296. if (SSL_IO_ERROR(ssl_err)) {
  297. wsh->ssl_io_error = 1;
  298. }
  299. r = -1;
  300. goto end;
  301. }
  302. }
  303. } while (r < 0 && SSL_WANT_READ_WRITE(ssl_err) && wsh->x < block_n);
  304. goto end;
  305. }
  306. do {
  307. r = recv(wsh->sock, data, bytes, 0);
  308. if (r == -1) {
  309. if (!block && xp_is_blocking(xp_errno())) {
  310. r = -2;
  311. goto end;
  312. }
  313. if (block) {
  314. wsh->x++;
  315. ms_sleep(10);
  316. }
  317. }
  318. } while (r == -1 && xp_is_blocking(xp_errno()) && wsh->x < block_n);
  319. end:
  320. if (wsh->x >= 10000 || (block && wsh->x >= block_n)) {
  321. r = -1;
  322. }
  323. if (r > 0) {
  324. *((char *)data + r) = '\0';
  325. }
  326. if (r >= 0) {
  327. wsh->x = 0;
  328. }
  329. return r;
  330. }
  331. /** Log WSS error(s).
  332. *
  333. * Log the WSS error specified by the error code @a e and all the errors in
  334. * the queue. The error code @a e implies no error, and it is not logged.
  335. */
  336. void wss_log_errors(unsigned level, char const *s, unsigned long e)
  337. {
  338. if (e == 0)
  339. e = ERR_get_error();
  340. if (!tport_log->log_init)
  341. su_log_init(tport_log);
  342. if (s == NULL) s = "tls";
  343. for (; e != 0; e = ERR_get_error()) {
  344. if (level <= tport_log->log_level) {
  345. const char *error = ERR_lib_error_string(e);
  346. const char *func = ERR_func_error_string(e);
  347. const char *reason = ERR_reason_error_string(e);
  348. su_llog(tport_log, level, "%s: %08lx:%s:%s:%s\n",
  349. s, e, error, func, reason);
  350. }
  351. }
  352. }
  353. int wss_error(wsh_t *wsh, int ssl_err, char const *who)
  354. {
  355. switch (ssl_err) {
  356. case SSL_ERROR_ZERO_RETURN:
  357. return 0;
  358. case SSL_ERROR_SYSCALL:
  359. ERR_clear_error();
  360. if (SSL_get_shutdown(wsh->ssl) & SSL_RECEIVED_SHUTDOWN)
  361. return 0; /* EOS */
  362. if (errno == 0)
  363. return 0; /* EOS */
  364. errno = EIO;
  365. return -1;
  366. default:
  367. wss_log_errors(1, who, ssl_err);
  368. errno = EIO;
  369. return -1;
  370. }
  371. }
  372. /*
  373. * Blocking read until bytes have been received, failure, or too many retries.
  374. */
  375. static ssize_t ws_raw_read_blocking(wsh_t *wsh, char *data, size_t max_bytes, int max_retries)
  376. {
  377. ssize_t total_bytes_read = 0;
  378. while (total_bytes_read < max_bytes && max_retries-- > 0) {
  379. ssize_t bytes_read = ws_raw_read(wsh, data + total_bytes_read, max_bytes - total_bytes_read, WS_BLOCK);
  380. if (bytes_read < 0) {
  381. break;
  382. }
  383. total_bytes_read += bytes_read;
  384. }
  385. return total_bytes_read;
  386. }
  387. ssize_t ws_raw_write(wsh_t *wsh, void *data, size_t bytes)
  388. {
  389. ssize_t r;
  390. int sanity = WS_WRITE_SANITY;
  391. int ssl_err = 0;
  392. size_t wrote = 0;
  393. if (wsh == NULL || data == NULL) {
  394. errno = EINVAL;
  395. return -1;
  396. }
  397. if (wsh->ssl) {
  398. do {
  399. void *buf = (void *)((unsigned char *)data + wrote);
  400. int size = bytes - wrote;
  401. //ERR_clear_error();
  402. r = SSL_write(wsh->ssl, buf, size);
  403. if (r == 0) {
  404. ssl_err = SSL_get_error(wsh->ssl, r);
  405. if (SSL_IO_ERROR(ssl_err)) {
  406. wsh->ssl_io_error = 1;
  407. }
  408. ssl_err = -42;
  409. break;
  410. }
  411. if (r > 0) {
  412. wrote += r;
  413. }
  414. if (sanity < WS_WRITE_SANITY) {
  415. int ms = 1;
  416. if (wsh->block) {
  417. if (sanity < WS_WRITE_SANITY / 2) {
  418. ms = 25;
  419. } else if (sanity < WS_WRITE_SANITY * 3 / 4) {
  420. ms = 50;
  421. }
  422. }
  423. ms_sleep(ms);
  424. }
  425. if (r < 0) {
  426. ssl_err = SSL_get_error(wsh->ssl, r);
  427. if (!SSL_WANT_READ_WRITE(ssl_err)) {
  428. if (SSL_IO_ERROR(ssl_err)) {
  429. wsh->ssl_io_error = 1;
  430. }
  431. ssl_err = wss_error(wsh, ssl_err, "ws_raw_write: SSL_write");
  432. break;
  433. }
  434. ssl_err = 0;
  435. }
  436. } while (--sanity > 0 && wrote < bytes);
  437. if (!sanity) ssl_err = -56;
  438. if (ssl_err) {
  439. r = ssl_err;
  440. }
  441. return r < 0 ? r : wrote;
  442. }
  443. do {
  444. r = send(wsh->sock, (void *)((unsigned char *)data + wrote), bytes - wrote, 0);
  445. if (r > 0) {
  446. wrote += r;
  447. }
  448. if (sanity < WS_WRITE_SANITY) {
  449. int ms = 1;
  450. if (wsh->block) {
  451. if (sanity < WS_WRITE_SANITY / 2) {
  452. ms = 25;
  453. } else if (sanity < WS_WRITE_SANITY * 3 / 4) {
  454. ms = 50;
  455. }
  456. }
  457. ms_sleep(ms);
  458. }
  459. if (r == -1) {
  460. if (!xp_is_blocking(xp_errno())) {
  461. break;
  462. }
  463. }
  464. } while (--sanity > 0 && wrote < bytes);
  465. //if (r<0) {
  466. //printf("wRITE FAIL: %s\n", strerror(errno));
  467. //}
  468. return r < 0 ? r : wrote;
  469. }
  470. #ifdef _MSC_VER
  471. static int setup_socket(ws_socket_t sock)
  472. {
  473. unsigned long v = 1;
  474. if (ioctlsocket(sock, FIONBIO, &v) == SOCKET_ERROR) {
  475. return -1;
  476. }
  477. return 0;
  478. }
  479. #else
  480. static int setup_socket(ws_socket_t sock)
  481. {
  482. int flags = fcntl(sock, F_GETFL, 0);
  483. return fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  484. }
  485. #endif
  486. int establish_logical_layer(wsh_t *wsh)
  487. {
  488. if (!wsh->sanity) {
  489. return -1;
  490. }
  491. if (wsh->logical_established) {
  492. return 0;
  493. }
  494. if (wsh->secure && !wsh->secure_established) {
  495. int code;
  496. if (!wsh->ssl) {
  497. wsh->ssl = SSL_new(wsh->ssl_ctx);
  498. assert(wsh->ssl);
  499. SSL_set_fd(wsh->ssl, wsh->sock);
  500. }
  501. do {
  502. code = SSL_accept(wsh->ssl);
  503. if (code == 1) {
  504. wsh->secure_established = 1;
  505. break;
  506. }
  507. if (code == 0) {
  508. return -1;
  509. }
  510. if (code < 0) {
  511. int ssl_err = SSL_get_error(wsh->ssl, code);
  512. if (!SSL_WANT_READ_WRITE(ssl_err)) {
  513. wss_error(wsh, ssl_err, "establish_logical_layer: SSL_accept");
  514. return -1;
  515. }
  516. }
  517. if (wsh->block) {
  518. ms_sleep(10);
  519. } else {
  520. ms_sleep(1);
  521. }
  522. wsh->sanity--;
  523. if (!wsh->block) {
  524. return -2;
  525. }
  526. } while (wsh->sanity > 0);
  527. if (!wsh->sanity) {
  528. return -1;
  529. }
  530. }
  531. while (!wsh->down && !wsh->handshake) {
  532. int r = ws_handshake(wsh);
  533. if (r < 0) {
  534. wsh->down = 1;
  535. return -1;
  536. }
  537. if (!wsh->handshake && !wsh->block) {
  538. return -2;
  539. }
  540. }
  541. wsh->logical_established = 1;
  542. return 0;
  543. }
  544. void ws_set_global_payload_size_max(ssize_t bytes)
  545. {
  546. ws_global_payload_size_max = bytes;
  547. }
  548. int ws_init(wsh_t *wsh, ws_socket_t sock, SSL_CTX *ssl_ctx, int close_sock, int block, int stay_open)
  549. {
  550. memset(wsh, 0, sizeof(*wsh));
  551. wsh->payload_size_max = ws_global_payload_size_max;
  552. wsh->sock = sock;
  553. wsh->block = block;
  554. wsh->sanity = WS_INIT_SANITY;
  555. wsh->ssl_ctx = ssl_ctx;
  556. wsh->stay_open = stay_open;
  557. if (!ssl_ctx) {
  558. ssl_ctx = ws_globals.ssl_ctx;
  559. }
  560. if (close_sock) {
  561. wsh->close_sock = 1;
  562. }
  563. wsh->buflen = 1024 * 64;
  564. wsh->bbuflen = wsh->buflen;
  565. wsh->buffer = malloc(wsh->buflen);
  566. wsh->bbuffer = malloc(wsh->bbuflen);
  567. //printf("init %p %ld\n", (void *) wsh->bbuffer, wsh->bbuflen);
  568. //memset(wsh->buffer, 0, wsh->buflen);
  569. //memset(wsh->bbuffer, 0, wsh->bbuflen);
  570. wsh->secure = ssl_ctx ? 1 : 0;
  571. setup_socket(sock);
  572. if (establish_logical_layer(wsh) == -1) {
  573. return -1;
  574. }
  575. if (wsh->down) {
  576. return -1;
  577. }
  578. return 0;
  579. }
  580. void ws_destroy(wsh_t *wsh)
  581. {
  582. if (!wsh) {
  583. return;
  584. }
  585. if (!wsh->down) {
  586. ws_close(wsh, WS_NONE);
  587. }
  588. if (wsh->down > 1) {
  589. return;
  590. }
  591. wsh->down = 2;
  592. if (wsh->write_buffer) {
  593. free(wsh->write_buffer);
  594. wsh->write_buffer = NULL;
  595. wsh->write_buffer_len = 0;
  596. }
  597. if (wsh->buffer) free(wsh->buffer);
  598. if (wsh->bbuffer) free(wsh->bbuffer);
  599. wsh->buffer = wsh->bbuffer = NULL;
  600. }
  601. ssize_t ws_close(wsh_t *wsh, int16_t reason)
  602. {
  603. if (wsh->down) {
  604. return -1;
  605. }
  606. wsh->down = 1;
  607. if (wsh->uri) {
  608. free(wsh->uri);
  609. wsh->uri = NULL;
  610. }
  611. if (reason && wsh->sock != ws_sock_invalid) {
  612. uint16_t *u16;
  613. uint8_t fr[4] = {WSOC_CLOSE | 0x80, 2, 0};
  614. u16 = (uint16_t *) &fr[2];
  615. *u16 = htons((int16_t)reason);
  616. ws_raw_write(wsh, fr, 4);
  617. }
  618. if (wsh->ssl) {
  619. int code = 0, rcode = 0;
  620. int ssl_error = 0;
  621. int n = 0, block_n = WS_SOFT_BLOCK / 10;
  622. /* SSL layer was never established or underlying IO error occured */
  623. if (!wsh->secure_established || wsh->ssl_io_error) {
  624. goto ssl_finish_it;
  625. }
  626. /* connection has been already closed */
  627. if (SSL_get_shutdown(wsh->ssl) & SSL_SENT_SHUTDOWN) {
  628. goto ssl_finish_it;
  629. }
  630. /* peer closes the connection */
  631. if (SSL_get_shutdown(wsh->ssl) & SSL_RECEIVED_SHUTDOWN) {
  632. SSL_shutdown(wsh->ssl);
  633. goto ssl_finish_it;
  634. }
  635. /* us closes the connection. We do bidirection shutdown handshake */
  636. for(;;) {
  637. code = SSL_shutdown(wsh->ssl);
  638. ssl_error = SSL_get_error(wsh->ssl, code);
  639. if (code <= 0 && ssl_error == SSL_ERROR_WANT_READ) {
  640. /* need to make sure there are no more data to read */
  641. for(;;) {
  642. if ((rcode = SSL_read(wsh->ssl, wsh->buffer, 9)) <= 0) {
  643. ssl_error = SSL_get_error(wsh->ssl, rcode);
  644. if (ssl_error == SSL_ERROR_ZERO_RETURN) {
  645. break;
  646. } else if (SSL_IO_ERROR(ssl_error)) {
  647. goto ssl_finish_it;
  648. } else if (ssl_error == SSL_ERROR_WANT_READ) {
  649. if (++n == block_n) {
  650. goto ssl_finish_it;
  651. }
  652. ms_sleep(10);
  653. } else {
  654. goto ssl_finish_it;
  655. }
  656. }
  657. }
  658. } else if (code == 0 || (code < 0 && ssl_error == SSL_ERROR_WANT_WRITE)) {
  659. if (++n == block_n) {
  660. goto ssl_finish_it;
  661. }
  662. ms_sleep(10);
  663. } else { /* code != 0 */
  664. goto ssl_finish_it;
  665. }
  666. }
  667. ssl_finish_it:
  668. SSL_free(wsh->ssl);
  669. wsh->ssl = NULL;
  670. }
  671. if (wsh->close_sock && wsh->sock != ws_sock_invalid) {
  672. #ifndef WIN32
  673. close(wsh->sock);
  674. #else
  675. closesocket(wsh->sock);
  676. #endif
  677. }
  678. wsh->sock = ws_sock_invalid;
  679. return reason * -1;
  680. }
  681. uint64_t hton64(uint64_t val)
  682. {
  683. if (__BYTE_ORDER == __BIG_ENDIAN) return (val);
  684. else return __bswap_64(val);
  685. }
  686. uint64_t ntoh64(uint64_t val)
  687. {
  688. if (__BYTE_ORDER == __BIG_ENDIAN) return (val);
  689. else return __bswap_64(val);
  690. }
  691. ssize_t ws_read_frame(wsh_t *wsh, ws_opcode_t *oc, uint8_t **data)
  692. {
  693. ssize_t need = 2;
  694. char *maskp;
  695. int ll = 0;
  696. int frag = 0;
  697. int blen;
  698. wsh->body = wsh->bbuffer;
  699. wsh->packetlen = 0;
  700. again:
  701. need = 2;
  702. maskp = NULL;
  703. *data = NULL;
  704. ll = establish_logical_layer(wsh);
  705. if (ll < 0) {
  706. return ll;
  707. }
  708. if (wsh->down) {
  709. return -1;
  710. }
  711. if (!wsh->handshake) {
  712. return ws_close(wsh, WS_NONE);
  713. }
  714. if ((wsh->datalen = ws_raw_read(wsh, wsh->buffer, 9, wsh->block)) < 0) {
  715. if (wsh->datalen == -2) {
  716. return -2;
  717. }
  718. return ws_close(wsh, WS_NONE);
  719. }
  720. if (wsh->datalen < need) {
  721. ssize_t bytes = ws_raw_read(wsh, wsh->buffer + wsh->datalen, 9 - wsh->datalen, WS_BLOCK);
  722. if (bytes < 0 || (wsh->datalen += bytes) < need) {
  723. /* too small - protocol err */
  724. return ws_close(wsh, WS_NONE);
  725. }
  726. }
  727. *oc = *wsh->buffer & 0xf;
  728. switch(*oc) {
  729. case WSOC_CLOSE:
  730. {
  731. wsh->plen = wsh->buffer[1] & 0x7f;
  732. *data = (uint8_t *) &wsh->buffer[2];
  733. return ws_close(wsh, 1000);
  734. }
  735. break;
  736. case WSOC_CONTINUATION:
  737. case WSOC_TEXT:
  738. case WSOC_BINARY:
  739. case WSOC_PING:
  740. case WSOC_PONG:
  741. {
  742. int fin = (wsh->buffer[0] >> 7) & 1;
  743. int mask = (wsh->buffer[1] >> 7) & 1;
  744. if (!fin && *oc != WSOC_CONTINUATION) {
  745. frag = 1;
  746. } else if (fin && *oc == WSOC_CONTINUATION) {
  747. frag = 0;
  748. }
  749. if (mask) {
  750. need += 4;
  751. if (need > wsh->datalen) {
  752. ssize_t bytes = ws_raw_read_blocking(wsh, wsh->buffer + wsh->datalen, need - wsh->datalen, 10);
  753. if (bytes < 0 || (wsh->datalen += bytes) < need) {
  754. /* too small - protocol err */
  755. *oc = WSOC_CLOSE;
  756. return ws_close(wsh, WS_NONE);
  757. }
  758. }
  759. }
  760. wsh->plen = wsh->buffer[1] & 0x7f;
  761. wsh->payload = &wsh->buffer[2];
  762. if (wsh->plen == 127) {
  763. uint64_t *u64;
  764. need += 8;
  765. if (need > wsh->datalen) {
  766. ssize_t bytes = ws_raw_read_blocking(wsh, wsh->buffer + wsh->datalen, need - wsh->datalen, 10);
  767. if (bytes < 0 || (wsh->datalen += bytes) < need) {
  768. /* too small - protocol err */
  769. *oc = WSOC_CLOSE;
  770. return ws_close(wsh, WS_NONE);
  771. }
  772. }
  773. u64 = (uint64_t *) wsh->payload;
  774. wsh->payload += 8;
  775. wsh->plen = ntoh64(*u64);
  776. } else if (wsh->plen == 126) {
  777. uint16_t *u16;
  778. need += 2;
  779. if (need > wsh->datalen) {
  780. ssize_t bytes = ws_raw_read_blocking(wsh, wsh->buffer + wsh->datalen, need - wsh->datalen, 10);
  781. if (bytes < 0 || (wsh->datalen += bytes) < need) {
  782. /* too small - protocol err */
  783. *oc = WSOC_CLOSE;
  784. return ws_close(wsh, WS_NONE);
  785. }
  786. }
  787. u16 = (uint16_t *) wsh->payload;
  788. wsh->payload += 2;
  789. wsh->plen = ntohs(*u16);
  790. }
  791. if (mask) {
  792. maskp = (char *)wsh->payload;
  793. wsh->payload += 4;
  794. }
  795. need = (wsh->plen - (wsh->datalen - need));
  796. if (need < 0) {
  797. /* invalid read - protocol err .. */
  798. *oc = WSOC_CLOSE;
  799. return ws_close(wsh, WS_NONE);
  800. }
  801. blen = wsh->body - wsh->bbuffer;
  802. if (need + blen > (ssize_t)wsh->bbuflen) {
  803. void *tmp;
  804. wsh->bbuflen = need + blen + wsh->rplen;
  805. if (wsh->payload_size_max && wsh->bbuflen > wsh->payload_size_max) {
  806. /* size limit */
  807. *oc = WSOC_CLOSE;
  808. return ws_close(wsh, WS_NONE);
  809. }
  810. if ((tmp = realloc(wsh->bbuffer, wsh->bbuflen))) {
  811. wsh->bbuffer = tmp;
  812. } else {
  813. abort();
  814. }
  815. wsh->body = wsh->bbuffer + blen;
  816. }
  817. wsh->rplen = wsh->plen - need;
  818. if (wsh->rplen) {
  819. memcpy(wsh->body, wsh->payload, wsh->rplen);
  820. }
  821. while(need) {
  822. ssize_t r = ws_raw_read(wsh, wsh->body + wsh->rplen, need, WS_BLOCK);
  823. if (r < 1) {
  824. /* invalid read - protocol err .. */
  825. *oc = WSOC_CLOSE;
  826. return ws_close(wsh, WS_NONE);
  827. }
  828. wsh->datalen += r;
  829. wsh->rplen += r;
  830. need -= r;
  831. }
  832. if (mask && maskp) {
  833. ssize_t i;
  834. for (i = 0; i < wsh->datalen; i++) {
  835. wsh->body[i] ^= maskp[i % 4];
  836. }
  837. }
  838. if (*oc == WSOC_PING) {
  839. ws_write_frame(wsh, WSOC_PONG, wsh->body, wsh->rplen);
  840. goto again;
  841. }
  842. *(wsh->body+wsh->rplen) = '\0';
  843. wsh->packetlen += wsh->rplen;
  844. wsh->body += wsh->rplen;
  845. if (frag) {
  846. goto again;
  847. }
  848. *data = (uint8_t *)wsh->bbuffer;
  849. //printf("READ[%ld][%d]-----------------------------:\n[%s]\n-------------------------------\n", wsh->packetlen, *oc, (char *)*data);
  850. return wsh->packetlen;
  851. }
  852. break;
  853. default:
  854. {
  855. /* invalid op code - protocol err .. */
  856. *oc = WSOC_CLOSE;
  857. return ws_close(wsh, WS_PROTO_ERR);
  858. }
  859. break;
  860. }
  861. }
  862. ssize_t ws_write_frame(wsh_t *wsh, ws_opcode_t oc, void *data, size_t bytes)
  863. {
  864. uint8_t hdr[14] = { 0 };
  865. size_t hlen = 2;
  866. uint8_t *bp;
  867. ssize_t raw_ret = 0;
  868. if (wsh->down) {
  869. errno = EIO;
  870. return -1;
  871. }
  872. //printf("WRITE[%ld]-----------------------------:\n[%s]\n-----------------------------------\n", bytes, (char *) data);
  873. hdr[0] = (uint8_t)(oc | 0x80);
  874. if (bytes < 126) {
  875. hdr[1] = (uint8_t)bytes;
  876. } else if (bytes < 0x10000) {
  877. uint16_t *u16;
  878. hdr[1] = 126;
  879. hlen += 2;
  880. u16 = (uint16_t *) &hdr[2];
  881. *u16 = htons((uint16_t) bytes);
  882. } else {
  883. uint64_t *u64;
  884. hdr[1] = 127;
  885. hlen += 8;
  886. u64 = (uint64_t *) &hdr[2];
  887. *u64 = hton64(bytes);
  888. }
  889. if (wsh->write_buffer_len < (hlen + bytes + 1)) {
  890. void *tmp;
  891. wsh->write_buffer_len = hlen + bytes + 1;
  892. if ((tmp = realloc(wsh->write_buffer, wsh->write_buffer_len))) {
  893. wsh->write_buffer = tmp;
  894. } else {
  895. abort();
  896. }
  897. }
  898. bp = (uint8_t *) wsh->write_buffer;
  899. memcpy(bp, (void *) &hdr[0], hlen);
  900. memcpy(bp + hlen, data, bytes);
  901. raw_ret = ws_raw_write(wsh, bp, (hlen + bytes));
  902. if (raw_ret <= 0 || raw_ret != (ssize_t) (hlen + bytes)) {
  903. return raw_ret;
  904. }
  905. return bytes;
  906. }
  907. #ifdef _MSC_VER
  908. int xp_errno(void)
  909. {
  910. return WSAGetLastError();
  911. }
  912. int xp_is_blocking(int errcode)
  913. {
  914. return errcode == WSAEWOULDBLOCK || errcode == WSAEINPROGRESS;
  915. }
  916. #else
  917. int xp_errno(void)
  918. {
  919. return errno;
  920. }
  921. int xp_is_blocking(int errcode)
  922. {
  923. return errcode == EAGAIN || errcode == EWOULDBLOCK || errcode == EINPROGRESS || errcode == EINTR || errcode == ETIMEDOUT;
  924. }
  925. #endif