forked from hffqyd/tw5-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseBody.nim
75 lines (66 loc) · 2.29 KB
/
parseBody.nim
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
import tables, strtabs
import strutils
import parseutils
type MultiData = OrderedTable[string, tuple[fields: StringTableRef, body: string]]
template parseContentDisposition() =
var hCount = 0
while hCount < hValue.len()-1:
var key = ""
hCount += hValue.parseUntil(key, {';', '='}, hCount)
if hValue[hCount] == '=':
var value = hvalue.captureBetween('"', start = hCount)
hCount += value.len+2
inc(hCount) # Skip ;
hCount += hValue.skipWhitespace(hCount)
if key == "name": c_name = value
newPart[0][key] = value
else:
inc(hCount)
hCount += hValue.skipWhitespace(hCount)
proc parseMultiPart(body: string, boundary: string): MultiData =
result = initOrderedTable[string, tuple[fields: StringTableRef, body: string]]()
var mboundary = "--" & boundary
var i = 0
var partsLeft = true
while partsLeft:
var firstBoundary = body.skip(mboundary, i)
if firstBoundary == 0:
raise newException(ValueError, "Expected boundary. Got: " & body.substr(i, i+25))
i += firstBoundary
i += body.skipWhitespace(i)
# Headers
var newPart: tuple[fields: StringTableRef, body: string] = ({:}.newStringTable, "")
var c_name = ""
while true:
if body[i] == '\c':
inc(i, 2) # Skip \c\L
break
var hName = ""
i += body.parseUntil(hName, ':', i)
if body[i] != ':':
raise newException(ValueError, "Expected : in headers.")
inc(i) # Skip :
i += body.skipWhitespace(i)
var hValue = ""
i += body.parseUntil(hValue, {'\c', '\L'}, i)
if toLowerAscii(hName) == "content-disposition":
parseContentDisposition()
newPart[0][hName] = hValue
i += body.skip("\c\L", i) # Skip *one* \c\L
# Parse body.
while true:
if body[i] == '\c' and body[i+1] == '\L' and
body.skip(mboundary, i+2) != 0:
if body.skip("--", i+2+mboundary.len) != 0:
partsLeft = false
break
break
else:
newPart[1].add(body[i])
inc(i)
i += body.skipWhitespace(i)
result[c_name] = newPart
proc parseMPFD*(contentType: string, body: string): MultiData =
var boundaryEqIndex = contentType.find("boundary=")+9
var boundary = contentType.substr(boundaryEqIndex, contentType.len()-1)
return parseMultiPart(body, boundary)