-
Notifications
You must be signed in to change notification settings - Fork 2
/
body_parser.swift
854 lines (771 loc) · 19.5 KB
/
body_parser.swift
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
public struct BodyFile {
public var name = ""
public var contentType = ""
public var file: File
// Handy method that can both rename and move the file to a new directory.
public func rename(path: String) throws {
try File.rename(oldPath: file.path, newPath: path)
}
}
public struct Body {
public var fields = [String: String]()
public var files = [String: BodyFile]()
public subscript(key: String) -> String? {
get { return fields[key] ?? nil }
set { fields[key] = newValue }
}
}
// DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_"
// / "," / "-" / "." / "/" / ":" / "=" / "?"
struct BoundaryCharTable {
let table: [Bool]
init() {
var t = [Bool](repeating: false, count: 256)
for i in 65..<91 { // A-Z
t[i] = true
}
for i in 97..<123 { // a-z
t[i] = true
}
for i in 48..<58 { // 0-9
t[i] = true
}
t[39] = true // '
t[40] = true // (
t[41] = true // )
t[43] = true // +
t[44] = true // ,
t[45] = true // -
t[46] = true // .
t[47] = true // /
t[58] = true // :
t[61] = true // =
t[63] = true // ?
t[95] = true // _
table = t
}
subscript(key: UInt8) -> Bool { return table[Int(key)] }
static let TABLE = BoundaryCharTable()
}
struct BodyTokenMatcher {
let bytes: [UInt8]
init(string: String) {
bytes = [UInt8](string.utf8)
}
init(bytes: [UInt8]) {
self.bytes = bytes
}
subscript(index: Int) -> UInt8 { return bytes[index] }
func match(index: Int, c: UInt8) -> Bool {
return bytes[index] == c
}
var count: Int { return bytes.count }
static let CONTENT_DISPOSITION = BodyTokenMatcher(
string: "Content-Disposition")
static let NAME = BodyTokenMatcher(string: "name")
static let FILENAME = BodyTokenMatcher(string: "filename")
static let CONTENT_TYPE = BodyTokenMatcher(string: "Content-Type")
static let FORM_DATA = BodyTokenMatcher(string: "form-data")
static let _EMPTY = BodyTokenMatcher(string: "")
}
enum BodyParserEntry {
case Body
case BodyStarted
case Key
case NextKey
case KeyStarted
case Colon
case Value
case ValueStarted
case Space
case LineFeed
case BeginMultipart
case BeginMultipartStarted
case MatchToken
case ContentDisposition
case ContentDispositionEnd
case FormData
case FormDataEnd
case Name
case NameEnd
case NameValue
case NameValueStarted
case NameValueEnd
case FileName
case FileNameEnd
case FileNameValue
case FileNameValueStarted
case FileNameValueEnd
case ContentType
case ContentTypeEnd
case ContentTypeValue
case ContentTypeValueStarted
case ContentValue
case ContentBody
case ContentBodyStarted
case ContentData
case ContentDataStarted
case ContentFile
case ContentFileStarted
}
// Supports streaming.
public struct BodyParser {
var stream = [UInt8]()
var entryParser: BodyParserEntry = .Body
public var body = Body()
var index = 0
var length = 0
var linedUpParser: BodyParserEntry = .Body
var tokenIndex = -1
var keyToken = ""
var tokenBuffer = [UInt8](repeating: 0, count: 1024)
var tokenBufferEnd = 0
var done = false
var boundary = BodyTokenMatcher._EMPTY
var shadowMatch = BodyTokenMatcher._EMPTY
var nameValue = ""
var fileNameValue = ""
var contentTypeValue = ""
var boundaryMatch = [Int]()
var boundTest1 = false // Match for the boundary token without line ending.
var boundTest2 = false // Match for the boundary token plus first - suffix.
var boundTest3 = false // Match for the boundary token plus -- suffix.
var tempFile: TempFile?
public init() { }
public var isDone: Bool { return done }
mutating func addToTokenBuffer(a: [UInt8], startIndex: Int, endIndex: Int) {
let tbe = tokenBufferEnd
let blen = tokenBuffer.count
let ne = tbe + (endIndex - startIndex)
if ne >= blen {
var c = [UInt8](repeating: 0, count: ne * 2)
for i in 0..<tbe {
c[i] = tokenBuffer[i]
}
tokenBuffer = c
}
var j = tbe
for i in startIndex..<endIndex {
tokenBuffer[j] = a[i]
j += 1
}
tokenBufferEnd = j
}
mutating func next() throws {
switch entryParser {
case .Body:
try inBody()
case .BodyStarted:
try inBodyStarted()
case .NextKey:
try inNextKey()
case .KeyStarted:
try inKeyStarted()
case .Value:
try inValue()
case .ValueStarted:
try inValueStarted()
case .BeginMultipart:
try inBeginMultipart()
case .BeginMultipartStarted:
try inBeginMultipartStarted()
case .ContentDisposition:
try inContentDisposition()
case .ContentDispositionEnd:
try inContentDispositionEnd()
case .LineFeed:
try inLineFeed()
case .MatchToken:
try inMatchToken()
case .Space:
try inSpace()
case .FormData:
try inFormData()
case .FormDataEnd:
try inFormDataEnd()
case .Name:
try inName()
case .NameEnd:
try inNameEnd()
case .NameValue:
try inNameValue()
case .NameValueStarted:
try inNameValueStarted()
case .NameValueEnd:
try inNameValueEnd()
case .FileName:
try inFileName()
case .FileNameEnd:
try inFileNameEnd()
case .FileNameValue:
try inFileNameValue()
case .FileNameValueStarted:
try inFileNameValueStarted()
case .FileNameValueEnd:
try inFileNameValueEnd()
case .ContentType:
try inContentType()
case .ContentTypeEnd:
try inContentTypeEnd()
case .ContentTypeValue:
try inContentTypeValue()
case .ContentTypeValueStarted:
try inContentTypeValueStarted()
case .ContentBody:
try inContentBody()
case .ContentBodyStarted:
try inContentBodyStarted()
case .ContentData:
try inContentData()
case .ContentDataStarted:
try inContentDataStarted()
default: throw BodyParserError.ContentBody
}
}
mutating public func parse(bytes: [UInt8], index si: Int = 0,
maxBytes: Int = -1) throws {
stream = bytes
index = si
length = maxBytes < 0 ? bytes.count : maxBytes
while index < length {
try next()
}
if tokenIndex >= 0 {
addToTokenBuffer(a: stream, startIndex: tokenIndex, endIndex: length)
tokenIndex = 0 // Set it at 0 to continue supporting addToTokenBuffer.
if let tf = tempFile {
if tokenBufferEnd >= 4096 {
let len = tokenBufferEnd - 80
let _ = tf.writeBytes(bytes: tokenBuffer, maxBytes: len)
for i in 0..<80 {
tokenBuffer[i] = tokenBuffer[len + i]
}
tokenBufferEnd = 80
}
}
}
}
mutating func collectToken(endIndex: Int) -> [UInt8] {
var a: [UInt8]?
if tokenBufferEnd > 0 {
addToTokenBuffer(a: stream, startIndex: tokenIndex, endIndex: endIndex)
a = [UInt8](tokenBuffer[0..<tokenBufferEnd])
tokenBufferEnd = 0
} else {
a = [UInt8](stream[tokenIndex..<endIndex])
}
index = endIndex + 1
tokenIndex = -1
return a!
}
mutating func collectString(endIndex: Int) -> String? {
return String.fromCharCodes(charCodes: collectToken(endIndex: endIndex))
}
mutating func collectFormUrlDecodedString(endIndex: Int) -> String? {
let a = collectToken(endIndex: endIndex)
if let b = HexaUtils.formUrlDecode(bytes: a, maxBytes: a.count) {
return String.fromCharCodes(charCodes: b)
}
return nil
}
mutating func inBody() throws {
let i = index
let c = stream[i]
if c == 45 { // -
entryParser = .BeginMultipart
tokenIndex = i
index = i + 1
} else if c >= 32 && c != 61 { // Some character, but not "=".
entryParser = .KeyStarted
tokenIndex = i
index = i + 1
} else {
throw BodyParserError.Body
}
}
mutating func inBodyStarted() throws {
throw BodyParserError.Body
}
mutating func inBeginMultipart() throws {
let i = index
if stream[i] == 45 { // -
entryParser = .BeginMultipartStarted
tokenIndex = i
index = i + 1
} else {
entryParser = .KeyStarted
}
}
mutating func inBeginMultipartStarted() throws {
var i = index
let len = length
repeat {
let c = stream[i]
if BoundaryCharTable.TABLE[c] {
// Ignore.
} else if c == 13 {
boundary = BodyTokenMatcher(bytes: collectToken(endIndex: i))
if boundary.count <= 2 {
throw BodyParserError.Key
}
entryParser = .LineFeed
linedUpParser = .ContentDisposition
break
} else {
throw BodyParserError.BeginMultipart
}
i += 1
} while i < len
if i >= len {
index = i
}
}
mutating func inNextKey() throws {
let i = index
let c = stream[i]
if c == 61 { // =
throw HeaderParserError.Key
} else if c >= 32 {
tokenIndex = i
index = i + 1
entryParser = .KeyStarted
} else {
throw HeaderParserError.Key
}
}
mutating func inKeyStarted() throws {
var i = index
let len = length
func process() throws {
if let k = collectFormUrlDecodedString(endIndex: i) {
keyToken = k
} else {
throw BodyParserError.Key
}
}
repeat {
let c = stream[i]
if c == 61 { // =
entryParser = .Value
try process()
break
} else if c >= 32 {
// ignore
} else {
throw BodyParserError.Key
}
i += 1
} while i < len
if i >= len {
index = i
}
}
mutating func inValue() throws {
let i = index
if stream[i] == 38 { // &
entryParser = .NextKey
body[keyToken] = ""
index = i + 1
} else if stream[i] >= 32 {
tokenIndex = i
index = i + 1
entryParser = .ValueStarted
} else if stream[i] == 0 {
body[keyToken] = ""
done = true
index = length // Done. Exit.
} else {
throw BodyParserError.Value
}
}
mutating func inValueStarted() throws {
var i = index
let len = length
repeat {
let c = stream[i]
if c == 38 { // &
entryParser = .NextKey
body[keyToken] = collectFormUrlDecodedString(endIndex: i)
break
} else if c >= 32 {
// ignore
} else if c == 0 {
body[keyToken] = collectFormUrlDecodedString(endIndex: i)
done = true
index = length // Done. Exit.
break
} else {
throw BodyParserError.Value
}
i += 1
} while i < len
if i >= len {
index = i
}
}
mutating func inLineFeed() throws {
if stream[index] == 10 { // \n
index += 1
entryParser = linedUpParser
} else {
throw BodyParserError.LineFeed
}
}
mutating func inContentDisposition() throws {
shadowMatch = BodyTokenMatcher.CONTENT_DISPOSITION
entryParser = .MatchToken
linedUpParser = .ContentDispositionEnd
tokenIndex = index
}
mutating func inContentDispositionEnd() throws {
if stream[index] == 58 { // :
index += 1
entryParser = .Space
linedUpParser = .FormData
} else {
throw BodyParserError.ContentDisposition
}
}
mutating func inFormData() throws {
shadowMatch = BodyTokenMatcher.FORM_DATA
entryParser = .MatchToken
linedUpParser = .FormDataEnd
tokenIndex = index
try inMatchToken()
}
mutating func inFormDataEnd() throws {
if stream[index] == 59 { // ;
index += 1
entryParser = .Space
linedUpParser = .Name
} else {
throw BodyParserError.FormData
}
}
mutating func inName() throws {
shadowMatch = BodyTokenMatcher.NAME
entryParser = .MatchToken
linedUpParser = .NameEnd
tokenIndex = index
try inMatchToken()
}
mutating func inNameEnd() throws {
if stream[index] == 61 { // =
index += 1
entryParser = .NameValue
} else {
throw BodyParserError.Name
}
}
mutating func inNameValue() throws {
if stream[index] == 34 { // "
index += 1
nameValue = ""
entryParser = .NameValueStarted
tokenIndex = index
} else {
throw BodyParserError.NameValue
}
}
mutating func inNameValueStarted() throws {
var i = index
let len = length
repeat {
let c = stream[i]
if c == 34 { // "
if let s = collectString(endIndex: i) {
nameValue = s
} else {
throw BodyParserError.NameValue
}
entryParser = .NameValueEnd
index = i + 1
break
} else if c >= 32 { // Space.
// ignore
} else {
throw BodyParserError.NameValue
}
i += 1
} while i < len
if i >= len {
index = i
}
}
mutating func inNameValueEnd() throws {
if stream[index] == 59 { // ;
index += 1
entryParser = .Space
linedUpParser = .FileName
} else if stream[index] == 13 { // Carriage return.
entryParser = .ContentBody
index += 1
} else {
throw BodyParserError.NameValue
}
}
mutating func inFileName() throws {
shadowMatch = BodyTokenMatcher.FILENAME
entryParser = .MatchToken
linedUpParser = .FileNameEnd
tokenIndex = index
try inMatchToken()
}
mutating func inFileNameEnd() throws {
if stream[index] == 61 { // =
index += 1
entryParser = .FileNameValue
} else {
throw BodyParserError.FileName
}
}
mutating func inFileNameValue() throws {
if stream[index] == 34 { // "
index += 1
tokenIndex = index
fileNameValue = ""
entryParser = .FileNameValueStarted
} else {
throw BodyParserError.FileNameValue
}
}
mutating func inFileNameValueStarted() throws {
var i = index
let len = length
repeat {
let c = stream[i]
if c == 34 { // "
if let s = collectString(endIndex: i) {
fileNameValue = s
} else {
throw BodyParserError.FileNameValue
}
entryParser = .FileNameValueEnd
index = i + 1
break
} else if c >= 32 { // Space.
// ignore
} else {
throw BodyParserError.FileNameValue
}
i += 1
} while i < len
if i >= len {
index = i
}
}
mutating func inFileNameValueEnd() throws {
if stream[index] == 13 { // Carriage return.
entryParser = .LineFeed
linedUpParser = .ContentType
index += 1
} else {
throw BodyParserError.FileNameValue
}
}
mutating func inContentType() throws {
shadowMatch = BodyTokenMatcher.CONTENT_TYPE
entryParser = .MatchToken
linedUpParser = .ContentTypeEnd
tokenIndex = index
try inMatchToken()
}
mutating func inContentTypeEnd() throws {
if stream[index] == 58 { // :
index += 1
entryParser = .Space
linedUpParser = .ContentTypeValue
} else {
throw BodyParserError.ContentDisposition
}
}
mutating func inContentTypeValue() throws {
if stream[index] > 32 {
tokenIndex = index
contentTypeValue = ""
index += 1
entryParser = .ContentTypeValueStarted
} else {
throw BodyParserError.ContentTypeValue
}
}
mutating func inContentTypeValueStarted() throws {
var i = index
let len = length
repeat {
let c = stream[i]
if c == 13 {
if let s = collectString(endIndex: i) {
contentTypeValue = s
} else {
throw BodyParserError.FileNameValue
}
entryParser = .ContentBody
index = i + 1
break
} else if c > 32 { // Space.
// ignore
} else {
throw BodyParserError.ContentTypeValue
}
i += 1
} while i < len
if i >= len {
index = i
}
}
mutating func inMatchToken() throws {
var i = index
let len = length
let shadowLasti = shadowMatch.count - 1
repeat {
let ci = i - tokenIndex
if stream[i] == shadowMatch[tokenBufferEnd + ci] {
if ci == shadowLasti {
entryParser = linedUpParser
index = i + 1
tokenIndex = -1
break
}
} else {
throw BodyParserError.MatchToken
}
i += 1
} while i < len
if i >= len {
index = i
}
}
mutating func inContentBody() throws {
if stream[index] == 10 {
index += 1
entryParser = .ContentBodyStarted
} else {
throw BodyParserError.ContentBody
}
}
mutating func inContentBodyStarted() throws {
if stream[index] == 13 {
index += 1
entryParser = .LineFeed
linedUpParser = .ContentData
} else {
throw BodyParserError.ContentBody
}
}
mutating func inContentData() throws {
tokenIndex = index
entryParser = .ContentDataStarted
boundaryMatch = []
boundTest1 = false
boundTest2 = false
boundTest3 = false
if !fileNameValue.isEmpty || !contentTypeValue.isEmpty {
tempFile = try TempFile(prefix: "bodyparser", suffix: "upload")
}
}
mutating func storeFile(endIndex: Int) {
let bb = collectToken(endIndex: endIndex)
let _ = tempFile!.writeBytes(bytes: bb, maxBytes: bb.count)
if let oldFile = body.files[nameValue] {
(oldFile.file as! TempFile).closeAndUnlink()
}
body.files[nameValue] = BodyFile(name: fileNameValue,
contentType: contentTypeValue, file: tempFile!)
tempFile = nil
}
mutating func inContentDataStarted() throws {
var i = index
let len = length
let blasti = boundary.count - 1
repeat {
let c = stream[i]
if boundTest3 && c == 13 {
let ei = i - boundary.count - 5
if tempFile != nil {
storeFile(endIndex: ei)
} else {
body.fields[nameValue] = collectString(endIndex: ei)
}
index = length // Body exit.
done = true
break
}
boundTest3 = false
if boundTest2 && c == 45 {
boundTest3 = true
}
boundTest2 = false
if boundTest1 {
if c == 13 {
let ei = i - boundary.count - 3
if tempFile != nil {
storeFile(endIndex: ei)
} else {
body.fields[nameValue] = collectString(endIndex: ei)
}
entryParser = .LineFeed
linedUpParser = .ContentDisposition
index = i + 1
break
} else if c == 45 {
boundTest2 = true
}
}
boundTest1 = false
if BoundaryCharTable.TABLE[c] {
var a = [Int]()
for j in 0..<boundaryMatch.count {
let m = boundaryMatch[j]
if boundary.match(index: m, c: c) {
if m == blasti {
boundTest1 = true
} else {
a.append(m + 1)
}
}
}
if c == 45 {
a.append(1)
}
boundaryMatch = a
}
i += 1
} while i < len
if i >= len {
index = i
}
}
mutating func inSpace() throws {
while index < length && stream[index] == 32 {
index += 1
}
entryParser = linedUpParser
}
// Call this to help remove the temp files.
//
// When BodyParser is used from a main file, outside functions, temp files
// could persist after the program has finished running.
mutating func close() {
for (_, bf) in body.files {
(bf.file as! TempFile).closeAndUnlink()
}
}
}
enum BodyParserError: ErrorProtocol {
case Body
case Key
case Value
case BeginMultipart
case MatchToken
case ContentDisposition
case LineFeed
case FormData
case Name
case NameValue
case FileName
case FileNameValue
case ContentBody
case ContentTypeValue
case Unreachable
}