-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-lcurl.lua
More file actions
439 lines (401 loc) · 14.2 KB
/
http-lcurl.lua
File metadata and controls
439 lines (401 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
---@class http-lcurl
local lib = {}
---return file info; for embedded purposes
---@private
function lib:INFO(_)
local info = {}
for k in pairs(self) do table.insert(info, k) end
return {
version = {
major = 0,
minor = 1,
revision = 3,
},
library = {
modulename = "http-lcurl"
},
dependencies = {
"lua-curl",
"rapidjson",
"xml2lua"
},
functions = info
}
end
local LCURL = require('lcurl')
local JSON = require('rapidjson')
--optionally include xml2lua
local function safe_require(module)
local ok, mod = pcall(require, module)
return ok and mod or nil
end
local XML = safe_require('xml2lua') or safe_require('lua.modules.xml2lua')
local HANDLER = safe_require('xmlhandler.tree') or safe_require('lua.modules.xmlhandler_tree')
local DEFAULT_HEADERS = {
["Content-Type"] = "application/json",
["Accept"] = "application/json",
["User-Agent"] = "Lua-cURLv3",
}
---enumerator of applicable methods
---@enum http-lcurl.METHOD
lib.METHOD = {
GET = "GET",
POST = "POST",
PUT = "PUT",
PATCH = "PATCH",
DELETE = "DELETE",
HEAD = "HEAD",
OPTIONS = "OPTIONS"
}
---@enum http-lcurl.CONTENT_TYPE
lib.CONTENT_TYPE = {
FORM = "application/x-www-form-urlencoded",
HTML = "text/html",
JSON = "application/json",
MULTIPART = "multipart/form-data",
TEXT = "text/plain",
XML = "application/xml"
}
---do bounds checks of input arguments
---@private
---@alias http-lcurl.arguments {url:string,headers?:table,body?:table|string,options?:table|string}
---@param t http-lcurl.arguments
---@return http-lcurl.arguments
local function parseArguments(t)
if type(t) ~= "table" then
error("insufficient arguments")
end
local ret = {}
--assert url
assert(t.url, "URL was not provided.")
assert(type(t.url) == "string", "URL must be of type string.")
assert(t.url ~= "", "URL can not be blank.")
ret.url = t.url
--check optionals: headers, body, options
local optionals = {"headers", "body", "options"}
for _,option in ipairs(optionals) do
if (t[option] ~= nil) then
if (option == "body" and type(t[option] == "string")) then
--skip this assert
else
assert(type(t[option]) == "table")
end
end
ret[option] = t[option] or {}
end
return ret
end
---main function
---@alias http-lcurl.success {code:number,success:boolean,url:string,data:table|string,headers:table}
---@param method http-lcurl.METHOD
---@param t http-lcurl.arguments
---@return http-lcurl.success|http-lcurl.error
local function request(method, t)
--sanitize inputs
local args = parseArguments(t)
local url = args.url
local request_headers = {}
local body = args["body"]
local options = args["options"] or {}
--copy headers over
for k,v in pairs(args["headers"]) do
request_headers[k] = v
end
--merge headers with defaults
for k,v in pairs(DEFAULT_HEADERS) do
if request_headers[k] == nil then
request_headers[k] = v
end
end
--[[
ssl_verifypeer refers to if the host has a valid CA SSL cert
--]]
local result_body = {}
local result_headers = {}
local INIT = {
url = url,
ssl_verifypeer = options.ssl_verifypeer or false,
verbose = options.verbose or 0,
timeout = options.timeout or 5,
followlocation = (options.followlocation == nil and true) or options.followlocation,
maxredirs = options.maxredirs or 5,
writefunction = function(data)
if data and type(data) == "string" then
table.insert(result_body, data)
end
end,
headerfunction = function(header_line)
if not header_line or type(header_line) ~= "string" then
return
end
--remove whitespaces
local clean_header = header_line:gsub("%s+$", "")
if clean_header ~= "" then
--parse headers
local header_k, header_v = clean_header:match("^([^:]+):%s*(.*)$")
if header_k and header_v then
-- Normalize header names to lowercase for consistency
header_k = header_k:lower():gsub("^%s+", ""):gsub("%s+$", "")
header_v = header_v:gsub("^%s+", ""):gsub("%s+$", "")
if header_k ~= "" then
-- Handle multiple headers with same name (like Set-Cookie)
if result_headers[header_k] then
if type(result_headers[header_k]) == "table" then
table.insert(result_headers[header_k], header_v)
else
result_headers[header_k] = {result_headers[header_k], header_v}
end
else
result_headers[header_k] = header_v
end
end
end
end
end
}
--Check for TLS
if url:match("^https://") then
INIT.ssl_verifyhost = options.ssl_verifyhost or 2 -- Verify hostname matches cert
if options.cainfo then
INIT.cainfo = options.cainfo -- Custom CA bundle path
end
end
--init curl request
local easy = LCURL.easy(INIT)
if not easy then error("Failed to initialize cURL: "..tostring(error)) end
--handle request_body
local request_body
if options.files or request_headers["Content-Type"] == lib.CONTENT_TYPE.FORM then
local form = LCURL.form()
--if options has files, verify has .name and .path
if options.files then
for _,file in pairs(options.files) do
assert(file.name, "file needs property 'name'")
assert(file.path, "file needs property 'path'")
file.type = file["type"] or lib.CONTENT_TYPE.TEXT
form:add_file(file.name, file.path, file.type)
end
end
--if body is populated
if body and request_headers["Content-Type"] == lib.CONTENT_TYPE.FORM then
local form_data = {}
if type(body) == "string" then
form_data = JSON.decode(body) or {}
if next(form_data) == nil then
--decode by & and =
for pair in body:gmatch("[^&]+") do
local function decode_url(str)
--replaces '+' with spaces & converts hex values to chars
return str:gsub("+", " "):gsub("%%(%x%x)", function(hex)
return string.char(tonumber(hex, 16))
end)
end
local key, value = pair:match("^([^=]+)=(.*)$")
if key then
key = decode_url(key) or ""
value = decode_url(value)
form_data[key] = value
else
-- Handle case where there's no = (just a key)
local decoded_key = decode_url(pair) or ""
form_data[decoded_key] = ""
end
end
end
elseif type(body) == "table" then
if next(body) ~= nil then form_data = body end
end
for k,v in pairs(form_data) do
form:add_content(k, tostring(v))
end
end
request_body = ""
easy:setopt_httppost(form)
request_headers["Content-Type"] = nil
elseif type(body) == "string" then
request_body = body
else --default and JSON
if body then
if next(body) ~= nil then
request_body = JSON.encode(body)
else
if type(body) == "table" then
request_body = ""
else
request_body = tostring(body)
end
end
end
end
--if username and password, make Basic Auth Token
if (request_headers["username"] and request_headers["password"] and options.ignoreBasicAuth == nil) then
if options.digestAuth then easy:setopt_httpauth(LCURL.AUTH_DIGEST) end
if options.NTLMAuth then easy:setopt_httpauth(LCURL.AUTH_NTLM) end
if options.negotiateAuth then easy:setopt_httpauth(LCURL.AUTH_NEGOTIATE) end
easy:setopt_userpwd(request_headers["username"]..":"..request_headers["password"])
request_headers["username"] = nil
request_headers["password"] = nil
end
--set request type
easy:setopt_customrequest(method)
if method == lib.METHOD.HEAD then easy:setopt_nobody(true) end
--[[
proxy options:
-> proxy is the url of the proxy
-> setopt_proxyuserpwd sets the header [Proxy-Authorization]: Basic base64
-> proxyCred and either be "username:password" or {username="",password=""}
--]]
if options["proxy"] then --url of proxy
easy:setopt_proxy(options.proxy)
if options.proxyCred then
if type(options.proxyCred) == "string" then
easy:setopt_proxyuserpwd(options.proxyCred)
elseif type(options.proxyCred) == "table" then
easy:setopt_proxyuserpwd(options.proxyCred.username..":"..options.proxyCred.password)
else
error("not acceptable proxy options")
end
end
end
--handle post body
local body_length = string.len(request_body)
if (method ~= lib.METHOD.GET and body_length > 0) then
easy:setopt_postfields(request_body)
request_headers["Content-Length"] = body_length
end
--cast headers as string
local httpheader = {}
for k,v in pairs(request_headers) do
table.insert(httpheader, string.format("%s: %s", k, v))
end
easy:setopt_httpheader(httpheader)
--make the request
local ok, err = easy:perform()
if not(ok) then
return "Error: "..err
end
local code = easy:getinfo_response_code()
local effective_url = easy:getinfo_effective_url()
easy:close()
local data
if result_body ~= nil then
if type(result_body) == "table" then --usually returns array
data = table.concat(result_body) --take first element
if data ~= "" then
-- check for redirects
local content_type
if type(result_headers["content-type"]) == "table" then
content_type = result_headers["content-type"][#result_headers["content-type"]] or ""
else
content_type = result_headers["content-type"] or ""
end
--if result_headers["Content-Encoding"] then end --*check if there is encoding?
if content_type:lower():find(lib.CONTENT_TYPE.JSON) then
data = JSON.decode(data) or data
elseif content_type:lower():find(lib.CONTENT_TYPE.XML) then
--if xml2lua is found, then try to use it. Else return as string
if XML and HANDLER then
local tree_handler = HANDLER:new()
local xml_parser = XML.parser(tree_handler)
xml_parser:parse(data)
data = tree_handler.root
else
data = data
end
end
end
else
data = result_body
end
end
--wrap up finish
return {
code = code or 0,
success = code >= 200 and code < 300,
url = effective_url,
data = data,
headers = result_headers
}
end
---@class http-lcurl.CurlError
---@field no fun(self): number
---@field msg fun(self): string
---@field __tostring fun(self): string
---@private
---@alias http-lcurl.error {success:boolean,code:number,msg:string}
---@param err http-lcurl.CurlError|string
---@return http-lcurl.error
local function retError(err)
local code, msg
if type(err) == "userdata" then
---@cast err http-lcurl.CurlError
code = err:no()
msg = err:msg() or err:__tostring()
else
---@cast err string
code = 0
msg = tostring(err)
end
return {
success = false,
code = code,
msg = msg
}
end
---HTTP GET Request
---@param args http-lcurl.arguments
---@return http-lcurl.success|http-lcurl.error
function lib:GET(args)
local ok, res = pcall(request, self.METHOD.GET, args)
if not(ok) then return retError(res) end
return res
end
---HTTP PUT Request
---@param args http-lcurl.arguments
---@return http-lcurl.success|http-lcurl.error
function lib:PUT(args)
local ok, res = pcall(request, self.METHOD.PUT, args)
if not(ok) then return retError(res) end
return res
end
---HTTP POST Request
---@param args http-lcurl.arguments
---@return http-lcurl.success|http-lcurl.error
function lib:POST(args)
local ok, res = pcall(request, self.METHOD.POST, args)
if not(ok) then return retError(res) end
return res
end
---HTTP PATCH Request
---@param args http-lcurl.arguments
---@return http-lcurl.success|http-lcurl.error
function lib:PATCH(args)
local ok, res = pcall(request, self.METHOD.PATCH, args)
if not(ok) then return retError(res) end
return res
end
---HTTP DELETE Request
---@param args http-lcurl.arguments
---@return http-lcurl.success|http-lcurl.error
function lib:DELETE(args)
local ok, res = pcall(request, self.METHOD.DELETE, args)
if not(ok) then return retError(res) end
return res
end
---HTTP HEAD Request
---@param args http-lcurl.arguments
---@return http-lcurl.success|http-lcurl.error
function lib:HEAD(args)
local ok, res = pcall(request, self.METHOD.HEAD, args)
if not(ok) then return retError(res) end
return res
end
---HTTP OPTIONS Request
---@param args http-lcurl.arguments
---@return http-lcurl.success|http-lcurl.error
function lib:OPTIONS(args)
local ok, res = pcall(request, self.METHOD.OPTIONS, args)
if not(ok) then return retError(res) end
return res
end
return lib