forked from PerfectlySoft/Perfect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMimeReader.swift
444 lines (365 loc) · 12.4 KB
/
MimeReader.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
//
// MimeReader.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/6/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
#if os(Linux)
import SwiftGlibc
import LinuxBridge
let S_IRUSR = __S_IREAD
let S_IROTH = (S_IRGRP >> 3)
let S_IWOTH = (S_IWGRP >> 3)
#else
import Darwin
#endif
enum MimeReadState {
case StateNone
case StateBoundary // next thing to be read will be a boundry
case StateHeader // read header lines until data starts
case StateFieldValue // read a simple value; name has already been set
case StateFile // read file data until boundry
case StateDone
}
let kMultiPartForm = "multipart/form-data"
let kBoundary = "boundary"
let kContentDisposition = "Content-Disposition"
let kContentType = "Content-Type"
let kPerfectTempPrefix = "perfect_upload_"
let mime_cr = UInt8(13)
let mime_lf = UInt8(10)
let mime_dash = UInt8(45)
/// This class is responsible for reading multi-part POST form data, including handling file uploads.
/// Data can be given for parsing in little bits at a time by calling the `addTobuffer` function.
/// Any file uploads which are encountered will be written to the temporary directory indicated when the `MimeReader` is created.
/// Temporary files will be deleted when this object is deinitialized.
public class MimeReader {
/// Array of BodySpecs representing each part that was parsed.
public var bodySpecs = [BodySpec]()
var maxFileSize = -1
var (multi, gotFile) = (false, false)
var buffer = [UInt8]()
let tempDirectory: String
var state: MimeReadState = .StateNone
/// The boundary identifier.
public var boundary = ""
/// This class represents a single part of a multi-part POST submission
public class BodySpec {
/// The name of the form field.
public var fieldName = ""
/// The value for the form field.
/// Having a fieldValue and a file are mutually exclusive.
public var fieldValue = ""
var fieldValueTempBytes: [UInt8]?
/// The content-type for the form part.
public var contentType = ""
/// The client-side file name as submitted by the form.
public var fileName = ""
/// The size of the file which was submitted.
public var fileSize = 0
/// The name of the temporary file which stores the file upload on the server-side.
public var tmpFileName = ""
/// The File object for the local temporary file.
public var file: File?
init() {
}
/// Clean up the BodySpec, possibly closing and deleting any associated temporary file.
public func cleanup() {
if let f = self.file {
if f.exists() {
f.delete()
}
self.file = nil
}
}
deinit {
self.cleanup()
}
}
/// Initialize given a Content-type header line.
/// - parameter contentType: The Content-type header line.
/// - parameter tempDir: The path to the directory in which to store temporary files. Defaults to "/tmp/".
public init(_ contentType: String, tempDir: String = "/tmp/") {
self.tempDirectory = tempDir
if contentType.rangeOf(kMultiPartForm) != nil {
self.multi = true
if let range = contentType.rangeOf(kBoundary) {
var startIndex = range.startIndex.successor()
for _ in 1...kBoundary.characters.count {
startIndex = startIndex.successor()
}
let endIndex = contentType.endIndex
let boundaryString = contentType.substringWith(Range(start: startIndex, end: endIndex))
self.boundary.appendContentsOf("--")
self.boundary.appendContentsOf(boundaryString)
self.state = .StateBoundary
}
}
}
// not implimented
// public func setMaxFileSize(size: Int) {
// self.maxFileSize = size
// }
func openTempFile(spec: BodySpec) {
spec.file = File(tempFilePrefix: self.tempDirectory + kPerfectTempPrefix)
spec.tmpFileName = spec.file!.path()
}
func isBoundaryStart(bytes: [UInt8], start: Array<UInt8>.Index) -> Bool {
var gen = self.boundary.utf8.generate()
var pos = start
var next = gen.next()
while let char = next {
if pos == bytes.endIndex || char != bytes[pos] {
return false
}
pos = pos.successor()
next = gen.next()
}
return next == nil // got to the end is success
}
func isField(name: String, bytes: [UInt8], start: Array<UInt8>.Index) -> Array<UInt8>.Index {
var check = start
let end = bytes.endIndex
var gen = name.utf8.generate()
while check != end {
if bytes[check] == 58 { // :
return check
}
let gened = gen.next()
if gened == nil {
break
}
if tolower(Int32(gened!)) != tolower(Int32(bytes[check])) {
break
}
check = check.successor()
}
return end
}
func pullValue(name: String, from: String) -> String {
var accum = ""
if let nameRange = from.rangeOf(name + "=", ignoreCase: true) {
var start = nameRange.endIndex
let end = from.endIndex
if from[start] == "\"" {
start = start.successor()
}
while start < end {
if from[start] == "\"" || from[start] == ";" {
break;
}
accum.append(from[start])
start = start.successor()
}
}
return accum
}
func internalAddToBuffer(bytes: [UInt8]) -> MimeReadState {
var clearBuffer = true
var position = bytes.startIndex
let end = bytes.endIndex
while position != end {
switch self.state {
case .StateDone, .StateNone:
return .StateNone
case .StateBoundary:
if position.distanceTo(end) < self.boundary.characters.count + 2 {
self.buffer = Array(bytes[position..<end])
clearBuffer = false
position = end
} else {
position = position.advancedBy(self.boundary.characters.count)
if bytes[position] == mime_dash && bytes[position.successor()] == mime_dash {
self.state = .StateDone
position = position.advancedBy(2)
} else {
self.state = .StateHeader
self.bodySpecs.append(BodySpec())
}
if self.state != .StateDone {
position = position.advancedBy(2) // line end
} else {
position = end
}
}
case .StateHeader:
var eolPos = position
while eolPos.distanceTo(end) > 1 {
let b1 = bytes[eolPos]
let b2 = bytes[eolPos.successor()]
if b1 == mime_cr && b2 == mime_lf {
break
}
eolPos = eolPos.successor()
}
if eolPos.distanceTo(end) <= 1 { // no eol
self.buffer = Array(bytes[position..<end])
clearBuffer = false
position = end
} else {
let spec = self.bodySpecs.last!
if eolPos != position {
let check = isField(kContentDisposition, bytes: bytes, start: position)
if check != end { // yes, content-disposition
let line = UTF8Encoding.encode(bytes[check.advancedBy(2)..<eolPos])
let name = pullValue("name", from: line)
let fileName = pullValue("filename", from: line)
spec.fieldName = name
spec.fileName = fileName
} else {
let check = isField(kContentType, bytes: bytes, start: position)
if check != end { // yes, content-type
spec.contentType = UTF8Encoding.encode(bytes[check.advancedBy(2)..<eolPos])
}
}
position = eolPos.advancedBy(2)
}
if (eolPos == position || position != end) && position.distanceTo(end) > 1 && bytes[position] == mime_cr && bytes[position.successor()] == mime_lf {
position = position.advancedBy(2)
if spec.fileName.characters.count > 0 {
openTempFile(spec)
self.state = .StateFile
} else {
self.state = .StateFieldValue
spec.fieldValueTempBytes = [UInt8]()
}
}
}
case .StateFieldValue:
let spec = self.bodySpecs.last!
while position != end {
if bytes[position] == mime_cr {
if position.distanceTo(end) == 1 {
self.buffer = Array(bytes[position..<end])
clearBuffer = false
position = end
continue
}
if bytes[position.successor()] == mime_lf {
if isBoundaryStart(bytes, start: position.advancedBy(2)) {
position = position.advancedBy(2)
self.state = .StateBoundary
spec.fieldValue = UTF8Encoding.encode(spec.fieldValueTempBytes!)
spec.fieldValueTempBytes = nil
break
} else if position.distanceTo(end) - 2 < self.boundary.characters.count {
// we are at the eol, but check to see if the next line may be starting a boundary
if position.distanceTo(end) < 4 || (bytes[position.advancedBy(2)] == mime_dash && bytes[position.advancedBy(3)] == mime_dash) {
self.buffer = Array(bytes[position..<end])
clearBuffer = false
position = end
continue
}
}
}
}
spec.fieldValueTempBytes!.append(bytes[position])
position = position.successor()
}
case .StateFile:
let spec = self.bodySpecs.last!
while position != end {
if bytes[position] == mime_cr {
if position.distanceTo(end) == 1 {
self.buffer = Array(bytes[position..<end])
clearBuffer = false
position = end
continue
}
if bytes[position.successor()] == mime_lf {
if isBoundaryStart(bytes, start: position.advancedBy(2)) {
position = position.advancedBy(2)
self.state = .StateBoundary
// end of file data
spec.file!.close()
chmod(spec.file!.path(), mode_t(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH))
break
} else if position.distanceTo(end) - 2 < self.boundary.characters.count {
// we are at the eol, but check to see if the next line may be starting a boundary
if position.distanceTo(end) < 4 || (bytes[position.advancedBy(2)] == mime_dash && bytes[position.advancedBy(3)] == mime_dash) {
self.buffer = Array(bytes[position..<end])
clearBuffer = false
position = end
continue
}
}
}
}
// write as much data as we reasonably can
var writeEnd = position
while writeEnd < end {
if bytes[writeEnd] == mime_cr {
if writeEnd.distanceTo(end) < 2 {
break
}
if bytes[writeEnd.successor()] == mime_lf {
if isBoundaryStart(bytes, start: writeEnd.advancedBy(2)) {
break
} else if writeEnd.distanceTo(end) - 2 < self.boundary.characters.count {
// we are at the eol, but check to see if the next line may be starting a boundary
if writeEnd.distanceTo(end) < 4 || (bytes[writeEnd.advancedBy(2)] == mime_dash && bytes[writeEnd.advancedBy(3)] == mime_dash) {
break
}
}
}
}
writeEnd = writeEnd.successor()
}
do {
let length = position.distanceTo(writeEnd)
spec.fileSize += try spec.file!.writeBytes(bytes, dataPosition: position, length: length)
} catch let e {
print("Exception while writing file upload data: \(e)")
self.state = .StateNone
break
}
if (writeEnd == end) {
self.buffer.removeAll()
}
position = writeEnd
self.gotFile = true
}
}
}
if clearBuffer {
self.buffer.removeAll()
}
return self.state
}
/// Add data to be parsed.
/// - parameter bytes: The array of UInt8 to be parsed.
public func addToBuffer(bytes: [UInt8]) {
if isMultiPart() {
if self.buffer.count != 0 {
self.buffer.appendContentsOf(bytes)
internalAddToBuffer(self.buffer)
} else {
internalAddToBuffer(bytes)
}
} else {
self.buffer.appendContentsOf(bytes)
}
}
/// Returns true of the content type indicated a multi-part form.
public func isMultiPart() -> Bool {
return self.multi
}
}