httpplus.lua 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. --[[
  2. @module httpplus
  3. @summary http库的补充
  4. @version 1.0
  5. @date 2023.11.23
  6. @author wendal
  7. @demo httpplus
  8. @tag LUAT_USE_NETWORK
  9. @usage
  10. -- 本库支持的功能有:
  11. -- 1. 大文件上传的问题,不限大小
  12. -- 2. 任意长度的header设置
  13. -- 3. 任意长度的body设置
  14. -- 4. 鉴权URL自动识别
  15. -- 5. body使用zbuff返回,可直接传输给uart等库
  16. -- 与http库的差异
  17. -- 1. 不支持文件下载
  18. -- 2. 不支持fota
  19. ]]
  20. local httpplus = {}
  21. local TAG = "httpplus"
  22. local function http_opts_parse(opts)
  23. if not opts then
  24. log.error(TAG, "opts不能为nil")
  25. return -100, "opts不能为nil"
  26. end
  27. if not opts.url or #opts.url < 5 then
  28. log.error(TAG, "URL不存在或者太短了", url)
  29. return -100, "URL不存在或者太短了"
  30. end
  31. if not opts.headers then
  32. opts.headers = {}
  33. end
  34. if opts.debug or httpplus.debug then
  35. if not opts.log then
  36. opts.log = log.debug
  37. end
  38. else
  39. opts.log = function()
  40. -- log.info(TAG, "无日志")
  41. end
  42. end
  43. -- 解析url
  44. -- 先判断协议是否加密
  45. local is_ssl = false
  46. local tmp = ""
  47. if opts.url:startsWith("https://") then
  48. is_ssl = true
  49. tmp = opts.url:sub(9)
  50. elseif opts.url:startsWith("http://") then
  51. tmp = opts.url:sub(8)
  52. else
  53. tmp = opts.url
  54. end
  55. -- log.info("http分解阶段1", is_ssl, tmp)
  56. -- 然后判断host段
  57. local uri = ""
  58. local host = ""
  59. local port = 0
  60. if tmp:find("/") then
  61. uri = tmp:sub((tmp:find("/"))) -- 注意find会返回多个值
  62. tmp = tmp:sub(1, tmp:find("/") - 1)
  63. else
  64. uri = "/"
  65. end
  66. -- log.info("http分解阶段2", is_ssl, tmp, uri)
  67. if tmp == nil or #tmp == 0 then
  68. log.error(TAG, "非法的URL", url)
  69. return -101, "非法的URL"
  70. end
  71. -- 有无鉴权信息
  72. if tmp:find("@") then
  73. local auth = tmp:sub(1, tmp:find("@") - 1)
  74. if not opts.headers["Authorization"] then
  75. opts.headers["Authorization"] = "Basic " .. auth:toBase64()
  76. end
  77. -- log.info("http鉴权信息", auth, opts.headers["Authorization"])
  78. tmp = tmp:sub(tmp:find("@") + 1)
  79. end
  80. -- 解析端口
  81. if tmp:find(":") then
  82. host = tmp:sub(1, tmp:find(":") - 1)
  83. port = tmp:sub(tmp:find(":") + 1)
  84. port = tonumber(port)
  85. else
  86. host = tmp
  87. end
  88. if not port or port < 1 then
  89. if is_ssl then
  90. port = 443
  91. else
  92. port = 80
  93. end
  94. end
  95. -- 收尾工作
  96. if not opts.headers["Host"] then
  97. opts.headers["Host"] = string.format("%s:%d", host, port)
  98. end
  99. -- Connection 必须关闭
  100. opts.headers["Connection"] = "Close"
  101. -- 复位一些变量,免得判断出错
  102. opts.is_closed = nil
  103. opts.body_len = 0
  104. -- multipart需要boundary
  105. local boundary = "------------------------16ef6e68ef" .. tostring(os.time())
  106. opts.boundary = boundary
  107. opts.mp = {}
  108. if opts.files then
  109. -- 强制设置为true
  110. opts.multipart = true
  111. local contentType =
  112. {
  113. txt = "text/plain", -- 文本
  114. jpg = "image/jpeg", -- JPG 格式图片
  115. jpeg = "image/jpeg", -- JPEG 格式图片
  116. png = "image/png", -- PNG 格式图片
  117. gif = "image/gif", -- GIF 格式图片
  118. html = "image/html", -- HTML
  119. json = "application/json" -- JSON
  120. }
  121. for kk, vv in pairs(opts.files) do
  122. local ct = contentType[vv:match("%.(%w+)$")] or "application/octet-stream"
  123. local fname = vv:match("[^%/]+%w$")
  124. local tmp = string.format("--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n", boundary, kk, fname, ct)
  125. -- log.info("文件传输头", tmp)
  126. table.insert(opts.mp, {vv, tmp, "file"})
  127. opts.body_len = opts.body_len + #tmp + io.fileSize(vv) + 2
  128. -- log.info("当前body长度", opts.body_len, "文件长度", io.fileSize(vv), fname, ct)
  129. end
  130. end
  131. -- 表单数据
  132. if opts.forms then
  133. if opts.multipart then
  134. for kk, vv in pairs(opts.forms) do
  135. local tmp = string.format("--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n", boundary, kk)
  136. table.insert(opts.mp, {vv, tmp, "form"})
  137. opts.body_len = opts.body_len + #tmp + #vv + 2
  138. -- log.info("当前body长度", opts.body_len, "数据长度", #vv)
  139. end
  140. else
  141. if not opts.headers["Content-Type"] then
  142. opts.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"
  143. end
  144. local buff = zbuff.create(120)
  145. for kk, vv in pairs(opts.forms) do
  146. buff:copy(nil, kk)
  147. buff:copy(nil, "=")
  148. buff:copy(nil, string.urlEncode(tostring(vv)))
  149. buff:copy(nil, "&")
  150. end
  151. if buff:used() > 0 then
  152. buff:del(-1, 1)
  153. opts.body = buff
  154. opts.body_len = buff:used()
  155. opts.log(TAG, "普通表单", opts.body)
  156. end
  157. end
  158. end
  159. -- 如果multipart模式
  160. if opts.multipart then
  161. -- 如果没主动设置body, 那么补个结尾
  162. if not opts.body then
  163. opts.body_len = opts.body_len + #boundary + 2 + 2 + 2
  164. end
  165. -- Content-Type没设置? 那就设置一下
  166. if not opts.headers["Content-Type"] then
  167. opts.headers["Content-Type"] = "multipart/form-data; boundary="..boundary
  168. end
  169. end
  170. -- 直接设置bodyfile
  171. if opts.bodyfile then
  172. local fd = io.open(opts.bodyfile, "rb")
  173. if not fd then
  174. log.error("httpplus", "bodyfile失败,文件不存在", opts.bodyfile)
  175. return -104, "bodyfile失败,文件不存在"
  176. end
  177. fd:close()
  178. opts.body_len = io.fileSize(opts.bodyfile)
  179. end
  180. -- 有设置body, 而且没设置长度
  181. if opts.body and (not opts.body_len or opts.body_len == 0) then
  182. -- body是zbuff的情况
  183. if type(opts.body) == "userdata" then
  184. opts.body_len = opts.body:used()
  185. -- body是json的情况
  186. elseif type(opts.body) == "table" then
  187. opts.body = json.encode(opts.body, "7f")
  188. if opts.body then
  189. opts.body_len = #opts.body
  190. if not opts.headers["Content-Type"] then
  191. opts.headers["Content-Type"] = "application/json;charset=UTF-8"
  192. opts.log(TAG, "JSON", opts.body)
  193. end
  194. end
  195. -- 其他情况就只能当文本了
  196. else
  197. opts.body = tostring(opts.body)
  198. opts.body_len = #opts.body
  199. end
  200. end
  201. -- 一定要设置Content-Length,而且强制覆盖客户自定义的值
  202. -- opts.body_len = opts.body_len or 0
  203. opts.headers["Content-Length"] = tostring(opts.body_len or 0)
  204. -- 如果没设置method, 自动补齐
  205. if not opts.method or #opts.method == 0 then
  206. if opts.body_len > 0 then
  207. opts.method = "POST"
  208. else
  209. opts.method = "GET"
  210. end
  211. else
  212. -- 确保一定是大写字母
  213. opts.method = opts.method:upper()
  214. end
  215. if opts.debug then
  216. opts.log(TAG, is_ssl, host, port, uri, json.encode(opts.headers))
  217. end
  218. -- 把剩余的属性设置好
  219. opts.host = host
  220. opts.port = port
  221. opts.uri = uri
  222. opts.is_ssl = is_ssl
  223. if not opts.timeout or opts.timeout == 0 then
  224. opts.timeout = 30
  225. end
  226. return -- 成功完成,不需要返回值
  227. end
  228. local function zbuff_find(buff, str)
  229. -- log.info("zbuff查找", buff:used(), #str)
  230. if buff:used() < #str then
  231. return
  232. end
  233. local maxoff = buff:used()
  234. maxoff = maxoff - #str
  235. local tmp = zbuff.create(#str)
  236. tmp:write(str)
  237. -- log.info("tmp数据", tmp:query():toHex())
  238. for i = 0, maxoff, 1 do
  239. local flag = true
  240. for j = 0, #str - 1, 1 do
  241. -- log.info("对比", i, j, string.char(buff[i+j]):toHex(), string.char(tmp[j]):toHex(), buff[i+j] ~= tmp[j])
  242. if buff[i+j] ~= tmp[j] then
  243. flag = false
  244. break
  245. end
  246. end
  247. if flag then
  248. return i
  249. end
  250. end
  251. end
  252. local function resp_parse(opts)
  253. -- log.info("这里--------")
  254. local header_offset = zbuff_find(opts.rx_buff, "\r\n\r\n")
  255. -- log.info("头部偏移量", header_offset)
  256. if not header_offset then
  257. log.warn(TAG, "没有检测到http响应头部,非法响应")
  258. opts.resp_code = -198
  259. return
  260. end
  261. local state_line_offset = zbuff_find(opts.rx_buff, "\r\n")
  262. local state_line = opts.rx_buff:query(0, state_line_offset)
  263. local tmp = state_line:split(" ")
  264. if not tmp or #tmp < 2 then
  265. log.warn(TAG, "非法的响应行", state_line)
  266. opts.resp_code = -197
  267. return
  268. end
  269. local code = tonumber(tmp[2])
  270. if not code then
  271. log.warn(TAG, "非法的响应码", tmp[2])
  272. opts.resp_code = -196
  273. return
  274. end
  275. opts.resp_code = code
  276. opts.resp = {
  277. headers = {}
  278. }
  279. opts.log(TAG, "state code", code)
  280. -- TODO 解析header和body
  281. opts.rx_buff:del(0, state_line_offset + 2)
  282. -- opts.log(TAG, "剩余的响应体", opts.rx_buff:query())
  283. -- 解析headers
  284. while 1 do
  285. local offset = zbuff_find(opts.rx_buff, "\r\n")
  286. if not offset then
  287. log.warn(TAG, "不合法的剩余headers", opts.rx_buff:query())
  288. break
  289. end
  290. if offset == 0 then
  291. -- header的最后一个空行
  292. opts.rx_buff:del(0, 2)
  293. break
  294. end
  295. local line = opts.rx_buff:query(0, offset)
  296. opts.rx_buff:del(0, offset + 2)
  297. local tmp2 = line:split(":")
  298. opts.log(TAG, tmp2[1]:trim(), tmp2[2]:trim())
  299. opts.resp.headers[tmp2[1]:trim()] = tmp2[2]:trim()
  300. end
  301. -- if opts.resp_code < 299 then
  302. -- 解析body
  303. -- 有Content-Length就好办
  304. if opts.resp.headers["Content-Length"] then
  305. opts.log(TAG, "有长度, 标准的咯")
  306. opts.resp.body = opts.rx_buff
  307. elseif opts.resp.headers["Transfer-Encoding"] == "chunked" then
  308. -- log.info(TAG, "数据是chunked编码", opts.rx_buff[0], opts.rx_buff[1])
  309. -- log.info(TAG, "数据是chunked编码", opts.rx_buff:query(0, 4):toHex())
  310. local coffset = 0
  311. local crun = true
  312. while crun and coffset < opts.rx_buff:used() do
  313. -- 从当前offset读取长度, 长度总不会超过8字节吧?
  314. local flag = true
  315. -- local coffset = zbuff_find(opts.rx_buff, "\r\n")
  316. -- if not coffset then
  317. -- end
  318. for i = 1, 8, 1 do
  319. if opts.rx_buff[coffset+i] == 0x0D and opts.rx_buff[coffset+i+1] == 0x0A then
  320. local ctmp = opts.rx_buff:query(coffset, i)
  321. -- opts.log(TAG, "chunked分片长度", ctmp, ctmp:toHex())
  322. local clen = tonumber(ctmp, 16)
  323. -- opts.log(TAG, "chunked分片长度2", clen)
  324. if clen == 0 then
  325. -- 末尾了
  326. opts.rx_buff:resize(coffset)
  327. crun = false
  328. else
  329. -- 先删除chunked块
  330. opts.rx_buff:del(coffset, i+2)
  331. coffset = coffset + clen
  332. end
  333. flag = false
  334. break
  335. end
  336. end
  337. -- 肯定能搜到chunked
  338. if flag then
  339. log.error("非法的chunked块")
  340. break
  341. end
  342. end
  343. opts.resp.body = opts.rx_buff
  344. end
  345. -- end
  346. -- 清空rx_buff
  347. opts.rx_buff = nil
  348. -- 完结散花
  349. end
  350. -- socket 回调函数
  351. local function http_socket_cb(opts, event)
  352. opts.log(TAG, "tcp.event", event)
  353. if event == socket.ON_LINE then
  354. -- TCP链接已建立, 那就可以上行了
  355. -- opts.state = "ON_LINE"
  356. sys.publish(opts.topic)
  357. elseif event == socket.TX_OK then
  358. -- 数据传输完成, 如果是文件上传就需要这个消息
  359. -- opts.state = "TX_OK"
  360. sys.publish(opts.topic)
  361. elseif event == socket.EVENT then
  362. -- 收到数据或者链接断开了, 这里总需要读取一次才知道
  363. local succ, data_len = socket.rx(opts.netc, opts.rx_buff)
  364. if succ and data_len > 0 then
  365. opts.log(TAG, "收到数据", data_len, "总长", #opts.rx_buff)
  366. -- opts.log(TAG, "数据", opts.rx_buff:query())
  367. else
  368. if not opts.is_closed then
  369. opts.log(TAG, "服务器已经断开了连接或接收出错")
  370. opts.is_closed = true
  371. sys.publish(opts.topic)
  372. end
  373. end
  374. elseif event == socket.CLOSED then
  375. log.info(TAG, "连接已关闭")
  376. opts.is_closed = true
  377. sys.publish(opts.topic)
  378. end
  379. end
  380. local function http_exec(opts)
  381. local netc = socket.create(opts.adapter, function(sc, event)
  382. if opts.netc then
  383. return http_socket_cb(opts, event)
  384. end
  385. end)
  386. if not netc then
  387. log.error(TAG, "创建socket失败了!!")
  388. return -102
  389. end
  390. opts.netc = netc
  391. opts.rx_buff = zbuff.create(1024)
  392. opts.topic = tostring(netc)
  393. socket.config(netc, nil,nil, opts.is_ssl)
  394. if opts.debug or httpplus.debug then
  395. socket.debug(netc)
  396. end
  397. if not socket.connect(netc, opts.host, opts.port, opts.try_ipv6) then
  398. log.warn(TAG, "调用socket.connect返回错误了")
  399. return -103, "调用socket.connect返回错误了"
  400. end
  401. local ret = sys.waitUntil(opts.topic, 5000)
  402. if ret == false then
  403. log.warn(TAG, "建立连接超时了!!!")
  404. return -104, "建立连接超时了!!!"
  405. end
  406. -- 首先是头部
  407. local line = string.format("%s %s HTTP/1.1\r\n", opts.method:upper(), opts.uri)
  408. -- opts.log(TAG, line)
  409. socket.tx(netc, line)
  410. for k, v in pairs(opts.headers) do
  411. line = string.format("%s: %s\r\n", k, v)
  412. socket.tx(netc, line)
  413. end
  414. line = "\r\n"
  415. socket.tx(netc, line)
  416. -- 然后是body
  417. local rbody = ""
  418. local write_counter = 0
  419. if opts.mp and #opts.mp > 0 then
  420. opts.log(TAG, "执行mulitpart上传模式")
  421. for k, v in pairs(opts.mp) do
  422. socket.tx(netc, v[2])
  423. write_counter = write_counter + #v[2]
  424. if v[3] == "file" then
  425. -- log.info("写入文件数据头", v[2])
  426. local fd = io.open(v[1], "rb")
  427. -- log.info("写入文件数据", v[1])
  428. if fd then
  429. while not opts.is_closed do
  430. local fdata = fd:read(1400)
  431. if not fdata or #fdata == 0 then
  432. break
  433. end
  434. -- log.info("写入文件数据", "长度", #fdata)
  435. socket.tx(netc, fdata)
  436. write_counter = write_counter + #fdata
  437. -- 注意, 这里要等待TX_OK事件
  438. sys.waitUntil(opts.topic, 3000)
  439. end
  440. fd:close()
  441. end
  442. else
  443. socket.tx(netc, v[1])
  444. write_counter = write_counter + #v[1]
  445. end
  446. socket.tx(netc, "\r\n")
  447. write_counter = write_counter + 2
  448. end
  449. -- rbody = rbody .. "--" .. opts.boundary .. "--\r\n"
  450. socket.tx(netc, "--")
  451. socket.tx(netc, opts.boundary)
  452. socket.tx(netc, "--\r\n")
  453. write_counter = write_counter + #opts.boundary + 2 + 2 + 2
  454. elseif opts.bodyfile then
  455. local fd = io.open(opts.bodyfile, "rb")
  456. -- log.info("写入文件数据", v[1])
  457. if fd then
  458. while not opts.is_closed do
  459. local fdata = fd:read(1400)
  460. if not fdata or #fdata == 0 then
  461. break
  462. end
  463. -- log.info("写入文件数据", "长度", #fdata)
  464. socket.tx(netc, fdata)
  465. write_counter = write_counter + #fdata
  466. -- 注意, 这里要等待TX_OK事件
  467. sys.waitUntil(opts.topic, 300)
  468. end
  469. fd:close()
  470. end
  471. elseif opts.body then
  472. if type(opts.body) == "string" and #opts.body > 0 then
  473. socket.tx(netc, opts.body)
  474. write_counter = write_counter + #opts.body
  475. elseif type(opts.body) == "userdata" then
  476. write_counter = write_counter + opts.body:used()
  477. if opts.body:used() < 4*1024 then
  478. socket.tx(netc, opts.body)
  479. else
  480. local offset = 0
  481. local tmpbuff = opts.body
  482. local tsize = tmpbuff:used()
  483. while offset < tsize do
  484. opts.log(TAG, "body(zbuff)分段写入", offset, tsize)
  485. if tsize - offset > 4096 then
  486. socket.tx(netc, tmpbuff:toStr(offset, 4096))
  487. offset = offset + 4096
  488. sys.waitUntil(opts.topic, 300)
  489. else
  490. socket.tx(netc, tmpbuff:toStr(offset, tsize - offset))
  491. break
  492. end
  493. end
  494. end
  495. end
  496. end
  497. -- log.info("写入长度", "期望", opts.body_len, "实际", write_counter)
  498. -- log.info("hex", rbody)
  499. -- 处理响应信息
  500. while not opts.is_closed and opts.timeout > 0 do
  501. log.info(TAG, "等待服务器完成响应")
  502. sys.waitUntil(opts.topic, 1000)
  503. opts.timeout = opts.timeout - 1
  504. end
  505. log.info(TAG, "服务器已完成响应,开始解析响应")
  506. resp_parse(opts)
  507. -- log.info("执行完成", "返回结果")
  508. end
  509. --[[
  510. 执行HTTP请求
  511. @api httpplus.request(opts)
  512. @table 请求参数,是一个table,最起码得有url属性
  513. @return int 响应码,服务器返回的状态码>=100, 若本地检测到错误,会返回<0的值
  514. @return 服务器正常响应时返回结果, 否则是错误信息或者nil
  515. @usage
  516. -- 请求参数介绍
  517. local opts = {
  518. url = "https://httpbin.air32.cn/abc", -- 必选, 目标URL
  519. method = "POST", -- 可选,默认GET, 如果有body,files,forms参数,会设置成POST
  520. headers = {}, -- 可选,自定义的额外header
  521. files = {}, -- 可选,文件上传,若存在本参数,会强制以multipart/form-data形式上传
  522. forms = {}, -- 可选,表单参数,若存在本参数,如果不存在files,按application/x-www-form-urlencoded上传
  523. body = "abc=123",-- 可选,自定义body参数, 字符串/zbuff/table均可, 但不能与files和forms同时存在
  524. debug = false, -- 可选,打开调试日志,默认false
  525. try_ipv6 = false, -- 可选,是否优先尝试ipv6地址,默认是false
  526. adapter = nil, -- 可选,网络适配器编号, 默认是自动选
  527. timeout = 30, -- 可选,读取服务器响应的超时时间,单位秒,默认30
  528. bodyfile = "xxx" -- 可选,直接把文件内容作为body上传, 优先级高于body参数
  529. }
  530. local code, resp = httpplus.request({url="https://httpbin.air32.cn/get"})
  531. log.info("http", code)
  532. -- 返回值resp的说明
  533. -- 情况1, code >= 100 时, resp会是个table, 包含2个元素
  534. if code >= 100 then
  535. -- headers, 是个table
  536. log.info("http", "headers", json.encode(resp.headers))
  537. -- body, 是个zbuff
  538. -- 通过query函数可以转为lua的string
  539. log.info("http", "headers", resp.body:query())
  540. -- 也可以通过uart.tx等支持zbuff的函数转发出去
  541. -- uart.tx(1, resp.body)
  542. end
  543. ]]
  544. function httpplus.request(opts)
  545. -- 参数解析
  546. local ret = http_opts_parse(opts)
  547. if ret then
  548. return ret
  549. end
  550. -- 执行请求
  551. local ret, msg = pcall(http_exec, opts)
  552. if opts.netc then
  553. -- 清理连接
  554. if not opts.is_closed then
  555. socket.close(opts.netc)
  556. end
  557. socket.release(opts.netc)
  558. opts.netc = nil
  559. end
  560. -- 处理响应或错误
  561. if not ret then
  562. log.error(TAG, msg)
  563. return -199, msg
  564. end
  565. return opts.resp_code, opts.resp
  566. end
  567. return httpplus