luat_lib_http.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. /*
  2. @module http
  3. @summary http 客户端
  4. @version 1.0
  5. @date 2022.09.05
  6. @demo http
  7. @tag LUAT_USE_NETWORK
  8. @usage
  9. -- 使用http库,需要引入sysplus库, 且需要在task内使用
  10. require "sys"
  11. require "sysplus"
  12. sys.taskInit(function()
  13. sys.wait(1000)
  14. local code,headers,body = http.request("GET", "http://www.example.com/abc").wait()
  15. log.info("http", code, body)
  16. end)
  17. */
  18. #include "luat_base.h"
  19. #include "luat_spi.h"
  20. #include "luat_network_adapter.h"
  21. #include "luat_rtos.h"
  22. #include "luat_msgbus.h"
  23. #include "luat_fs.h"
  24. #include "luat_malloc.h"
  25. #include "http_parser.h"
  26. #include "luat_http.h"
  27. #define LUAT_LOG_TAG "http"
  28. #include "luat_log.h"
  29. #define HTTP_DEBUG 0
  30. #if HTTP_DEBUG == 0
  31. #undef LLOGD
  32. #define LLOGD(...)
  33. #endif
  34. int http_close(luat_http_ctrl_t *http_ctrl);
  35. int http_set_url(luat_http_ctrl_t *http_ctrl, const char* url, const char* method);
  36. static int http_add_header(luat_http_ctrl_t *http_ctrl, const char* name, const char* value){
  37. // TODO 对value还需要进行urlencode
  38. char tmp[1024] = {0};
  39. int ret = snprintf(tmp, 1023, "%s:%s\r\n", name, value);
  40. // LLOGI("snprintf %d", ret);
  41. if (ret < 1) {
  42. return 0;
  43. }
  44. if (http_ctrl->req_header == NULL) {
  45. http_ctrl->req_header = luat_heap_malloc(strlen(tmp)+1);
  46. if (http_ctrl->req_header == NULL) {
  47. LLOGE("out of memory when malloc custom headers");
  48. return 0;
  49. }
  50. http_ctrl->req_header[0] = 0;
  51. }
  52. else {
  53. void *ptr = luat_heap_realloc(http_ctrl->req_header, strlen(http_ctrl->req_header) + strlen(tmp) + 1);
  54. if (ptr == NULL) {
  55. LLOGE("out of memory when malloc custom headers");
  56. return 0;
  57. }
  58. http_ctrl->req_header = ptr;
  59. }
  60. memcpy(http_ctrl->req_header + strlen(http_ctrl->req_header), tmp, strlen(tmp) + 1);
  61. return 0;
  62. }
  63. /*
  64. http客户端
  65. @api http.request(method,url,headers,body,opts,ca_file,client_ca, client_key, client_password)
  66. @string 请求方法, 支持 GET/POST 等合法的HTTP方法
  67. @string url地址, 支持 http和https, 支持域名, 支持自定义端口
  68. @tabal 请求头 可选 例如 {["Content-Type"] = "application/x-www-form-urlencoded"}
  69. @string body 可选, 对POST/PUT等请求方式有效
  70. @table 额外配置 可选 包含 timeout:超时时间单位ms 可选,默认10分钟,写0即永久等待 dst:下载路径,可选 adapter:选择使用网卡,可选 debug:是否打开debug信息,可选,ipv6:是否为ipv6 默认不是,可选 callback:下载回调函数,参数 content_len:总长度 body_len:以下载长度 userdata 用户传参,可选 userdata:回调自定义传参
  71. @string 服务器ca证书数据, 可选, 一般不需要
  72. @string 客户端ca证书数据, 可选, 一般不需要, 双向https认证才需要
  73. @string 客户端私钥加密数据, 可选, 一般不需要, 双向https认证才需要
  74. @string 客户端私钥口令数据, 可选, 一般不需要, 双向https认证才需要
  75. @return int code , 服务器反馈的值>=100, 最常见的是200.如果是底层错误,例如连接失败, 返回值小于0
  76. @return tabal headers 当code>100时, 代表服务器返回的头部数据
  77. @return string/int body 服务器响应的内容字符串,如果是下载模式, 则返回文件大小
  78. @usage
  79. -- GET请求
  80. local code, headers, body = http.request("GET","http://site0.cn/api/httptest/simple/time").wait()
  81. log.info("http.get", code, headers, body)
  82. -- POST请求
  83. local code, headers, body = http.request("POST","http://httpbin.com/post", {}, "abc=123").wait()
  84. log.info("http.post", code, headers, body)
  85. -- GET请求,但下载到文件
  86. local code, headers, body = http.request("GET","http://httpbin.com/", {}, "", {dst="/data.bin"}).wait()
  87. log.info("http.get", code, headers, body)
  88. -- 自定义超时时间, 5000ms
  89. http.request("GET","http://httpbin.com/", nil, nil, {timeout=5000}).wait()
  90. */
  91. static int l_http_request(lua_State *L) {
  92. size_t server_cert_len,client_cert_len, client_key_len, client_password_len,len;
  93. const char *server_cert = NULL;
  94. const char *client_cert = NULL;
  95. const char *client_key = NULL;
  96. const char *client_password = NULL;
  97. int adapter_index = -1;
  98. char body_len[6] = {0};
  99. // mbedtls_debug_set_threshold(4);
  100. luat_http_ctrl_t *http_ctrl = (luat_http_ctrl_t *)luat_heap_malloc(sizeof(luat_http_ctrl_t));
  101. if (!http_ctrl){
  102. LLOGE("out of memory when malloc http_ctrl");
  103. lua_pushinteger(L,HTTP_ERROR_CONNECT);
  104. luat_pushcwait_error(L,1);
  105. return 1;
  106. }
  107. memset(http_ctrl, 0, sizeof(luat_http_ctrl_t));
  108. http_ctrl->timeout = HTTP_TIMEOUT;
  109. int use_ipv6 = 0;
  110. int is_debug = 0;
  111. if (lua_istable(L, 5)){
  112. lua_pushstring(L, "adapter");
  113. if (LUA_TNUMBER == lua_gettable(L, 5)) {
  114. adapter_index = luaL_optinteger(L, -1, network_get_last_register_adapter());
  115. }else{
  116. adapter_index = network_get_last_register_adapter();
  117. }
  118. lua_pop(L, 1);
  119. lua_pushstring(L, "timeout");
  120. if (LUA_TNUMBER == lua_gettable(L, 5)) {
  121. http_ctrl->timeout = luaL_optinteger(L, -1, HTTP_TIMEOUT);
  122. }
  123. lua_pop(L, 1);
  124. lua_pushstring(L, "dst");
  125. if (LUA_TSTRING == lua_gettable(L, 5)) {
  126. const char *dst = luaL_checklstring(L, -1, &len);
  127. http_ctrl->dst = luat_heap_malloc(len + 1);
  128. memset(http_ctrl->dst, 0, len + 1);
  129. memcpy(http_ctrl->dst, dst, len);
  130. http_ctrl->is_download = 1;
  131. }
  132. lua_pop(L, 1);
  133. lua_pushstring(L, "debug");
  134. if (LUA_TBOOLEAN == lua_gettable(L, 5)) {
  135. is_debug = lua_toboolean(L, -1);
  136. }
  137. lua_pop(L, 1);
  138. #ifdef LUAT_USE_FOTA
  139. http_ctrl->address = 0xffffffff;
  140. http_ctrl->length = 0;
  141. lua_pushstring(L, "fota");
  142. int type = lua_gettable(L, 5);
  143. if (LUA_TBOOLEAN == type) {
  144. http_ctrl->isfota = lua_toboolean(L, -1);
  145. }else if (LUA_TTABLE == type) {
  146. http_ctrl->isfota = 1;
  147. lua_pushstring(L, "address");
  148. if (LUA_TNUMBER == lua_gettable(L, -2)) {
  149. http_ctrl->address = luaL_checkinteger(L, -1);
  150. }
  151. lua_pop(L, 1);
  152. lua_pushstring(L, "length");
  153. if (LUA_TNUMBER == lua_gettable(L, -2)) {
  154. http_ctrl->length = luaL_checkinteger(L, -1);
  155. }
  156. lua_pop(L, 1);
  157. lua_pushstring(L, "param1");
  158. if (LUA_TUSERDATA == lua_gettable(L, -2)) {
  159. http_ctrl->spi_device = (luat_spi_device_t*)lua_touserdata(L, -1);
  160. }
  161. lua_pop(L, 1);
  162. }
  163. lua_pop(L, 1);
  164. #endif
  165. lua_pushstring(L, "ipv6");
  166. if (LUA_TBOOLEAN == lua_gettable(L, 5) && lua_toboolean(L, -1)) {
  167. use_ipv6 = 1;
  168. }
  169. lua_pop(L, 1);
  170. lua_pushstring(L, "callback");
  171. if (LUA_TFUNCTION == lua_gettable(L, 5)) {
  172. http_ctrl->http_cb = luaL_ref(L, LUA_REGISTRYINDEX);
  173. }
  174. if (http_ctrl->http_cb){
  175. lua_pushstring(L, "userdata");
  176. lua_gettable(L, 5);
  177. http_ctrl->http_cb_userdata = luaL_ref(L, LUA_REGISTRYINDEX);
  178. }
  179. }else{
  180. adapter_index = network_get_last_register_adapter();
  181. }
  182. #ifdef LUAT_USE_FOTA
  183. if (http_ctrl->isfota == 1 && http_ctrl->is_download == 1){
  184. LLOGE("Only one can be selected for FOTA and Download");
  185. goto error;
  186. }
  187. #endif
  188. if (adapter_index < 0 || adapter_index >= NW_ADAPTER_QTY){
  189. LLOGE("bad network adapter index %d", adapter_index);
  190. goto error;
  191. }
  192. http_ctrl->netc = network_alloc_ctrl(adapter_index);
  193. if (!http_ctrl->netc){
  194. LLOGE("netc create fail");
  195. goto error;
  196. }
  197. http_ctrl->netc->is_debug = is_debug;
  198. luat_http_client_init(http_ctrl, use_ipv6);
  199. const char *method = luaL_optlstring(L, 1, "GET", &len);
  200. if (len > 11) {
  201. LLOGE("method is too long %s", method);
  202. goto error;
  203. }
  204. // memcpy(http_ctrl->method, method, len + 1);
  205. // LLOGD("method:%s",http_ctrl->method);
  206. const char *url = luaL_checklstring(L, 2, &len);
  207. // http_ctrl->url = luat_heap_malloc(len + 1);
  208. // memset(http_ctrl->url, 0, len + 1);
  209. // memcpy(http_ctrl->url, url, len);
  210. int ret = http_set_url(http_ctrl, url, method);
  211. if (ret){
  212. goto error;
  213. }
  214. // LLOGD("http_ctrl->url:%s",http_ctrl->url);
  215. #ifndef LUAT_USE_TLS
  216. if (http_ctrl->is_tls){
  217. LLOGE("NOT SUPPORT TLS");
  218. goto error;
  219. }
  220. #endif
  221. if (lua_istable(L, 3)) {
  222. lua_pushnil(L);
  223. while (lua_next(L, 3) != 0) {
  224. const char *name = lua_tostring(L, -2);
  225. const char *value = lua_tostring(L, -1);
  226. if (!strcmp("Host", name) || !strcmp("host", name)) {
  227. http_ctrl->custom_host = 1;
  228. }
  229. if (strcmp("Content-Length", name)) {
  230. http_add_header(http_ctrl,name,value);
  231. }
  232. lua_pop(L, 1);
  233. }
  234. }
  235. if (lua_isstring(L, 4)) {
  236. const char *body = luaL_checklstring(L, 4, &(http_ctrl->req_body_len));
  237. http_ctrl->req_body = luat_heap_malloc((http_ctrl->req_body_len) + 1);
  238. // TODO 检测req_body是否为NULL
  239. memset(http_ctrl->req_body, 0, (http_ctrl->req_body_len) + 1);
  240. memcpy(http_ctrl->req_body, body, (http_ctrl->req_body_len));
  241. snprintf_(body_len, 6,"%d",(http_ctrl->req_body_len));
  242. http_add_header(http_ctrl,"Content-Length",body_len);
  243. }
  244. // TODO 对 req_header进行realloc
  245. if (http_ctrl->is_tls){
  246. if (lua_isstring(L, 6)){
  247. server_cert = luaL_checklstring(L, 6, &server_cert_len);
  248. }
  249. if (lua_isstring(L, 7)){
  250. client_cert = luaL_checklstring(L, 7, &client_cert_len);
  251. }
  252. if (lua_isstring(L, 8)){
  253. client_key = luaL_checklstring(L, 8, &client_key_len);
  254. }
  255. if (lua_isstring(L, 9)){
  256. client_password = luaL_checklstring(L, 9, &client_password_len);
  257. }
  258. network_init_tls(http_ctrl->netc, (server_cert || client_cert)?2:0);
  259. if (server_cert){
  260. network_set_server_cert(http_ctrl->netc, (const unsigned char *)server_cert, server_cert_len+1);
  261. }
  262. if (client_cert){
  263. network_set_client_cert(http_ctrl->netc, (const unsigned char *)client_cert, client_cert_len+1,
  264. (const unsigned char *)client_key, client_key_len+1,
  265. (const unsigned char *)client_password, client_password_len+1);
  266. }
  267. }else{
  268. network_deinit_tls(http_ctrl->netc);
  269. }
  270. network_set_ip_invaild(&http_ctrl->ip_addr);
  271. http_ctrl->idp = luat_pushcwait(L);
  272. if (luat_http_client_start(http_ctrl)) {
  273. goto error;
  274. }
  275. return 1;
  276. error:
  277. // if (http_ctrl->timeout_timer){
  278. // luat_stop_rtos_timer(http_ctrl->timeout_timer);
  279. // }
  280. http_close(http_ctrl);
  281. lua_pushinteger(L,HTTP_ERROR_CONNECT);
  282. luat_pushcwait_error(L,1);
  283. return 1;
  284. }
  285. #include "rotable2.h"
  286. const rotable_Reg_t reg_http[] =
  287. {
  288. {"request", ROREG_FUNC(l_http_request)},
  289. { NULL, ROREG_INT(0)}
  290. };
  291. const rotable_Reg_t reg_http_emtry[] =
  292. {
  293. { NULL, ROREG_INT(0)}
  294. };
  295. LUAMOD_API int luaopen_http( lua_State *L ) {
  296. #ifdef LUAT_USE_NETWORK
  297. luat_newlib2(L, reg_http);
  298. #else
  299. luat_newlib2(L, reg_http_emtry);
  300. LLOGE("reg_http require network enable!!");
  301. #endif
  302. lua_pushvalue(L, -1);
  303. lua_setglobal(L, "http2");
  304. return 1;
  305. }
  306. //------------------------------------------------------
  307. int32_t l_http_callback(lua_State *L, void* ptr){
  308. (void)ptr;
  309. char* temp;
  310. char* header;
  311. char* value;
  312. uint16_t header_len = 0,value_len = 0;
  313. rtos_msg_t* msg = (rtos_msg_t*)lua_topointer(L, -1);
  314. luat_http_ctrl_t *http_ctrl =(luat_http_ctrl_t *)msg->ptr;
  315. uint64_t idp = http_ctrl->idp;
  316. if (http_ctrl->timeout_timer){
  317. luat_stop_rtos_timer(http_ctrl->timeout_timer);
  318. luat_release_rtos_timer(http_ctrl->timeout_timer);
  319. http_ctrl->timeout_timer = NULL;
  320. }
  321. LLOGD("l_http_callback arg1:%d is_download:%d idp:%d",msg->arg1,http_ctrl->is_download,idp);
  322. if (msg->arg1!=0 && msg->arg1!=HTTP_ERROR_FOTA ){
  323. if (msg->arg1 == HTTP_CALLBACK){
  324. lua_geti(L, LUA_REGISTRYINDEX, http_ctrl->http_cb);
  325. // int userdata_type = lua_type(L, -2);
  326. if (lua_isfunction(L, -1)) {
  327. lua_pushinteger(L, http_ctrl->resp_content_len);
  328. lua_pushinteger(L, msg->arg2);
  329. if (http_ctrl->http_cb_userdata){
  330. lua_geti(L, LUA_REGISTRYINDEX, http_ctrl->http_cb_userdata);
  331. lua_call(L, 3, 0);
  332. }else{
  333. lua_call(L, 2, 0);
  334. }
  335. }
  336. return 0;
  337. }else{
  338. lua_pushinteger(L, msg->arg1); // 把错误码返回去
  339. luat_cbcwait(L, idp, 1);
  340. goto exit;
  341. }
  342. }
  343. lua_pushinteger(L, msg->arg1==HTTP_ERROR_FOTA?HTTP_ERROR_FOTA:http_ctrl->parser.status_code);
  344. lua_newtable(L);
  345. // LLOGD("http_ctrl->headers:%.*s",http_ctrl->headers_len,http_ctrl->headers);
  346. header = http_ctrl->headers;
  347. while ( (http_ctrl->headers_len)>0 ){
  348. value = strstr(header,":")+1;
  349. if (value[1]==' '){
  350. value++;
  351. }
  352. temp = strstr(value,"\r\n")+2;
  353. header_len = value-header-1;
  354. value_len = temp-value-2;
  355. LLOGD("header:%.*s",header_len,header);
  356. LLOGD("value:%.*s",value_len,value);
  357. lua_pushlstring(L, header,header_len);
  358. lua_pushlstring(L, value,value_len);
  359. lua_settable(L, -3);
  360. http_ctrl->headers_len -= temp-header;
  361. header = temp;
  362. }
  363. LLOGD("http_ctrl->body:%.*s len:%d",http_ctrl->body_len,http_ctrl->body,http_ctrl->body_len);
  364. // 处理body, 需要区分下载模式和非下载模式
  365. if (http_ctrl->is_download) {
  366. // 下载模式
  367. if (http_ctrl->fd == NULL) {
  368. // 下载操作一切正常, 返回长度
  369. lua_pushinteger(L, http_ctrl->body_len);
  370. luat_cbcwait(L, idp, 3); // code, headers, body
  371. goto exit;
  372. }else if (http_ctrl->fd != NULL) {
  373. // 下载中断了!!
  374. luat_fs_fclose(http_ctrl->fd);
  375. luat_fs_remove(http_ctrl->dst); // 移除文件
  376. }
  377. // 下载失败, 返回错误码
  378. lua_pushinteger(L, -1);
  379. luat_cbcwait(L, idp, 3); // code, headers, body
  380. goto exit;
  381. }
  382. #ifdef LUAT_USE_FOTA
  383. else if(http_ctrl->isfota && http_ctrl->parser.status_code == 200){
  384. lua_pushinteger(L, http_ctrl->body_len);
  385. luat_cbcwait(L, idp, 3); // code, headers, body
  386. }
  387. #endif
  388. else {
  389. // 非下载模式
  390. lua_pushlstring(L, http_ctrl->body, http_ctrl->body_len);
  391. luat_cbcwait(L, idp, 3); // code, headers, body
  392. }
  393. exit:
  394. if (http_ctrl->http_cb){
  395. luaL_unref(L, LUA_REGISTRYINDEX, http_ctrl->http_cb);
  396. http_ctrl->http_cb = 0;
  397. if (http_ctrl->http_cb_userdata){
  398. luaL_unref(L, LUA_REGISTRYINDEX, http_ctrl->http_cb_userdata);
  399. http_ctrl->http_cb_userdata = 0;
  400. }
  401. }
  402. http_close(http_ctrl);
  403. return 0;
  404. }
  405. void luat_http_client_onevent(luat_http_ctrl_t *http_ctrl, int arg1, int arg2) {
  406. // network_close(http_ctrl->netc, 0);
  407. rtos_msg_t msg = {0};
  408. msg.handler = l_http_callback;
  409. msg.ptr = http_ctrl;
  410. msg.arg1 = arg1;
  411. msg.arg2 = arg2;
  412. luat_msgbus_put(&msg, 0);
  413. }