luat_lib_http.c 15 KB

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