/modules/http/request.c

https://bitbucket.org/cesbo/astra · C · 1408 lines · 1046 code · 252 blank · 110 comment · 202 complexity · b5cf72be8c2047e981052f05b00ec9a4 MD5 · raw file

  1. /*
  2. * Astra Module: HTTP Request
  3. * http://cesbo.com/astra
  4. *
  5. * Copyright (C) 2012-2015, Andrey Dyldin <and@cesbo.com>
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /*
  21. * Module Name:
  22. * http_request
  23. *
  24. * Module Options:
  25. * host - string, server hostname or IP address
  26. * port - number, server port (default: 80)
  27. * path - string, request path
  28. * method - string, method (default: "GET")
  29. * version - string, HTTP version (default: "HTTP/1.1")
  30. * headers - table, list of the request headers
  31. * content - string, request content
  32. * stream - boolean, true to read MPEG-TS stream
  33. * sync - boolean or number, enable stream synchronization
  34. * sctp - boolean, use sctp instead of tcp
  35. * timeout - number, request timeout
  36. * callback - function,
  37. * upstream - object, stream instance returned by module_instance:stream()
  38. */
  39. #include "http.h"
  40. #define MSG(_msg) \
  41. "[http_request %s:%d%s] " _msg, mod->config.host \
  42. , mod->config.port \
  43. , mod->config.path
  44. struct module_data_t
  45. {
  46. MODULE_STREAM_DATA();
  47. struct
  48. {
  49. const char *host;
  50. int port;
  51. const char *path;
  52. bool sync;
  53. } config;
  54. int timeout_ms;
  55. bool is_stream;
  56. int idx_self;
  57. asc_socket_t *sock;
  58. asc_timer_t *timeout;
  59. bool is_socket_busy;
  60. // request
  61. struct
  62. {
  63. int status; // 1 - connected, 2 - request done
  64. const char *buffer;
  65. size_t skip;
  66. size_t size;
  67. int idx_body;
  68. } request;
  69. bool is_head;
  70. bool is_connection_close;
  71. bool is_connection_keep_alive;
  72. // response
  73. char buffer[HTTP_BUFFER_SIZE];
  74. size_t buffer_skip;
  75. size_t chunk_left;
  76. int idx_response;
  77. int status_code;
  78. int status; // 1 - empty line is found, 2 - request ready, 3 - release
  79. int idx_content;
  80. bool is_chunked;
  81. bool is_content_length;
  82. string_buffer_t *content;
  83. bool is_active;
  84. // receiver
  85. struct
  86. {
  87. void *arg;
  88. union
  89. {
  90. void (*fn)(void *, void *, size_t);
  91. void *ptr;
  92. } callback;
  93. } receiver;
  94. // stream
  95. bool is_thread_started;
  96. asc_thread_t *thread;
  97. asc_thread_buffer_t *thread_output;
  98. struct
  99. {
  100. uint8_t *buffer;
  101. size_t buffer_size;
  102. size_t buffer_count;
  103. size_t buffer_read;
  104. size_t buffer_write;
  105. size_t buffer_fill;
  106. } sync;
  107. uint64_t pcr;
  108. };
  109. static const char __path[] = "path";
  110. static const char __method[] = "method";
  111. static const char __version[] = "version";
  112. static const char __headers[] = "headers";
  113. static const char __content[] = "content";
  114. static const char __callback[] = "callback";
  115. static const char __stream[] = "stream";
  116. static const char __code[] = "code";
  117. static const char __message[] = "message";
  118. static const char __default_method[] = "GET";
  119. static const char __default_path[] = "/";
  120. static const char __default_version[] = "HTTP/1.1";
  121. static const char __connection[] = "Connection: ";
  122. static const char __close[] = "close";
  123. static const char __keep_alive[] = "keep-alive";
  124. static void on_close(void *);
  125. static void callback(module_data_t *mod)
  126. {
  127. const int response = lua_gettop(lua);
  128. lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_self);
  129. lua_getfield(lua, -1, "__options");
  130. lua_getfield(lua, -1, "callback");
  131. lua_pushvalue(lua, -3);
  132. lua_pushvalue(lua, response);
  133. lua_call(lua, 2, 0);
  134. lua_pop(lua, 3); // self + options + response
  135. }
  136. static void call_error(module_data_t *mod, const char *msg)
  137. {
  138. lua_newtable(lua);
  139. lua_pushnumber(lua, 0);
  140. lua_setfield(lua, -2, __code);
  141. lua_pushstring(lua, msg);
  142. lua_setfield(lua, -2, __message);
  143. callback(mod);
  144. }
  145. void timeout_callback(void *arg)
  146. {
  147. module_data_t *mod = (module_data_t *)arg;
  148. asc_timer_destroy(mod->timeout);
  149. mod->timeout = NULL;
  150. if(mod->request.status == 0)
  151. {
  152. mod->status = -1;
  153. mod->request.status = -1;
  154. call_error(mod, "connection timeout");
  155. }
  156. else
  157. {
  158. mod->status = -1;
  159. mod->request.status = -1;
  160. call_error(mod, "response timeout");
  161. }
  162. on_close(mod);
  163. }
  164. static void on_thread_close(void *arg);
  165. static void on_close(void *arg)
  166. {
  167. module_data_t *mod = (module_data_t *)arg;
  168. if(mod->thread)
  169. on_thread_close(mod);
  170. if(!mod->sock)
  171. return;
  172. if(mod->receiver.callback.ptr)
  173. {
  174. mod->receiver.callback.fn(mod->receiver.arg, NULL, 0);
  175. mod->receiver.arg = NULL;
  176. mod->receiver.callback.ptr = NULL;
  177. }
  178. asc_socket_close(mod->sock);
  179. mod->sock = NULL;
  180. if(mod->timeout)
  181. {
  182. asc_timer_destroy(mod->timeout);
  183. mod->timeout = NULL;
  184. }
  185. if(mod->request.buffer)
  186. {
  187. if(mod->request.status == 1)
  188. free((void *)mod->request.buffer);
  189. mod->request.buffer = NULL;
  190. }
  191. if(mod->request.idx_body)
  192. {
  193. luaL_unref(lua, LUA_REGISTRYINDEX, mod->request.idx_body);
  194. mod->request.idx_body = 0;
  195. }
  196. if(mod->request.status == 0)
  197. {
  198. mod->request.status = -1;
  199. call_error(mod, "connection failed");
  200. }
  201. else if(mod->status == 0)
  202. {
  203. mod->request.status = -1;
  204. call_error(mod, "failed to parse response");
  205. }
  206. if(mod->status == 2)
  207. {
  208. mod->status = 3;
  209. lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_response);
  210. callback(mod);
  211. }
  212. if(mod->__stream.self)
  213. {
  214. module_stream_destroy(mod);
  215. if(mod->status == 3)
  216. {
  217. /* stream on_close */
  218. mod->status = -1;
  219. mod->request.status = -1;
  220. lua_pushnil(lua);
  221. callback(mod);
  222. }
  223. }
  224. if(mod->sync.buffer)
  225. {
  226. free(mod->sync.buffer);
  227. mod->sync.buffer = NULL;
  228. }
  229. if(mod->idx_response)
  230. {
  231. luaL_unref(lua, LUA_REGISTRYINDEX, mod->idx_response);
  232. mod->idx_response = 0;
  233. }
  234. if(mod->idx_content)
  235. {
  236. luaL_unref(lua, LUA_REGISTRYINDEX, mod->idx_content);
  237. mod->idx_content = 0;
  238. }
  239. if(mod->idx_self)
  240. {
  241. luaL_unref(lua, LUA_REGISTRYINDEX, mod->idx_self);
  242. mod->idx_self = 0;
  243. }
  244. if(mod->content)
  245. {
  246. string_buffer_free(mod->content);
  247. mod->content = NULL;
  248. }
  249. }
  250. /*
  251. * oooooooo8 ooooooooooo oooooooooo ooooooooooo o oooo oooo
  252. * 888 88 888 88 888 888 888 88 888 8888o 888
  253. * 888oooooo 888 888oooo88 888ooo8 8 88 88 888o8 88
  254. * 888 888 888 88o 888 oo 8oooo88 88 888 88
  255. * o88oooo888 o888o o888o 88o8 o888ooo8888 o88o o888o o88o 8 o88o
  256. *
  257. */
  258. static bool seek_pcr( module_data_t *mod
  259. , size_t *block_size, size_t *next_block
  260. , uint64_t *pcr)
  261. {
  262. size_t count;
  263. while(1)
  264. {
  265. if(mod->sync.buffer_count < 2 * TS_PACKET_SIZE)
  266. return false;
  267. count = mod->sync.buffer_read + TS_PACKET_SIZE;
  268. if(count >= mod->sync.buffer_size)
  269. count -= mod->sync.buffer_size;
  270. if( mod->sync.buffer[mod->sync.buffer_read] == 0x47
  271. && mod->sync.buffer[count] == 0x47)
  272. {
  273. break;
  274. }
  275. ++mod->sync.buffer_read;
  276. if(mod->sync.buffer_read >= mod->sync.buffer_size)
  277. mod->sync.buffer_read = 0;
  278. --mod->sync.buffer_count;
  279. }
  280. uint8_t *ptr, ts[TS_PACKET_SIZE];
  281. size_t next_skip, skip = mod->sync.buffer_read + TS_PACKET_SIZE;
  282. if(skip >= mod->sync.buffer_size)
  283. skip -= mod->sync.buffer_size;
  284. for( count = TS_PACKET_SIZE
  285. ; count < mod->sync.buffer_count
  286. ; count += TS_PACKET_SIZE)
  287. {
  288. ptr = &mod->sync.buffer[skip];
  289. next_skip = skip + TS_PACKET_SIZE;
  290. if(next_skip > mod->sync.buffer_size)
  291. {
  292. const size_t packet_head = mod->sync.buffer_size - skip;
  293. memcpy(ts, ptr, packet_head);
  294. next_skip -= mod->sync.buffer_size;
  295. memcpy(&ts[packet_head], mod->sync.buffer, next_skip);
  296. ptr = ts;
  297. }
  298. if(TS_IS_PCR(ptr))
  299. {
  300. *block_size = count;
  301. *next_block = skip;
  302. *pcr = TS_GET_PCR(ptr);
  303. return true;
  304. }
  305. skip = (next_skip == mod->sync.buffer_size) ? 0 : next_skip;
  306. }
  307. return false;
  308. }
  309. static void on_thread_close(void *arg)
  310. {
  311. module_data_t *mod = (module_data_t *)arg;
  312. mod->is_thread_started = false;
  313. if(mod->thread)
  314. {
  315. asc_thread_destroy(mod->thread);
  316. mod->thread = NULL;
  317. }
  318. if(mod->thread_output)
  319. {
  320. asc_thread_buffer_destroy(mod->thread_output);
  321. mod->thread_output = NULL;
  322. }
  323. on_close(mod);
  324. }
  325. static void on_thread_read(void *arg)
  326. {
  327. module_data_t *mod = (module_data_t *)arg;
  328. uint8_t ts[TS_PACKET_SIZE];
  329. const ssize_t r = asc_thread_buffer_read(mod->thread_output, ts, sizeof(ts));
  330. if(r == sizeof(ts))
  331. module_stream_send(mod, ts);
  332. }
  333. static void thread_loop(void *arg)
  334. {
  335. module_data_t *mod = (module_data_t *)arg;
  336. uint8_t *ptr, ts[TS_PACKET_SIZE];
  337. mod->is_thread_started = true;
  338. while(mod->is_thread_started)
  339. {
  340. // block sync
  341. uint64_t pcr
  342. , system_time, system_time_check
  343. , block_time, block_time_total = 0;
  344. size_t block_size = 0, next_block;
  345. bool reset = true;
  346. asc_log_info(MSG("buffering..."));
  347. // flush
  348. mod->sync.buffer_count = 0;
  349. mod->sync.buffer_write = 0;
  350. mod->sync.buffer_read = 0;
  351. // check timeout
  352. system_time_check = asc_utime();
  353. while( mod->is_thread_started
  354. && mod->sync.buffer_write < mod->sync.buffer_size)
  355. {
  356. system_time = asc_utime();
  357. const ssize_t size = asc_socket_recv( mod->sock
  358. , &mod->sync.buffer[mod->sync.buffer_write]
  359. , mod->sync.buffer_size - mod->sync.buffer_write);
  360. if(size > 0)
  361. {
  362. system_time_check = system_time;
  363. mod->sync.buffer_write += size;
  364. }
  365. else
  366. {
  367. if(system_time - system_time_check >= (uint32_t)mod->timeout_ms * 1000)
  368. {
  369. asc_log_error(MSG("receiving timeout"));
  370. return;
  371. }
  372. asc_usleep(1000);
  373. }
  374. }
  375. mod->sync.buffer_count = mod->sync.buffer_write;
  376. if(mod->sync.buffer_write == mod->sync.buffer_size)
  377. mod->sync.buffer_write = 0;
  378. if(!seek_pcr(mod, &block_size, &next_block, &mod->pcr))
  379. {
  380. asc_log_error(MSG("first PCR is not found"));
  381. return;
  382. }
  383. mod->sync.buffer_count -= block_size;
  384. mod->sync.buffer_read = next_block;
  385. reset = true;
  386. while(mod->is_thread_started)
  387. {
  388. if(reset)
  389. {
  390. reset = false;
  391. block_time_total = asc_utime();
  392. }
  393. if( mod->is_thread_started
  394. && mod->sync.buffer_count < mod->sync.buffer_size)
  395. {
  396. const size_t tail = (mod->sync.buffer_read > mod->sync.buffer_write)
  397. ? (mod->sync.buffer_read - mod->sync.buffer_write)
  398. : (mod->sync.buffer_size - mod->sync.buffer_write);
  399. const ssize_t l = asc_socket_recv( mod->sock
  400. , &mod->sync.buffer[mod->sync.buffer_write]
  401. , tail);
  402. if(l > 0)
  403. {
  404. mod->sync.buffer_write += l;
  405. if(mod->sync.buffer_write >= mod->sync.buffer_size)
  406. mod->sync.buffer_write = 0;
  407. mod->sync.buffer_count += l;
  408. }
  409. }
  410. // get PCR
  411. if(!seek_pcr(mod, &block_size, &next_block, &pcr))
  412. {
  413. asc_log_error(MSG("next PCR is not found"));
  414. break;
  415. }
  416. block_time = mpegts_pcr_block_us(&mod->pcr, &pcr);
  417. mod->pcr = pcr;
  418. if(block_time == 0 || block_time > 500000)
  419. {
  420. asc_log_debug( MSG("block time out of range: %"PRIu64"ms block_size:%lu")
  421. , (uint64_t)(block_time / 1000), block_size);
  422. mod->sync.buffer_count -= block_size;
  423. mod->sync.buffer_read = next_block;
  424. reset = true;
  425. continue;
  426. }
  427. system_time = asc_utime();
  428. if(block_time_total > system_time + 100)
  429. asc_usleep(block_time_total - system_time);
  430. const uint32_t ts_count = block_size / TS_PACKET_SIZE;
  431. const uint32_t ts_sync = block_time / ts_count;
  432. const uint32_t block_time_tail = block_time % ts_count;
  433. system_time_check = asc_utime();
  434. while(mod->is_thread_started && mod->sync.buffer_read != next_block)
  435. {
  436. // sending
  437. ptr = &mod->sync.buffer[mod->sync.buffer_read];
  438. size_t next_packet = mod->sync.buffer_read + TS_PACKET_SIZE;
  439. if(next_packet < mod->sync.buffer_size)
  440. {
  441. mod->sync.buffer_read = next_packet;
  442. }
  443. else if(next_packet > mod->sync.buffer_size)
  444. {
  445. const size_t packet_head = mod->sync.buffer_size - mod->sync.buffer_read;
  446. memcpy(ts, ptr, packet_head);
  447. mod->sync.buffer_read = next_packet - mod->sync.buffer_size;
  448. memcpy(&ts[packet_head], mod->sync.buffer, mod->sync.buffer_read);
  449. ptr = ts;
  450. }
  451. else /* next_packet == mod->sync.buffer_size */
  452. {
  453. mod->sync.buffer_read = 0;
  454. }
  455. const ssize_t write_size = asc_thread_buffer_write( mod->thread_output
  456. , ptr
  457. , TS_PACKET_SIZE);
  458. if(write_size != TS_PACKET_SIZE)
  459. {
  460. // overflow
  461. }
  462. system_time = asc_utime();
  463. block_time_total += ts_sync;
  464. if( (system_time < system_time_check) /* <-0s */
  465. ||(system_time > system_time_check + 1000000)) /* >+1s */
  466. {
  467. asc_log_warning(MSG("system time changed"));
  468. mod->sync.buffer_read = next_block;
  469. reset = true;
  470. break;
  471. }
  472. system_time_check = system_time;
  473. if(block_time_total > system_time + 100)
  474. asc_usleep(block_time_total - system_time);
  475. }
  476. mod->sync.buffer_count -= block_size;
  477. if(reset)
  478. continue;
  479. system_time = asc_utime();
  480. if(system_time > block_time_total + 100000)
  481. {
  482. asc_log_warning( MSG("wrong syncing time. -%"PRIu64"ms")
  483. , (system_time - block_time_total) / 1000);
  484. reset = true;
  485. }
  486. block_time_total += block_time_tail;
  487. }
  488. }
  489. }
  490. static void check_is_active(void *arg)
  491. {
  492. module_data_t *mod = (module_data_t *)arg;
  493. if(mod->is_active)
  494. {
  495. mod->is_active = false;
  496. return;
  497. }
  498. asc_log_error(MSG("receiving timeout"));
  499. on_close(mod);
  500. }
  501. static void on_ts_read(void *arg)
  502. {
  503. module_data_t *mod = (module_data_t *)arg;
  504. ssize_t size = asc_socket_recv( mod->sock
  505. , &mod->sync.buffer[mod->sync.buffer_write]
  506. , mod->sync.buffer_size - mod->sync.buffer_write);
  507. if(size <= 0)
  508. {
  509. on_close(mod);
  510. return;
  511. }
  512. mod->is_active = true;
  513. mod->sync.buffer_write += size;
  514. mod->sync.buffer_read = 0;
  515. while(1)
  516. {
  517. while(mod->sync.buffer[mod->sync.buffer_read] != 0x47)
  518. {
  519. ++mod->sync.buffer_read;
  520. if(mod->sync.buffer_read >= mod->sync.buffer_write)
  521. {
  522. mod->sync.buffer_write = 0;
  523. return;
  524. }
  525. }
  526. const size_t next = mod->sync.buffer_read + TS_PACKET_SIZE;
  527. if(next > mod->sync.buffer_write)
  528. {
  529. const size_t tail = mod->sync.buffer_write - mod->sync.buffer_read;
  530. if(tail > 0)
  531. memmove(mod->sync.buffer, &mod->sync.buffer[mod->sync.buffer_read], tail);
  532. mod->sync.buffer_write = tail;
  533. return;
  534. }
  535. module_stream_send(mod, &mod->sync.buffer[mod->sync.buffer_read]);
  536. mod->sync.buffer_read += TS_PACKET_SIZE;
  537. }
  538. }
  539. /*
  540. * oooooooooo ooooooooooo o ooooooooo
  541. * 888 888 888 88 888 888 88o
  542. * 888oooo88 888ooo8 8 88 888 888
  543. * 888 88o 888 oo 8oooo88 888 888
  544. * o888o 88o8 o888ooo8888 o88o o888o o888ooo88
  545. *
  546. */
  547. static void on_read(void *arg)
  548. {
  549. module_data_t *mod = (module_data_t *)arg;
  550. if(mod->timeout)
  551. {
  552. asc_timer_destroy(mod->timeout);
  553. mod->timeout = NULL;
  554. }
  555. ssize_t size = asc_socket_recv( mod->sock
  556. , &mod->buffer[mod->buffer_skip]
  557. , HTTP_BUFFER_SIZE - mod->buffer_skip);
  558. if(size <= 0)
  559. {
  560. on_close(mod);
  561. return;
  562. }
  563. if(mod->receiver.callback.ptr)
  564. {
  565. mod->receiver.callback.fn(mod->receiver.arg, &mod->buffer[mod->buffer_skip], size);
  566. return;
  567. }
  568. if(mod->status == 3)
  569. {
  570. asc_log_warning(MSG("received data after response"));
  571. return;
  572. }
  573. size_t eoh = 0; // end of headers
  574. size_t skip = 0;
  575. mod->buffer_skip += size;
  576. if(mod->status == 0)
  577. {
  578. // check empty line
  579. while(skip < mod->buffer_skip)
  580. {
  581. if( skip + 1 < mod->buffer_skip
  582. && mod->buffer[skip + 0] == '\n' && mod->buffer[skip + 1] == '\n')
  583. {
  584. eoh = skip + 2;
  585. mod->status = 1;
  586. break;
  587. }
  588. else if( skip + 3 < mod->buffer_skip
  589. && mod->buffer[skip + 0] == '\r' && mod->buffer[skip + 1] == '\n'
  590. && mod->buffer[skip + 2] == '\r' && mod->buffer[skip + 3] == '\n')
  591. {
  592. eoh = skip + 4;
  593. mod->status = 1;
  594. break;
  595. }
  596. ++skip;
  597. }
  598. if(mod->status != 1)
  599. return;
  600. }
  601. if(mod->status == 1)
  602. {
  603. parse_match_t m[4];
  604. skip = 0;
  605. /*
  606. * oooooooooo ooooooooooo oooooooo8 oooooooooo
  607. * 888 888 888 88 888 888 888
  608. * 888oooo88 888ooo8 888oooooo 888oooo88
  609. * ooo 888 88o 888 oo 888 888
  610. * 888 o888o 88o8 o888ooo8888 o88oooo888 o888o
  611. *
  612. */
  613. if(!http_parse_response(mod->buffer, eoh, m))
  614. {
  615. call_error(mod, "failed to parse response line");
  616. on_close(mod);
  617. return;
  618. }
  619. lua_newtable(lua);
  620. const int response = lua_gettop(lua);
  621. lua_pushvalue(lua, -1);
  622. if(mod->idx_response)
  623. luaL_unref(lua, LUA_REGISTRYINDEX, mod->idx_response);
  624. mod->idx_response = luaL_ref(lua, LUA_REGISTRYINDEX);
  625. lua_pushlstring(lua, &mod->buffer[m[1].so], m[1].eo - m[1].so);
  626. lua_setfield(lua, response, __version);
  627. mod->status_code = atoi(&mod->buffer[m[2].so]);
  628. lua_pushnumber(lua, mod->status_code);
  629. lua_setfield(lua, response, __code);
  630. lua_pushlstring(lua, &mod->buffer[m[3].so], m[3].eo - m[3].so);
  631. lua_setfield(lua, response, __message);
  632. skip += m[0].eo;
  633. /*
  634. * ooooo ooooo ooooooooooo o ooooooooo ooooooooooo oooooooooo oooooooo8
  635. * 888 888 888 88 888 888 88o 888 88 888 888 888
  636. * 888ooo888 888ooo8 8 88 888 888 888ooo8 888oooo88 888oooooo
  637. * ooo 888 888 888 oo 8oooo88 888 888 888 oo 888 88o 888
  638. * 888 o888o o888o o888ooo8888 o88o o888o o888ooo88 o888ooo8888 o888o 88o8 o88oooo888
  639. *
  640. */
  641. lua_newtable(lua);
  642. lua_pushvalue(lua, -1);
  643. lua_setfield(lua, response, __headers);
  644. const int headers = lua_gettop(lua);
  645. while(skip < eoh)
  646. {
  647. if(!http_parse_header(&mod->buffer[skip], eoh - skip, m))
  648. {
  649. call_error(mod, "failed to parse response headers");
  650. on_close(mod);
  651. return;
  652. }
  653. if(m[1].eo == 0)
  654. { /* empty line */
  655. skip += m[0].eo;
  656. mod->status = 2;
  657. break;
  658. }
  659. lua_string_to_lower(&mod->buffer[skip], m[1].eo);
  660. lua_pushlstring(lua, &mod->buffer[skip + m[2].so], m[2].eo - m[2].so);
  661. lua_settable(lua, headers);
  662. skip += m[0].eo;
  663. }
  664. mod->chunk_left = 0;
  665. mod->is_content_length = false;
  666. if(mod->content)
  667. {
  668. free(mod->content);
  669. mod->content = NULL;
  670. }
  671. lua_getfield(lua, headers, "content-length");
  672. if(lua_isnumber(lua, -1))
  673. {
  674. mod->chunk_left = lua_tonumber(lua, -1);
  675. if(mod->chunk_left > 0)
  676. {
  677. mod->is_content_length = true;
  678. }
  679. }
  680. lua_pop(lua, 1); // content-length
  681. lua_getfield(lua, headers, "transfer-encoding");
  682. if(lua_isstring(lua, -1))
  683. {
  684. const char *encoding = lua_tostring(lua, -1);
  685. mod->is_chunked = (strcmp(encoding, "chunked") == 0);
  686. }
  687. lua_pop(lua, 1); // transfer-encoding
  688. if(mod->is_content_length || mod->is_chunked)
  689. mod->content = string_buffer_alloc();
  690. lua_pop(lua, 2); // headers + response
  691. if( (mod->is_head)
  692. || (mod->status_code >= 100 && mod->status_code < 200)
  693. || (mod->status_code == 204)
  694. || (mod->status_code == 304))
  695. {
  696. mod->status = 3;
  697. lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_response);
  698. callback(mod);
  699. if(mod->is_connection_close)
  700. on_close(mod);
  701. mod->buffer_skip = 0;
  702. return;
  703. }
  704. if(mod->is_stream && mod->status_code == 200)
  705. {
  706. mod->status = 3;
  707. lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_response);
  708. lua_pushboolean(lua, mod->is_stream);
  709. lua_setfield(lua, -2, __stream);
  710. callback(mod);
  711. mod->sync.buffer = (uint8_t *)malloc(mod->sync.buffer_size);
  712. if(!mod->config.sync)
  713. {
  714. mod->timeout = asc_timer_init(mod->timeout_ms, check_is_active, mod);
  715. asc_socket_set_on_read(mod->sock, on_ts_read);
  716. asc_socket_set_on_ready(mod->sock, NULL);
  717. }
  718. else
  719. {
  720. asc_socket_set_on_read(mod->sock, NULL);
  721. asc_socket_set_on_ready(mod->sock, NULL);
  722. asc_socket_set_on_close(mod->sock, NULL);
  723. mod->thread = asc_thread_init(mod);
  724. mod->thread_output = asc_thread_buffer_init(mod->sync.buffer_size);
  725. asc_thread_start( mod->thread
  726. , thread_loop
  727. , on_thread_read, mod->thread_output
  728. , on_thread_close);
  729. }
  730. mod->buffer_skip = 0;
  731. return;
  732. }
  733. if(!mod->content)
  734. {
  735. mod->status = 3;
  736. lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_response);
  737. callback(mod);
  738. if(mod->is_connection_close)
  739. on_close(mod);
  740. mod->buffer_skip = 0;
  741. return;
  742. }
  743. }
  744. /*
  745. * oooooooo8 ooooooo oooo oooo ooooooooooo ooooooooooo oooo oooo ooooooooooo
  746. * o888 88 o888 888o 8888o 88 88 888 88 888 88 8888o 88 88 888 88
  747. * 888 888 888 88 888o88 888 888ooo8 88 888o88 888
  748. * ooo 888o oo 888o o888 88 8888 888 888 oo 88 8888 888
  749. * 888 888oooo88 88ooo88 o88o 88 o888o o888ooo8888 o88o 88 o888o
  750. *
  751. */
  752. // Transfer-Encoding: chunked
  753. if(mod->is_chunked)
  754. {
  755. parse_match_t m[2];
  756. while(skip < mod->buffer_skip)
  757. {
  758. if(!mod->chunk_left)
  759. {
  760. if(!http_parse_chunk(&mod->buffer[skip], mod->buffer_skip - skip, m))
  761. {
  762. call_error(mod, "invalid chunk");
  763. on_close(mod);
  764. return;
  765. }
  766. mod->chunk_left = 0;
  767. for(size_t i = m[1].so; i < m[1].eo; ++i)
  768. {
  769. char c = mod->buffer[skip + i];
  770. if(c >= '0' && c <= '9')
  771. mod->chunk_left = (mod->chunk_left << 4) | (c - '0');
  772. else if(c >= 'a' && c <= 'f')
  773. mod->chunk_left = (mod->chunk_left << 4) | (c - 'a' + 0x0A);
  774. else if(c >= 'A' && c <= 'F')
  775. mod->chunk_left = (mod->chunk_left << 4) | (c - 'A' + 0x0A);
  776. }
  777. skip += m[0].eo;
  778. if(!mod->chunk_left)
  779. {
  780. lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_response);
  781. string_buffer_push(lua, mod->content);
  782. mod->content = NULL;
  783. lua_setfield(lua, -2, __content);
  784. mod->status = 3;
  785. callback(mod);
  786. if(mod->is_connection_close)
  787. {
  788. on_close(mod);
  789. return;
  790. }
  791. break;
  792. }
  793. mod->chunk_left += 2;
  794. }
  795. const size_t tail = size - skip;
  796. if(mod->chunk_left <= tail)
  797. {
  798. string_buffer_addlstring(mod->content, &mod->buffer[skip], mod->chunk_left - 2);
  799. skip += mod->chunk_left;
  800. mod->chunk_left = 0;
  801. }
  802. else
  803. {
  804. string_buffer_addlstring(mod->content, &mod->buffer[skip], tail);
  805. mod->chunk_left -= tail;
  806. break;
  807. }
  808. }
  809. mod->buffer_skip = 0;
  810. return;
  811. }
  812. // Content-Length: *
  813. if(mod->is_content_length)
  814. {
  815. const size_t tail = mod->buffer_skip - skip;
  816. if(mod->chunk_left > tail)
  817. {
  818. string_buffer_addlstring(mod->content, &mod->buffer[skip], tail);
  819. mod->chunk_left -= tail;
  820. }
  821. else
  822. {
  823. string_buffer_addlstring(mod->content, &mod->buffer[skip], mod->chunk_left);
  824. mod->chunk_left = 0;
  825. lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_response);
  826. string_buffer_push(lua, mod->content);
  827. mod->content = NULL;
  828. lua_setfield(lua, -2, __content);
  829. mod->status = 3;
  830. callback(mod);
  831. if(mod->is_connection_close)
  832. {
  833. on_close(mod);
  834. return;
  835. }
  836. }
  837. mod->buffer_skip = 0;
  838. return;
  839. }
  840. }
  841. /*
  842. * oooooooo8 ooooooooooo oooo oooo ooooooooo
  843. * 888 888 88 8888o 88 888 88o
  844. * 888oooooo 888ooo8 88 888o88 888 888
  845. * 888 888 oo 88 8888 888 888
  846. * o88oooo888 o888ooo8888 o88o 88 o888ooo88
  847. *
  848. */
  849. static void on_ready_send_content(void *arg)
  850. {
  851. module_data_t *mod = (module_data_t *)arg;
  852. asc_assert(mod->request.size > 0, MSG("invalid content size"));
  853. const size_t rem = mod->request.size - mod->request.skip;
  854. const size_t cap = (rem > HTTP_BUFFER_SIZE) ? HTTP_BUFFER_SIZE : rem;
  855. const ssize_t send_size = asc_socket_send( mod->sock
  856. , &mod->request.buffer[mod->request.skip]
  857. , cap);
  858. if(send_size == -1)
  859. {
  860. asc_log_error(MSG("failed to send content [%s]"), asc_socket_error());
  861. on_close(mod);
  862. return;
  863. }
  864. mod->request.skip += send_size;
  865. if(mod->request.skip >= mod->request.size)
  866. {
  867. mod->request.buffer = NULL;
  868. luaL_unref(lua, LUA_REGISTRYINDEX, mod->request.idx_body);
  869. mod->request.idx_body = 0;
  870. mod->request.status = 3;
  871. asc_socket_set_on_ready(mod->sock, NULL);
  872. }
  873. }
  874. static void on_ready_send_request(void *arg)
  875. {
  876. module_data_t *mod = (module_data_t *)arg;
  877. asc_assert(mod->request.size > 0, MSG("invalid request size"));
  878. const size_t rem = mod->request.size - mod->request.skip;
  879. const size_t cap = (rem > HTTP_BUFFER_SIZE) ? HTTP_BUFFER_SIZE : rem;
  880. const ssize_t send_size = asc_socket_send( mod->sock
  881. , &mod->request.buffer[mod->request.skip]
  882. , cap);
  883. if(send_size == -1)
  884. {
  885. asc_log_error(MSG("failed to send response [%s]"), asc_socket_error());
  886. on_close(mod);
  887. return;
  888. }
  889. mod->request.skip += send_size;
  890. if(mod->request.skip >= mod->request.size)
  891. {
  892. free((void *)mod->request.buffer);
  893. mod->request.buffer = NULL;
  894. if(mod->request.idx_body)
  895. {
  896. lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->request.idx_body);
  897. mod->request.buffer = lua_tostring(lua, -1);
  898. mod->request.size = luaL_len(lua, -1);
  899. mod->request.skip = 0;
  900. lua_pop(lua, 1);
  901. mod->request.status = 2;
  902. asc_socket_set_on_ready(mod->sock, on_ready_send_content);
  903. }
  904. else
  905. {
  906. mod->request.status = 3;
  907. asc_socket_set_on_ready(mod->sock, NULL);
  908. }
  909. }
  910. }
  911. static void lua_make_request(module_data_t *mod)
  912. {
  913. lua_getfield(lua, -1, __method);
  914. const char *method = lua_isstring(lua, -1) ? lua_tostring(lua, -1) : __default_method;
  915. lua_pop(lua, 1);
  916. mod->is_head = (strcmp(method, "HEAD") == 0);
  917. lua_getfield(lua, -1, __path);
  918. mod->config.path = lua_isstring(lua, -1) ? lua_tostring(lua, -1) : __default_path;
  919. lua_pop(lua, 1);
  920. lua_getfield(lua, -1, __version);
  921. const char *version = lua_isstring(lua, -1) ? lua_tostring(lua, -1) : __default_version;
  922. lua_pop(lua, 1);
  923. string_buffer_t *buffer = string_buffer_alloc();
  924. string_buffer_addfstring(buffer, "%s %s %s\r\n", method, mod->config.path, version);
  925. lua_getfield(lua, -1, __headers);
  926. if(lua_istable(lua, -1))
  927. {
  928. for(lua_pushnil(lua); lua_next(lua, -2); lua_pop(lua, 1))
  929. {
  930. const char *h = lua_tostring(lua, -1);
  931. if(!strncasecmp(h, __connection, sizeof(__connection) - 1))
  932. {
  933. const char *hp = &h[sizeof(__connection) - 1];
  934. if(!strncasecmp(hp, __close, sizeof(__close) - 1))
  935. mod->is_connection_close = true;
  936. else if(!strncasecmp(hp, __keep_alive, sizeof(__keep_alive) - 1))
  937. mod->is_connection_keep_alive = true;
  938. }
  939. string_buffer_addfstring(buffer, "%s\r\n", h);
  940. }
  941. }
  942. lua_pop(lua, 1); // headers
  943. string_buffer_addlstring(buffer, "\r\n", 2);
  944. mod->request.buffer = string_buffer_release(buffer, &mod->request.size);
  945. mod->request.skip = 0;
  946. if(mod->request.idx_body)
  947. {
  948. luaL_unref(lua, LUA_REGISTRYINDEX, mod->request.idx_body);
  949. mod->request.idx_body = 0;
  950. }
  951. lua_getfield(lua, -1, __content);
  952. if(lua_isstring(lua, -1))
  953. mod->request.idx_body = luaL_ref(lua, LUA_REGISTRYINDEX);
  954. else
  955. lua_pop(lua, 1);
  956. }
  957. static void on_connect(void *arg)
  958. {
  959. module_data_t *mod = (module_data_t *)arg;
  960. mod->request.status = 1;
  961. asc_timer_destroy(mod->timeout);
  962. mod->timeout = asc_timer_init(mod->timeout_ms, timeout_callback, mod);
  963. lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_self);
  964. lua_getfield(lua, -1, "__options");
  965. lua_make_request(mod);
  966. lua_pop(lua, 2); // self + __options
  967. asc_socket_set_on_read(mod->sock, on_read);
  968. asc_socket_set_on_ready(mod->sock, on_ready_send_request);
  969. }
  970. static void on_upstream_ready(void *arg)
  971. {
  972. module_data_t *mod = (module_data_t *)arg;
  973. if(mod->sync.buffer_count > 0)
  974. {
  975. size_t block_size = (mod->sync.buffer_write > mod->sync.buffer_read)
  976. ? (mod->sync.buffer_write - mod->sync.buffer_read)
  977. : (mod->sync.buffer_size - mod->sync.buffer_read);
  978. if(block_size > mod->sync.buffer_count)
  979. block_size = mod->sync.buffer_count;
  980. const ssize_t send_size = asc_socket_send( mod->sock
  981. , &mod->sync.buffer[mod->sync.buffer_read]
  982. , block_size);
  983. if(send_size > 0)
  984. {
  985. mod->sync.buffer_count -= send_size;
  986. mod->sync.buffer_read += send_size;
  987. if(mod->sync.buffer_read >= mod->sync.buffer_size)
  988. mod->sync.buffer_read = 0;
  989. }
  990. else if(send_size == -1)
  991. {
  992. asc_log_error( MSG("failed to send ts (%lu bytes) [%s]")
  993. , block_size, asc_socket_error());
  994. on_close(mod);
  995. return;
  996. }
  997. }
  998. if(mod->sync.buffer_count == 0)
  999. {
  1000. asc_socket_set_on_ready(mod->sock, NULL);
  1001. mod->is_socket_busy = false;
  1002. }
  1003. }
  1004. static void on_ts(module_data_t *mod, const uint8_t *ts)
  1005. {
  1006. if(mod->status != 3 || mod->status_code != 200)
  1007. return;
  1008. if(mod->sync.buffer_count + TS_PACKET_SIZE >= mod->sync.buffer_size)
  1009. {
  1010. // overflow
  1011. mod->sync.buffer_count = 0;
  1012. mod->sync.buffer_read = 0;
  1013. mod->sync.buffer_write = 0;
  1014. if(mod->is_socket_busy)
  1015. {
  1016. asc_socket_set_on_ready(mod->sock, NULL);
  1017. mod->is_socket_busy = false;
  1018. }
  1019. return;
  1020. }
  1021. const size_t buffer_write = mod->sync.buffer_write + TS_PACKET_SIZE;
  1022. if(buffer_write < mod->sync.buffer_size)
  1023. {
  1024. memcpy(&mod->sync.buffer[mod->sync.buffer_write], ts, TS_PACKET_SIZE);
  1025. mod->sync.buffer_write = buffer_write;
  1026. }
  1027. else if(buffer_write > mod->sync.buffer_size)
  1028. {
  1029. const size_t ts_head = mod->sync.buffer_size - mod->sync.buffer_write;
  1030. memcpy(&mod->sync.buffer[mod->sync.buffer_write], ts, ts_head);
  1031. mod->sync.buffer_write = TS_PACKET_SIZE - ts_head;
  1032. memcpy(mod->sync.buffer, &ts[ts_head], mod->sync.buffer_write);
  1033. }
  1034. else
  1035. {
  1036. memcpy(&mod->sync.buffer[mod->sync.buffer_write], ts, TS_PACKET_SIZE);
  1037. mod->sync.buffer_write = 0;
  1038. }
  1039. mod->sync.buffer_count += TS_PACKET_SIZE;
  1040. if( mod->is_socket_busy == false
  1041. && mod->sync.buffer_count >= mod->sync.buffer_fill)
  1042. {
  1043. asc_socket_set_on_ready(mod->sock, on_upstream_ready);
  1044. mod->is_socket_busy = true;
  1045. }
  1046. }
  1047. /*
  1048. * oooo oooo ooooooo ooooooooo ooooo oooo ooooo ooooooooooo
  1049. * 8888o 888 o888 888o 888 88o 888 88 888 888 88
  1050. * 88 888o8 88 888 888 888 888 888 88 888 888ooo8
  1051. * 88 888 88 888o o888 888 888 888 88 888 o 888 oo
  1052. * o88o 8 o88o 88ooo88 o888ooo88 888oo88 o888ooooo88 o888ooo8888
  1053. *
  1054. */
  1055. static int method_set_receiver(module_data_t *mod)
  1056. {
  1057. if(lua_isnil(lua, -1))
  1058. {
  1059. mod->receiver.arg = NULL;
  1060. mod->receiver.callback.ptr = NULL;
  1061. }
  1062. else
  1063. {
  1064. mod->receiver.arg = lua_touserdata(lua, -2);
  1065. mod->receiver.callback.ptr = lua_touserdata(lua, -1);
  1066. }
  1067. return 0;
  1068. }
  1069. static int method_send(module_data_t *mod)
  1070. {
  1071. mod->status = 0;
  1072. if(mod->timeout)
  1073. asc_timer_destroy(mod->timeout);
  1074. mod->timeout = asc_timer_init(mod->timeout_ms, timeout_callback, mod);
  1075. asc_assert(lua_istable(lua, 2), MSG(":send() table required"));
  1076. lua_pushvalue(lua, 2);
  1077. lua_make_request(mod);
  1078. lua_pop(lua, 2); // :send() options
  1079. asc_socket_set_on_read(mod->sock, on_read);
  1080. asc_socket_set_on_ready(mod->sock, on_ready_send_request);
  1081. return 0;
  1082. }
  1083. static int method_close(module_data_t *mod)
  1084. {
  1085. mod->status = -1;
  1086. mod->request.status = -1;
  1087. on_close(mod);
  1088. return 0;
  1089. }
  1090. static void module_init(module_data_t *mod)
  1091. {
  1092. module_option_string("host", &mod->config.host, NULL);
  1093. asc_assert(mod->config.host != NULL, MSG("option 'host' is required"));
  1094. mod->config.port = 80;
  1095. module_option_number("port", &mod->config.port);
  1096. mod->config.path = __default_path;
  1097. module_option_string(__path, &mod->config.path, NULL);
  1098. lua_getfield(lua, 2, __callback);
  1099. asc_assert(lua_isfunction(lua, -1), MSG("option 'callback' is required"));
  1100. lua_pop(lua, 1); // callback
  1101. // store self in registry
  1102. lua_pushvalue(lua, 3);
  1103. mod->idx_self = luaL_ref(lua, LUA_REGISTRYINDEX);
  1104. module_option_boolean(__stream, &mod->is_stream);
  1105. if(mod->is_stream)
  1106. {
  1107. module_stream_init(mod, NULL);
  1108. int value = 0;
  1109. module_option_number("sync", &value);
  1110. if(value > 0)
  1111. mod->config.sync = true;
  1112. else
  1113. value = 1;
  1114. mod->sync.buffer_size = value * 1024 * 1024;
  1115. }
  1116. lua_getfield(lua, MODULE_OPTIONS_IDX, "upstream");
  1117. if(lua_type(lua, -1) == LUA_TLIGHTUSERDATA)
  1118. {
  1119. asc_assert(mod->is_stream != true, MSG("option 'upstream' is not allowed in stream mode"));
  1120. module_stream_init(mod, on_ts);
  1121. int value = 1024;
  1122. module_option_number("buffer_size", &value);
  1123. mod->sync.buffer_size = value * 1024;
  1124. mod->sync.buffer = (uint8_t *)malloc(mod->sync.buffer_size);
  1125. value = 128;
  1126. module_option_number("buffer_fill", &value);
  1127. mod->sync.buffer_fill = value * 1024;
  1128. }
  1129. lua_pop(lua, 1);
  1130. mod->timeout_ms = 10;
  1131. module_option_number("timeout", &mod->timeout_ms);
  1132. mod->timeout_ms *= 1000;
  1133. mod->timeout = asc_timer_init(mod->timeout_ms, timeout_callback, mod);
  1134. bool sctp = false;
  1135. module_option_boolean("sctp", &sctp);
  1136. if(sctp == true)
  1137. mod->sock = asc_socket_open_sctp4(mod);
  1138. else
  1139. mod->sock = asc_socket_open_tcp4(mod);
  1140. asc_socket_connect(mod->sock, mod->config.host, mod->config.port, on_connect, on_close);
  1141. }
  1142. static void module_destroy(module_data_t *mod)
  1143. {
  1144. mod->status = -1;
  1145. mod->request.status = -1;
  1146. on_close(mod);
  1147. }
  1148. MODULE_STREAM_METHODS()
  1149. MODULE_LUA_METHODS()
  1150. {
  1151. MODULE_STREAM_METHODS_REF(),
  1152. { "send", method_send },
  1153. { "close", method_close },
  1154. { "set_receiver", method_set_receiver },
  1155. };
  1156. MODULE_LUA_REGISTER(http_request)