luat_lib_http.c 15 KB

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