luat_lib_http.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. static int l_http_request(lua_State *L) {
  106. size_t server_cert_len = 0,client_cert_len = 0, client_key_len = 0, client_password_len = 0,len = 0;
  107. const char *server_cert = NULL;
  108. const char *client_cert = NULL;
  109. const char *client_key = NULL;
  110. const char *client_password = NULL;
  111. int adapter_index = -1;
  112. char body_len[16] = {0};
  113. // mbedtls_debug_set_threshold(4);
  114. luat_http_ctrl_t *http_ctrl = (luat_http_ctrl_t *)luat_heap_malloc(sizeof(luat_http_ctrl_t));
  115. if (!http_ctrl){
  116. LLOGE("out of memory when malloc http_ctrl");
  117. lua_pushinteger(L,HTTP_ERROR_CONNECT);
  118. luat_pushcwait_error(L,1);
  119. return 1;
  120. }
  121. memset(http_ctrl, 0, sizeof(luat_http_ctrl_t));
  122. http_ctrl->timeout = 0;
  123. int use_ipv6 = 0;
  124. int is_debug = 0;
  125. if (lua_istable(L, 5)){
  126. lua_pushstring(L, "adapter");
  127. if (LUA_TNUMBER == lua_gettable(L, 5)) {
  128. adapter_index = luaL_optinteger(L, -1, network_get_last_register_adapter());
  129. }else{
  130. adapter_index = network_get_last_register_adapter();
  131. }
  132. lua_pop(L, 1);
  133. lua_pushstring(L, "timeout");
  134. if (LUA_TNUMBER == lua_gettable(L, 5)) {
  135. http_ctrl->timeout = luaL_optinteger(L, -1, 0);
  136. }
  137. lua_pop(L, 1);
  138. lua_pushstring(L, "dst");
  139. if (LUA_TSTRING == lua_gettable(L, 5)) {
  140. const char *dst = luaL_checklstring(L, -1, &len);
  141. http_ctrl->dst = luat_heap_malloc(len + 1);
  142. memset(http_ctrl->dst, 0, len + 1);
  143. memcpy(http_ctrl->dst, dst, len);
  144. http_ctrl->is_download = 1;
  145. }
  146. lua_pop(L, 1);
  147. lua_pushstring(L, "debug");
  148. if (LUA_TBOOLEAN == lua_gettable(L, 5)) {
  149. is_debug = lua_toboolean(L, -1);
  150. }
  151. lua_pop(L, 1);
  152. #ifdef LUAT_USE_FOTA
  153. http_ctrl->address = 0xffffffff;
  154. http_ctrl->length = 0;
  155. lua_pushstring(L, "fota");
  156. int type = lua_gettable(L, 5);
  157. if (LUA_TBOOLEAN == type) {
  158. http_ctrl->isfota = lua_toboolean(L, -1);
  159. }else if (LUA_TTABLE == type) {
  160. http_ctrl->isfota = 1;
  161. lua_pushstring(L, "address");
  162. if (LUA_TNUMBER == lua_gettable(L, -2)) {
  163. http_ctrl->address = luaL_checkinteger(L, -1);
  164. }
  165. lua_pop(L, 1);
  166. lua_pushstring(L, "length");
  167. if (LUA_TNUMBER == lua_gettable(L, -2)) {
  168. http_ctrl->length = luaL_checkinteger(L, -1);
  169. }
  170. lua_pop(L, 1);
  171. lua_pushstring(L, "param1");
  172. if (LUA_TUSERDATA == lua_gettable(L, -2)) {
  173. http_ctrl->spi_device = (luat_spi_device_t*)lua_touserdata(L, -1);
  174. }
  175. lua_pop(L, 1);
  176. }
  177. lua_pop(L, 1);
  178. #endif
  179. lua_pushstring(L, "ipv6");
  180. if (LUA_TBOOLEAN == lua_gettable(L, 5) && lua_toboolean(L, -1)) {
  181. use_ipv6 = 1;
  182. }
  183. lua_pop(L, 1);
  184. lua_pushstring(L, "callback");
  185. if (LUA_TFUNCTION == lua_gettable(L, 5)) {
  186. http_ctrl->http_cb = (void*)luaL_ref(L, LUA_REGISTRYINDEX);
  187. }
  188. if (http_ctrl->http_cb){
  189. lua_pushstring(L, "userdata");
  190. lua_gettable(L, 5);
  191. http_ctrl->http_cb_userdata = (void*)luaL_ref(L, LUA_REGISTRYINDEX);
  192. }
  193. }else{
  194. adapter_index = network_get_last_register_adapter();
  195. }
  196. #ifdef LUAT_USE_FOTA
  197. if (http_ctrl->isfota == 1 && http_ctrl->is_download == 1){
  198. LLOGE("Only one can be selected for FOTA and Download");
  199. goto error;
  200. }
  201. #endif
  202. if (adapter_index < 0 || adapter_index >= NW_ADAPTER_QTY){
  203. LLOGE("bad network adapter index %d", adapter_index);
  204. goto error;
  205. }
  206. http_ctrl->netc = network_alloc_ctrl((uint8_t)adapter_index);
  207. if (!http_ctrl->netc){
  208. LLOGE("netc create fail");
  209. goto error;
  210. }
  211. #ifdef LUAT_USE_FOTA
  212. if (http_ctrl->timeout < 1000 && http_ctrl->isfota) {
  213. http_ctrl->timeout = HTTP_TIMEOUT;
  214. }
  215. #endif
  216. if (http_ctrl->timeout < 1000) {
  217. if (http_ctrl->is_download) {
  218. http_ctrl->timeout = HTTP_TIMEOUT;
  219. }
  220. else {
  221. http_ctrl->timeout = 60*1000;
  222. }
  223. }
  224. LLOGD("http action timeout %dms", http_ctrl->timeout);
  225. luat_http_client_init(http_ctrl, use_ipv6);
  226. http_ctrl->netc->is_debug = (uint8_t)is_debug;
  227. http_ctrl->debug_onoff = (uint8_t)is_debug;
  228. const char *method = luaL_optlstring(L, 1, "GET", &len);
  229. if (len > 11) {
  230. LLOGE("method is too long %s", method);
  231. goto error;
  232. }
  233. // memcpy(http_ctrl->method, method, len + 1);
  234. // LLOGD("method:%s",http_ctrl->method);
  235. if (strcmp("POST", method) == 0 || strcmp("PUT", method) == 0){
  236. http_ctrl->is_post = 1;
  237. }
  238. const char *url = luaL_checklstring(L, 2, &len);
  239. // http_ctrl->url = luat_heap_malloc(len + 1);
  240. // memset(http_ctrl->url, 0, len + 1);
  241. // memcpy(http_ctrl->url, url, len);
  242. int ret = http_set_url(http_ctrl, url, method);
  243. if (ret){
  244. goto error;
  245. }
  246. // LLOGD("http_ctrl->url:%s",http_ctrl->url);
  247. #ifndef LUAT_USE_TLS
  248. if (http_ctrl->is_tls){
  249. LLOGE("NOT SUPPORT TLS");
  250. goto error;
  251. }
  252. #endif
  253. if (lua_istable(L, 3)) {
  254. lua_pushnil(L);
  255. while (lua_next(L, 3) != 0) {
  256. const char *name = lua_tostring(L, -2);
  257. const char *value = lua_tostring(L, -1);
  258. if (!strcmp("Host", name) || !strcmp("host", name)) {
  259. http_ctrl->custom_host = 1;
  260. }
  261. if (strcmp("Content-Length", name)) {
  262. http_add_header(http_ctrl,name,value);
  263. }
  264. lua_pop(L, 1);
  265. }
  266. }
  267. if (lua_isstring(L, 4)) {
  268. const char *body = luaL_checklstring(L, 4, &(http_ctrl->req_body_len));
  269. http_ctrl->req_body = luat_heap_malloc((http_ctrl->req_body_len) + 1);
  270. // TODO 检测req_body是否为NULL
  271. memset(http_ctrl->req_body, 0, (http_ctrl->req_body_len) + 1);
  272. memcpy(http_ctrl->req_body, body, (http_ctrl->req_body_len));
  273. snprintf_(body_len, 16,"%d",(http_ctrl->req_body_len));
  274. http_add_header(http_ctrl,"Content-Length",body_len);
  275. }else if(lua_isuserdata(L, 4)){//zbuff
  276. http_ctrl->zbuff_body = ((luat_zbuff_t *)luaL_checkudata(L, 4, LUAT_ZBUFF_TYPE));
  277. if (http_ctrl->is_post){
  278. snprintf_(body_len, 16,"%d",(http_ctrl->zbuff_body->used));
  279. http_add_header(http_ctrl,"Content-Length",body_len);
  280. }
  281. }
  282. // TODO 对 req_header进行realloc
  283. if (http_ctrl->is_tls){
  284. if (lua_isstring(L, 6)){
  285. server_cert = luaL_checklstring(L, 6, &server_cert_len);
  286. }
  287. if (lua_isstring(L, 7)){
  288. client_cert = luaL_checklstring(L, 7, &client_cert_len);
  289. }
  290. if (lua_isstring(L, 8)){
  291. client_key = luaL_checklstring(L, 8, &client_key_len);
  292. }
  293. if (lua_isstring(L, 9)){
  294. client_password = luaL_checklstring(L, 9, &client_password_len);
  295. }
  296. network_init_tls(http_ctrl->netc, (server_cert || client_cert)?2:0);
  297. if (server_cert){
  298. network_set_server_cert(http_ctrl->netc, (const unsigned char *)server_cert, server_cert_len+1);
  299. }
  300. if (client_cert){
  301. network_set_client_cert(http_ctrl->netc, (const unsigned char *)client_cert, client_cert_len+1,
  302. (const unsigned char *)client_key, client_key_len+1,
  303. (const unsigned char *)client_password, client_password_len+1);
  304. }
  305. }else{
  306. network_deinit_tls(http_ctrl->netc);
  307. }
  308. network_set_ip_invaild(&http_ctrl->ip_addr);
  309. http_ctrl->idp = luat_pushcwait(L);
  310. if (luat_http_client_start_luatos(http_ctrl)) {
  311. goto error;
  312. }
  313. return 1;
  314. error:
  315. // if (http_ctrl->timeout_timer){
  316. // luat_stop_rtos_timer(http_ctrl->timeout_timer);
  317. // }
  318. http_close(http_ctrl);
  319. lua_pushinteger(L,HTTP_ERROR_CONNECT);
  320. luat_pushcwait_error(L,1);
  321. return 1;
  322. }
  323. #include "rotable2.h"
  324. const rotable_Reg_t reg_http[] =
  325. {
  326. {"request", ROREG_FUNC(l_http_request)},
  327. { NULL, ROREG_INT(0)}
  328. };
  329. const rotable_Reg_t reg_http_emtry[] =
  330. {
  331. { NULL, ROREG_INT(0)}
  332. };
  333. LUAMOD_API int luaopen_http( lua_State *L ) {
  334. #ifdef LUAT_USE_NETWORK
  335. luat_newlib2(L, reg_http);
  336. #else
  337. luat_newlib2(L, reg_http_emtry);
  338. LLOGE("reg_http require network enable!!");
  339. #endif
  340. lua_pushvalue(L, -1);
  341. lua_setglobal(L, "http2");
  342. return 1;
  343. }
  344. //------------------------------------------------------
  345. int32_t l_http_callback(lua_State *L, void* ptr){
  346. (void)ptr;
  347. char* temp;
  348. char* header;
  349. char* value;
  350. uint16_t header_len = 0,value_len = 0;
  351. rtos_msg_t* msg = (rtos_msg_t*)lua_topointer(L, -1);
  352. luat_http_ctrl_t *http_ctrl =(luat_http_ctrl_t *)msg->ptr;
  353. uint64_t idp = http_ctrl->idp;
  354. if (http_ctrl->timeout_timer){
  355. luat_stop_rtos_timer(http_ctrl->timeout_timer);
  356. luat_release_rtos_timer(http_ctrl->timeout_timer);
  357. http_ctrl->timeout_timer = NULL;
  358. }
  359. LLOGD("l_http_callback arg1:%d is_download:%d idp:%d",msg->arg1,http_ctrl->is_download,idp);
  360. if (msg->arg1!=0 && msg->arg1!=HTTP_ERROR_FOTA ){
  361. if (msg->arg1 == HTTP_CALLBACK){
  362. lua_geti(L, LUA_REGISTRYINDEX, (int)http_ctrl->http_cb);
  363. // int userdata_type = lua_type(L, -2);
  364. if (lua_isfunction(L, -1)) {
  365. lua_pushinteger(L, http_ctrl->resp_content_len);
  366. lua_pushinteger(L, msg->arg2);
  367. if (http_ctrl->http_cb_userdata){
  368. lua_geti(L, LUA_REGISTRYINDEX, (int)http_ctrl->http_cb_userdata);
  369. lua_call(L, 3, 0);
  370. }else{
  371. lua_call(L, 2, 0);
  372. }
  373. }
  374. return 0;
  375. }else{
  376. lua_pushinteger(L, msg->arg1); // 把错误码返回去
  377. luat_cbcwait(L, idp, 1);
  378. goto exit;
  379. }
  380. }
  381. lua_pushinteger(L, msg->arg1==HTTP_ERROR_FOTA?HTTP_ERROR_FOTA:http_ctrl->parser.status_code);
  382. lua_newtable(L);
  383. // LLOGD("http_ctrl->headers:%.*s",http_ctrl->headers_len,http_ctrl->headers);
  384. header = http_ctrl->headers;
  385. while ( (http_ctrl->headers_len)>0 ){
  386. value = strstr(header,":")+1;
  387. if (value[1]==' '){
  388. value++;
  389. }
  390. temp = strstr(value,"\r\n")+2;
  391. header_len = (uint16_t)(value-header)-1;
  392. value_len = (uint16_t)(temp-value)-2;
  393. LLOGD("header:%.*s",header_len,header);
  394. LLOGD("value:%.*s",value_len,value);
  395. lua_pushlstring(L, header,header_len);
  396. lua_pushlstring(L, value,value_len);
  397. lua_settable(L, -3);
  398. http_ctrl->headers_len -= temp-header;
  399. header = temp;
  400. }
  401. // LLOGD("http_ctrl->body:%.*s len:%d",http_ctrl->body_len,http_ctrl->body,http_ctrl->body_len);
  402. // 处理body, 需要区分下载模式和非下载模式
  403. if (http_ctrl->is_download) {
  404. // 下载模式
  405. if (http_ctrl->fd == NULL) {
  406. // 下载操作一切正常, 返回长度
  407. lua_pushinteger(L, http_ctrl->body_len);
  408. luat_cbcwait(L, idp, 3); // code, headers, body
  409. goto exit;
  410. }else if (http_ctrl->fd != NULL) {
  411. // 下载中断了!!
  412. luat_fs_fclose(http_ctrl->fd);
  413. luat_fs_remove(http_ctrl->dst); // 移除文件
  414. }
  415. // 下载失败, 返回错误码
  416. lua_pushinteger(L, -1);
  417. luat_cbcwait(L, idp, 3); // code, headers, body
  418. goto exit;
  419. }
  420. #ifdef LUAT_USE_FOTA
  421. else if(http_ctrl->isfota && http_ctrl->parser.status_code == 200){
  422. lua_pushinteger(L, http_ctrl->body_len);
  423. luat_cbcwait(L, idp, 3); // code, headers, body
  424. }
  425. #endif
  426. else if (http_ctrl->zbuff_body) {
  427. lua_pushinteger(L, http_ctrl->body_len);
  428. luat_cbcwait(L, idp, 3); // code, headers, body
  429. }
  430. else {
  431. // 非下载模式
  432. lua_pushlstring(L, http_ctrl->body, http_ctrl->body_len);
  433. luat_cbcwait(L, idp, 3); // code, headers, body
  434. }
  435. exit:
  436. if (http_ctrl->http_cb){
  437. luaL_unref(L, LUA_REGISTRYINDEX, (int)http_ctrl->http_cb);
  438. http_ctrl->http_cb = 0;
  439. if (http_ctrl->http_cb_userdata){
  440. luaL_unref(L, LUA_REGISTRYINDEX, (int)http_ctrl->http_cb_userdata);
  441. http_ctrl->http_cb_userdata = 0;
  442. }
  443. }
  444. http_close(http_ctrl);
  445. return 0;
  446. }
  447. void luat_http_client_onevent(luat_http_ctrl_t *http_ctrl, int error_code, int arg) {
  448. // network_close(http_ctrl->netc, 0);
  449. rtos_msg_t msg = {0};
  450. msg.handler = l_http_callback;
  451. msg.ptr = http_ctrl;
  452. msg.arg1 = error_code;
  453. msg.arg2 = arg;
  454. luat_msgbus_put(&msg, 0);
  455. }