MultipartFormData.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. //
  2. // MultipartFormData.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. #if os(iOS) || os(watchOS) || os(tvOS)
  26. import MobileCoreServices
  27. #elseif os(macOS)
  28. import CoreServices
  29. #endif
  30. /// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
  31. /// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
  32. /// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
  33. /// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
  34. /// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
  35. ///
  36. /// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
  37. /// and the w3 form documentation.
  38. ///
  39. /// - https://www.ietf.org/rfc/rfc2388.txt
  40. /// - https://www.ietf.org/rfc/rfc2045.txt
  41. /// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13
  42. open class MultipartFormData {
  43. // MARK: - Helper Types
  44. struct EncodingCharacters {
  45. static let crlf = "\r\n"
  46. }
  47. struct BoundaryGenerator {
  48. enum BoundaryType {
  49. case initial, encapsulated, final
  50. }
  51. static func randomBoundary() -> String {
  52. return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
  53. }
  54. static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data {
  55. let boundaryText: String
  56. switch boundaryType {
  57. case .initial:
  58. boundaryText = "--\(boundary)\(EncodingCharacters.crlf)"
  59. case .encapsulated:
  60. boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)"
  61. case .final:
  62. boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)"
  63. }
  64. return Data(boundaryText.utf8)
  65. }
  66. }
  67. class BodyPart {
  68. let headers: HTTPHeaders
  69. let bodyStream: InputStream
  70. let bodyContentLength: UInt64
  71. var hasInitialBoundary = false
  72. var hasFinalBoundary = false
  73. init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) {
  74. self.headers = headers
  75. self.bodyStream = bodyStream
  76. self.bodyContentLength = bodyContentLength
  77. }
  78. }
  79. // MARK: - Properties
  80. /// Default memory threshold used when encoding `MultipartFormData`, in bytes.
  81. public static let encodingMemoryThreshold: UInt64 = 10_000_000
  82. /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
  83. open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)"
  84. /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
  85. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
  86. /// The boundary used to separate the body parts in the encoded form data.
  87. public let boundary: String
  88. let fileManager: FileManager
  89. private var bodyParts: [BodyPart]
  90. private var bodyPartError: AFError?
  91. private let streamBufferSize: Int
  92. // MARK: - Lifecycle
  93. /// Creates a multipart form data object.
  94. ///
  95. /// - returns: The multipart form data object.
  96. public init(fileManager: FileManager = .default, boundary: String? = nil) {
  97. self.fileManager = fileManager
  98. self.boundary = boundary ?? BoundaryGenerator.randomBoundary()
  99. self.bodyParts = []
  100. ///
  101. /// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
  102. /// information, please refer to the following article:
  103. /// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
  104. ///
  105. self.streamBufferSize = 1024
  106. }
  107. // MARK: - Body Parts
  108. /// Creates a body part from the data and appends it to the multipart form data object.
  109. ///
  110. /// The body part data will be encoded using the following format:
  111. ///
  112. /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  113. /// - `Content-Type: #{mimeType}` (HTTP Header)
  114. /// - Encoded file data
  115. /// - Multipart form boundary
  116. ///
  117. /// - parameter data: The data to encode into the multipart form data.
  118. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
  119. /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
  120. /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
  121. public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) {
  122. let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
  123. let stream = InputStream(data: data)
  124. let length = UInt64(data.count)
  125. append(stream, withLength: length, headers: headers)
  126. }
  127. /// Creates a body part from the file and appends it to the multipart form data object.
  128. ///
  129. /// The body part data will be encoded using the following format:
  130. ///
  131. /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
  132. /// - `Content-Type: #{generated mimeType}` (HTTP Header)
  133. /// - Encoded file data
  134. /// - Multipart form boundary
  135. ///
  136. /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
  137. /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
  138. /// system associated MIME type.
  139. ///
  140. /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
  141. /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
  142. public func append(_ fileURL: URL, withName name: String) {
  143. let fileName = fileURL.lastPathComponent
  144. let pathExtension = fileURL.pathExtension
  145. if !fileName.isEmpty && !pathExtension.isEmpty {
  146. let mime = mimeType(forPathExtension: pathExtension)
  147. append(fileURL, withName: name, fileName: fileName, mimeType: mime)
  148. } else {
  149. setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL))
  150. }
  151. }
  152. /// Creates a body part from the file and appends it to the multipart form data object.
  153. ///
  154. /// The body part data will be encoded using the following format:
  155. ///
  156. /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
  157. /// - Content-Type: #{mimeType} (HTTP Header)
  158. /// - Encoded file data
  159. /// - Multipart form boundary
  160. ///
  161. /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
  162. /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
  163. /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
  164. /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
  165. public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) {
  166. let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
  167. //============================================================
  168. // Check 1 - is file URL?
  169. //============================================================
  170. guard fileURL.isFileURL else {
  171. setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL))
  172. return
  173. }
  174. //============================================================
  175. // Check 2 - is file URL reachable?
  176. //============================================================
  177. do {
  178. let isReachable = try fileURL.checkPromisedItemIsReachable()
  179. guard isReachable else {
  180. setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL))
  181. return
  182. }
  183. } catch {
  184. setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error))
  185. return
  186. }
  187. //============================================================
  188. // Check 3 - is file URL a directory?
  189. //============================================================
  190. var isDirectory: ObjCBool = false
  191. let path = fileURL.path
  192. guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else {
  193. setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL))
  194. return
  195. }
  196. //============================================================
  197. // Check 4 - can the file size be extracted?
  198. //============================================================
  199. let bodyContentLength: UInt64
  200. do {
  201. guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else {
  202. setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL))
  203. return
  204. }
  205. bodyContentLength = fileSize.uint64Value
  206. }
  207. catch {
  208. setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error))
  209. return
  210. }
  211. //============================================================
  212. // Check 5 - can a stream be created from file URL?
  213. //============================================================
  214. guard let stream = InputStream(url: fileURL) else {
  215. setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL))
  216. return
  217. }
  218. append(stream, withLength: bodyContentLength, headers: headers)
  219. }
  220. /// Creates a body part from the stream and appends it to the multipart form data object.
  221. ///
  222. /// The body part data will be encoded using the following format:
  223. ///
  224. /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  225. /// - `Content-Type: #{mimeType}` (HTTP Header)
  226. /// - Encoded stream data
  227. /// - Multipart form boundary
  228. ///
  229. /// - parameter stream: The input stream to encode in the multipart form data.
  230. /// - parameter length: The content length of the stream.
  231. /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
  232. /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
  233. /// - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
  234. public func append(
  235. _ stream: InputStream,
  236. withLength length: UInt64,
  237. name: String,
  238. fileName: String,
  239. mimeType: String)
  240. {
  241. let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
  242. append(stream, withLength: length, headers: headers)
  243. }
  244. /// Creates a body part with the headers, stream and length and appends it to the multipart form data object.
  245. ///
  246. /// The body part data will be encoded using the following format:
  247. ///
  248. /// - HTTP headers
  249. /// - Encoded stream data
  250. /// - Multipart form boundary
  251. ///
  252. /// - parameter stream: The input stream to encode in the multipart form data.
  253. /// - parameter length: The content length of the stream.
  254. /// - parameter headers: The HTTP headers for the body part.
  255. public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) {
  256. let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
  257. bodyParts.append(bodyPart)
  258. }
  259. // MARK: - Data Encoding
  260. /// Encodes all the appended body parts into a single `Data` value.
  261. ///
  262. /// It is important to note that this method will load all the appended body parts into memory all at the same
  263. /// time. This method should only be used when the encoded data will have a small memory footprint. For large data
  264. /// cases, please use the `writeEncodedData(to:))` method.
  265. ///
  266. /// - throws: An `AFError` if encoding encounters an error.
  267. ///
  268. /// - returns: The encoded `Data` if encoding is successful.
  269. public func encode() throws -> Data {
  270. if let bodyPartError = bodyPartError {
  271. throw bodyPartError
  272. }
  273. var encoded = Data()
  274. bodyParts.first?.hasInitialBoundary = true
  275. bodyParts.last?.hasFinalBoundary = true
  276. for bodyPart in bodyParts {
  277. let encodedData = try encode(bodyPart)
  278. encoded.append(encodedData)
  279. }
  280. return encoded
  281. }
  282. /// Writes the appended body parts into the given file URL.
  283. ///
  284. /// This process is facilitated by reading and writing with input and output streams, respectively. Thus,
  285. /// this approach is very memory efficient and should be used for large body part data.
  286. ///
  287. /// - parameter fileURL: The file URL to write the multipart form data into.
  288. ///
  289. /// - throws: An `AFError` if encoding encounters an error.
  290. public func writeEncodedData(to fileURL: URL) throws {
  291. if let bodyPartError = bodyPartError {
  292. throw bodyPartError
  293. }
  294. if fileManager.fileExists(atPath: fileURL.path) {
  295. throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL))
  296. } else if !fileURL.isFileURL {
  297. throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL))
  298. }
  299. guard let outputStream = OutputStream(url: fileURL, append: false) else {
  300. throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL))
  301. }
  302. outputStream.open()
  303. defer { outputStream.close() }
  304. self.bodyParts.first?.hasInitialBoundary = true
  305. self.bodyParts.last?.hasFinalBoundary = true
  306. for bodyPart in self.bodyParts {
  307. try write(bodyPart, to: outputStream)
  308. }
  309. }
  310. // MARK: - Private - Body Part Encoding
  311. private func encode(_ bodyPart: BodyPart) throws -> Data {
  312. var encoded = Data()
  313. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  314. encoded.append(initialData)
  315. let headerData = encodeHeaders(for: bodyPart)
  316. encoded.append(headerData)
  317. let bodyStreamData = try encodeBodyStream(for: bodyPart)
  318. encoded.append(bodyStreamData)
  319. if bodyPart.hasFinalBoundary {
  320. encoded.append(finalBoundaryData())
  321. }
  322. return encoded
  323. }
  324. private func encodeHeaders(for bodyPart: BodyPart) -> Data {
  325. let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" }
  326. .joined()
  327. + EncodingCharacters.crlf
  328. return Data(headerText.utf8)
  329. }
  330. private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data {
  331. let inputStream = bodyPart.bodyStream
  332. inputStream.open()
  333. defer { inputStream.close() }
  334. var encoded = Data()
  335. while inputStream.hasBytesAvailable {
  336. var buffer = [UInt8](repeating: 0, count: streamBufferSize)
  337. let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
  338. if let error = inputStream.streamError {
  339. throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error))
  340. }
  341. if bytesRead > 0 {
  342. encoded.append(buffer, count: bytesRead)
  343. } else {
  344. break
  345. }
  346. }
  347. return encoded
  348. }
  349. // MARK: - Private - Writing Body Part to Output Stream
  350. private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws {
  351. try writeInitialBoundaryData(for: bodyPart, to: outputStream)
  352. try writeHeaderData(for: bodyPart, to: outputStream)
  353. try writeBodyStream(for: bodyPart, to: outputStream)
  354. try writeFinalBoundaryData(for: bodyPart, to: outputStream)
  355. }
  356. private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  357. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  358. return try write(initialData, to: outputStream)
  359. }
  360. private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  361. let headerData = encodeHeaders(for: bodyPart)
  362. return try write(headerData, to: outputStream)
  363. }
  364. private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  365. let inputStream = bodyPart.bodyStream
  366. inputStream.open()
  367. defer { inputStream.close() }
  368. while inputStream.hasBytesAvailable {
  369. var buffer = [UInt8](repeating: 0, count: streamBufferSize)
  370. let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
  371. if let streamError = inputStream.streamError {
  372. throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError))
  373. }
  374. if bytesRead > 0 {
  375. if buffer.count != bytesRead {
  376. buffer = Array(buffer[0..<bytesRead])
  377. }
  378. try write(&buffer, to: outputStream)
  379. } else {
  380. break
  381. }
  382. }
  383. }
  384. private func writeFinalBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  385. if bodyPart.hasFinalBoundary {
  386. return try write(finalBoundaryData(), to: outputStream)
  387. }
  388. }
  389. // MARK: - Private - Writing Buffered Data to Output Stream
  390. private func write(_ data: Data, to outputStream: OutputStream) throws {
  391. var buffer = [UInt8](repeating: 0, count: data.count)
  392. data.copyBytes(to: &buffer, count: data.count)
  393. return try write(&buffer, to: outputStream)
  394. }
  395. private func write(_ buffer: inout [UInt8], to outputStream: OutputStream) throws {
  396. var bytesToWrite = buffer.count
  397. while bytesToWrite > 0, outputStream.hasSpaceAvailable {
  398. let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
  399. if let error = outputStream.streamError {
  400. throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error))
  401. }
  402. bytesToWrite -= bytesWritten
  403. if bytesToWrite > 0 {
  404. buffer = Array(buffer[bytesWritten..<buffer.count])
  405. }
  406. }
  407. }
  408. // MARK: - Private - Mime Type
  409. private func mimeType(forPathExtension pathExtension: String) -> String {
  410. if
  411. let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
  412. let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue()
  413. {
  414. return contentType as String
  415. }
  416. return "application/octet-stream"
  417. }
  418. // MARK: - Private - Content Headers
  419. private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> HTTPHeaders {
  420. var disposition = "form-data; name=\"\(name)\""
  421. if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" }
  422. var headers: HTTPHeaders = [.contentDisposition(disposition)]
  423. if let mimeType = mimeType { headers.add(.contentType(mimeType)) }
  424. return headers
  425. }
  426. // MARK: - Private - Boundary Encoding
  427. private func initialBoundaryData() -> Data {
  428. return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary)
  429. }
  430. private func encapsulatedBoundaryData() -> Data {
  431. return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary)
  432. }
  433. private func finalBoundaryData() -> Data {
  434. return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary)
  435. }
  436. // MARK: - Private - Errors
  437. private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) {
  438. guard bodyPartError == nil else { return }
  439. bodyPartError = AFError.multipartEncodingFailed(reason: reason)
  440. }
  441. }