luat_lib_http.c 16 KB

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