MultipartFormData.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. //
  2. // MultipartFormData.swift
  3. //
  4. // Copyright (c) 2014-2016 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(OSX)
  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 boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)!
  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. /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
  81. open var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
  82. /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
  83. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
  84. /// The boundary used to separate the body parts in the encoded form data.
  85. public let boundary: String
  86. private var bodyParts: [BodyPart]
  87. private var bodyPartError: AFError?
  88. private let streamBufferSize: Int
  89. // MARK: - Lifecycle
  90. /// Creates a multipart form data object.
  91. ///
  92. /// - returns: The multipart form data object.
  93. public init() {
  94. self.boundary = BoundaryGenerator.randomBoundary()
  95. self.bodyParts = []
  96. ///
  97. /// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
  98. /// information, please refer to the following article:
  99. /// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
  100. ///
  101. self.streamBufferSize = 1024
  102. }
  103. // MARK: - Body Parts
  104. /// Creates a body part from the data and appends it to the multipart form data object.
  105. ///
  106. /// The body part data will be encoded using the following format:
  107. ///
  108. /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header)
  109. /// - Encoded data
  110. /// - Multipart form boundary
  111. ///
  112. /// - parameter data: The data to encode into the multipart form data.
  113. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
  114. public func append(_ data: Data, withName name: String) {
  115. let headers = contentHeaders(withName: name)
  116. let stream = InputStream(data: data)
  117. let length = UInt64(data.count)
  118. append(stream, withLength: length, headers: headers)
  119. }
  120. /// Creates a body part from the data and appends it to the multipart form data object.
  121. ///
  122. /// The body part data will be encoded using the following format:
  123. ///
  124. /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header)
  125. /// - `Content-Type: #{generated mimeType}` (HTTP Header)
  126. /// - Encoded data
  127. /// - Multipart form boundary
  128. ///
  129. /// - parameter data: The data to encode into the multipart form data.
  130. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
  131. /// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
  132. public func append(_ data: Data, withName name: String, mimeType: String) {
  133. let headers = contentHeaders(withName: name, mimeType: mimeType)
  134. let stream = InputStream(data: data)
  135. let length = UInt64(data.count)
  136. append(stream, withLength: length, headers: headers)
  137. }
  138. /// Creates a body part from the data and appends it to the multipart form data object.
  139. ///
  140. /// The body part data will be encoded using the following format:
  141. ///
  142. /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  143. /// - `Content-Type: #{mimeType}` (HTTP Header)
  144. /// - Encoded file data
  145. /// - Multipart form boundary
  146. ///
  147. /// - parameter data: The data to encode into the multipart form data.
  148. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
  149. /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
  150. /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
  151. public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) {
  152. let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
  153. let stream = InputStream(data: data)
  154. let length = UInt64(data.count)
  155. append(stream, withLength: length, headers: headers)
  156. }
  157. /// Creates a body part from the file and appends it to the multipart form data object.
  158. ///
  159. /// The body part data will be encoded using the following format:
  160. ///
  161. /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
  162. /// - `Content-Type: #{generated mimeType}` (HTTP Header)
  163. /// - Encoded file data
  164. /// - Multipart form boundary
  165. ///
  166. /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
  167. /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
  168. /// system associated MIME type.
  169. ///
  170. /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
  171. /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
  172. public func append(_ fileURL: URL, withName name: String) {
  173. let fileName = fileURL.lastPathComponent
  174. let pathExtension = fileURL.pathExtension
  175. if !fileName.isEmpty && !pathExtension.isEmpty {
  176. let mime = mimeType(forPathExtension: pathExtension)
  177. append(fileURL, withName: name, fileName: fileName, mimeType: mime)
  178. } else {
  179. setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL))
  180. }
  181. }
  182. /// Creates a body part from the file and appends it to the multipart form data object.
  183. ///
  184. /// The body part data will be encoded using the following format:
  185. ///
  186. /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
  187. /// - Content-Type: #{mimeType} (HTTP Header)
  188. /// - Encoded file data
  189. /// - Multipart form boundary
  190. ///
  191. /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
  192. /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
  193. /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
  194. /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
  195. public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) {
  196. let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
  197. //============================================================
  198. // Check 1 - is file URL?
  199. //============================================================
  200. guard fileURL.isFileURL else {
  201. setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL))
  202. return
  203. }
  204. //============================================================
  205. // Check 2 - is file URL reachable?
  206. //============================================================
  207. do {
  208. let isReachable = try fileURL.checkPromisedItemIsReachable()
  209. guard isReachable else {
  210. setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL))
  211. return
  212. }
  213. } catch {
  214. setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error))
  215. return
  216. }
  217. //============================================================
  218. // Check 3 - is file URL a directory?
  219. //============================================================
  220. var isDirectory: ObjCBool = false
  221. let path = fileURL.path
  222. guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else
  223. {
  224. setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL))
  225. return
  226. }
  227. //============================================================
  228. // Check 4 - can the file size be extracted?
  229. //============================================================
  230. let bodyContentLength: UInt64
  231. do {
  232. guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else {
  233. setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL))
  234. return
  235. }
  236. bodyContentLength = fileSize.uint64Value
  237. }
  238. catch {
  239. setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error))
  240. return
  241. }
  242. //============================================================
  243. // Check 5 - can a stream be created from file URL?
  244. //============================================================
  245. guard let stream = InputStream(url: fileURL) else {
  246. setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL))
  247. return
  248. }
  249. append(stream, withLength: bodyContentLength, headers: headers)
  250. }
  251. /// Creates a body part from the stream and appends it to the multipart form data object.
  252. ///
  253. /// The body part data will be encoded using the following format:
  254. ///
  255. /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  256. /// - `Content-Type: #{mimeType}` (HTTP Header)
  257. /// - Encoded stream data
  258. /// - Multipart form boundary
  259. ///
  260. /// - parameter stream: The input stream to encode in the multipart form data.
  261. /// - parameter length: The content length of the stream.
  262. /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
  263. /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
  264. /// - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
  265. public func append(
  266. _ stream: InputStream,
  267. withLength length: UInt64,
  268. name: String,
  269. fileName: String,
  270. mimeType: String)
  271. {
  272. let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
  273. append(stream, withLength: length, headers: headers)
  274. }
  275. /// Creates a body part with the headers, stream and length and appends it to the multipart form data object.
  276. ///
  277. /// The body part data will be encoded using the following format:
  278. ///
  279. /// - HTTP headers
  280. /// - Encoded stream data
  281. /// - Multipart form boundary
  282. ///
  283. /// - parameter stream: The input stream to encode in the multipart form data.
  284. /// - parameter length: The content length of the stream.
  285. /// - parameter headers: The HTTP headers for the body part.
  286. public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) {
  287. let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
  288. bodyParts.append(bodyPart)
  289. }
  290. // MARK: - Data Encoding
  291. /// Encodes all the appended body parts into a single `Data` value.
  292. ///
  293. /// It is important to note that this method will load all the appended body parts into memory all at the same
  294. /// time. This method should only be used when the encoded data will have a small memory footprint. For large data
  295. /// cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
  296. ///
  297. /// - throws: An `AFError` if encoding encounters an error.
  298. ///
  299. /// - returns: The encoded `Data` if encoding is successful.
  300. public func encode() throws -> Data {
  301. if let bodyPartError = bodyPartError {
  302. throw bodyPartError
  303. }
  304. var encoded = Data()
  305. bodyParts.first?.hasInitialBoundary = true
  306. bodyParts.last?.hasFinalBoundary = true
  307. for bodyPart in bodyParts {
  308. let encodedData = try encode(bodyPart)
  309. encoded.append(encodedData)
  310. }
  311. return encoded
  312. }
  313. /// Writes the appended body parts into the given file URL.
  314. ///
  315. /// This process is facilitated by reading and writing with input and output streams, respectively. Thus,
  316. /// this approach is very memory efficient and should be used for large body part data.
  317. ///
  318. /// - parameter fileURL: The file URL to write the multipart form data into.
  319. ///
  320. /// - throws: An `AFError` if encoding encounters an error.
  321. public func writeEncodedData(to fileURL: URL) throws {
  322. if let bodyPartError = bodyPartError {
  323. throw bodyPartError
  324. }
  325. if FileManager.default.fileExists(atPath: fileURL.path) {
  326. throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL))
  327. } else if !fileURL.isFileURL {
  328. throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL))
  329. }
  330. guard let outputStream = OutputStream(url: fileURL, append: false) else {
  331. throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL))
  332. }
  333. outputStream.open()
  334. defer { outputStream.close() }
  335. self.bodyParts.first?.hasInitialBoundary = true
  336. self.bodyParts.last?.hasFinalBoundary = true
  337. for bodyPart in self.bodyParts {
  338. try write(bodyPart, to: outputStream)
  339. }
  340. }
  341. // MARK: - Private - Body Part Encoding
  342. private func encode(_ bodyPart: BodyPart) throws -> Data {
  343. var encoded = Data()
  344. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  345. encoded.append(initialData)
  346. let headerData = encodeHeaders(for: bodyPart)
  347. encoded.append(headerData)
  348. let bodyStreamData = try encodeBodyStream(for: bodyPart)
  349. encoded.append(bodyStreamData)
  350. if bodyPart.hasFinalBoundary {
  351. encoded.append(finalBoundaryData())
  352. }
  353. return encoded
  354. }
  355. private func encodeHeaders(for bodyPart: BodyPart) -> Data {
  356. var headerText = ""
  357. for (key, value) in bodyPart.headers {
  358. headerText += "\(key): \(value)\(EncodingCharacters.crlf)"
  359. }
  360. headerText += EncodingCharacters.crlf
  361. return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)!
  362. }
  363. private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data {
  364. let inputStream = bodyPart.bodyStream
  365. inputStream.open()
  366. defer { inputStream.close() }
  367. var encoded = Data()
  368. while inputStream.hasBytesAvailable {
  369. var buffer = [UInt8](repeating: 0, count: streamBufferSize)
  370. let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
  371. if let error = inputStream.streamError {
  372. throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error))
  373. }
  374. if bytesRead > 0 {
  375. encoded.append(buffer, count: bytesRead)
  376. } else {
  377. break
  378. }
  379. }
  380. return encoded
  381. }
  382. // MARK: - Private - Writing Body Part to Output Stream
  383. private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws {
  384. try writeInitialBoundaryData(for: bodyPart, to: outputStream)
  385. try writeHeaderData(for: bodyPart, to: outputStream)
  386. try writeBodyStream(for: bodyPart, to: outputStream)
  387. try writeFinalBoundaryData(for: bodyPart, to: outputStream)
  388. }
  389. private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  390. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  391. return try write(initialData, to: outputStream)
  392. }
  393. private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  394. let headerData = encodeHeaders(for: bodyPart)
  395. return try write(headerData, to: outputStream)
  396. }
  397. private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  398. let inputStream = bodyPart.bodyStream
  399. inputStream.open()
  400. defer { inputStream.close() }
  401. while inputStream.hasBytesAvailable {
  402. var buffer = [UInt8](repeating: 0, count: streamBufferSize)
  403. let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
  404. if let streamError = inputStream.streamError {
  405. throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError))
  406. }
  407. if bytesRead > 0 {
  408. if buffer.count != bytesRead {
  409. buffer = Array(buffer[0..<bytesRead])
  410. }
  411. try write(&buffer, to: outputStream)
  412. } else {
  413. break
  414. }
  415. }
  416. }
  417. private func writeFinalBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  418. if bodyPart.hasFinalBoundary {
  419. return try write(finalBoundaryData(), to: outputStream)
  420. }
  421. }
  422. // MARK: - Private - Writing Buffered Data to Output Stream
  423. private func write(_ data: Data, to outputStream: OutputStream) throws {
  424. var buffer = [UInt8](repeating: 0, count: data.count)
  425. data.copyBytes(to: &buffer, count: data.count)
  426. return try write(&buffer, to: outputStream)
  427. }
  428. private func write(_ buffer: inout [UInt8], to outputStream: OutputStream) throws {
  429. var bytesToWrite = buffer.count
  430. while bytesToWrite > 0, outputStream.hasSpaceAvailable {
  431. let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
  432. if let error = outputStream.streamError {
  433. throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error))
  434. }
  435. bytesToWrite -= bytesWritten
  436. if bytesToWrite > 0 {
  437. buffer = Array(buffer[bytesWritten..<buffer.count])
  438. }
  439. }
  440. }
  441. // MARK: - Private - Mime Type
  442. private func mimeType(forPathExtension pathExtension: String) -> String {
  443. if
  444. let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
  445. let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue()
  446. {
  447. return contentType as String
  448. }
  449. return "application/octet-stream"
  450. }
  451. // MARK: - Private - Content Headers
  452. private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] {
  453. var disposition = "form-data; name=\"\(name)\""
  454. if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" }
  455. var headers = ["Content-Disposition": disposition]
  456. if let mimeType = mimeType { headers["Content-Type"] = mimeType }
  457. return headers
  458. }
  459. // MARK: - Private - Boundary Encoding
  460. private func initialBoundaryData() -> Data {
  461. return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary)
  462. }
  463. private func encapsulatedBoundaryData() -> Data {
  464. return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary)
  465. }
  466. private func finalBoundaryData() -> Data {
  467. return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary)
  468. }
  469. // MARK: - Private - Errors
  470. private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) {
  471. guard bodyPartError == nil else { return }
  472. bodyPartError = AFError.multipartEncodingFailed(reason: reason)
  473. }
  474. }