MultipartFormData.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. // MultipartFormData.swift
  2. //
  3. // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. #if os(iOS)
  24. import MobileCoreServices
  25. #elseif os(OSX)
  26. import CoreServices
  27. #endif
  28. /**
  29. Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
  30. multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
  31. to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
  32. data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
  33. larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
  34. For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
  35. and the w3 form documentation.
  36. - http://www.ietf.org/rfc/rfc2388.txt
  37. - http://www.ietf.org/rfc/rfc2045.txt
  38. - http://www.w3.org/TR/html401/interact/forms.html#h-17.13
  39. */
  40. public class MultipartFormData {
  41. // MARK: - Helper Types
  42. /**
  43. Used to specify whether encoding was successful.
  44. */
  45. public enum EncodingResult {
  46. case Success(NSData)
  47. case Failure(NSError)
  48. }
  49. struct EncodingCharacters {
  50. static let CRLF = "\r\n"
  51. }
  52. struct BoundaryGenerator {
  53. enum BoundaryType {
  54. case Initial, Encapsulated, Final
  55. }
  56. static func randomBoundary() -> String {
  57. return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
  58. }
  59. static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData {
  60. let boundaryText: String
  61. switch boundaryType {
  62. case .Initial:
  63. boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
  64. case .Encapsulated:
  65. boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
  66. case .Final:
  67. boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
  68. }
  69. return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  70. }
  71. }
  72. class BodyPart {
  73. let headers: [String: String]
  74. let bodyStream: NSInputStream
  75. let bodyContentLength: UInt64
  76. var hasInitialBoundary = false
  77. var hasFinalBoundary = false
  78. init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
  79. self.headers = headers
  80. self.bodyStream = bodyStream
  81. self.bodyContentLength = bodyContentLength
  82. }
  83. }
  84. // MARK: - Properties
  85. /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
  86. public var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
  87. /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
  88. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
  89. /// The boundary used to separate the body parts in the encoded form data.
  90. public let boundary: String
  91. private var bodyParts: [BodyPart]
  92. private var bodyPartError: NSError?
  93. private let streamBufferSize: Int
  94. // MARK: - Lifecycle
  95. /**
  96. Creates a multipart form data object.
  97. - returns: The multipart form data object.
  98. */
  99. public init() {
  100. self.boundary = BoundaryGenerator.randomBoundary()
  101. self.bodyParts = []
  102. /**
  103. * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
  104. * information, please refer to the following article:
  105. * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
  106. */
  107. self.streamBufferSize = 1024
  108. }
  109. // MARK: - Body Parts
  110. /**
  111. Creates a body part from the data and appends it to the multipart form data object.
  112. The body part data will be encoded using the following format:
  113. - `Content-Disposition: form-data; name=#{name}` (HTTP Header)
  114. - Encoded data
  115. - Multipart form boundary
  116. - parameter data: The data to encode into the multipart form data.
  117. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
  118. */
  119. public func appendBodyPart(data data: NSData, name: String) {
  120. let headers = contentHeaders(name: name)
  121. let stream = NSInputStream(data: data)
  122. let length = UInt64(data.length)
  123. appendBodyPart(stream: stream, length: length, headers: headers)
  124. }
  125. /**
  126. Creates a body part from the data and appends it to the multipart form data object.
  127. The body part data will be encoded using the following format:
  128. - `Content-Disposition: form-data; name=#{name}` (HTTP Header)
  129. - `Content-Type: #{generated mimeType}` (HTTP Header)
  130. - Encoded data
  131. - Multipart form boundary
  132. - parameter data: The data to encode into the multipart form data.
  133. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
  134. - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
  135. */
  136. public func appendBodyPart(data data: NSData, name: String, mimeType: String) {
  137. let headers = contentHeaders(name: name, mimeType: mimeType)
  138. let stream = NSInputStream(data: data)
  139. let length = UInt64(data.length)
  140. appendBodyPart(stream: stream, length: length, headers: headers)
  141. }
  142. /**
  143. Creates a body part from the data and appends it to the multipart form data object.
  144. The body part data will be encoded using the following format:
  145. - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  146. - `Content-Type: #{mimeType}` (HTTP Header)
  147. - Encoded file data
  148. - Multipart form boundary
  149. - parameter data: The data to encode into the multipart form data.
  150. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
  151. - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
  152. - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
  153. */
  154. public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) {
  155. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  156. let stream = NSInputStream(data: data)
  157. let length = UInt64(data.length)
  158. appendBodyPart(stream: stream, length: length, headers: headers)
  159. }
  160. /**
  161. Creates a body part from the file and appends it to the multipart form data object.
  162. The body part data will be encoded using the following format:
  163. - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
  164. - `Content-Type: #{generated mimeType}` (HTTP Header)
  165. - Encoded file data
  166. - Multipart form boundary
  167. The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
  168. `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
  169. system associated MIME type.
  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. */
  173. public func appendBodyPart(fileURL fileURL: NSURL, name: String) {
  174. if let
  175. fileName = fileURL.lastPathComponent,
  176. pathExtension = fileURL.pathExtension
  177. {
  178. let mimeType = mimeTypeForPathExtension(pathExtension)
  179. appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
  180. } else {
  181. let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
  182. let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
  183. let error = NSError(domain: AlamofireErrorDomain, code: NSURLErrorBadURL, userInfo: userInfo)
  184. setBodyPartError(error)
  185. }
  186. }
  187. /**
  188. Creates a body part from the file and appends it to the multipart form data object.
  189. The body part data will be encoded using the following format:
  190. - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
  191. - Content-Type: #{mimeType} (HTTP Header)
  192. - Encoded file data
  193. - Multipart form boundary
  194. - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
  195. - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
  196. - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
  197. - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
  198. */
  199. public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) {
  200. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  201. //============================================================
  202. // Check 1 - is file URL?
  203. //============================================================
  204. guard fileURL.fileURL else {
  205. let failureReason = "The file URL does not point to a file URL: \(fileURL)"
  206. let error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  207. setBodyPartError(error)
  208. return
  209. }
  210. //============================================================
  211. // Check 2 - is file URL reachable?
  212. //============================================================
  213. var isReachable = false
  214. do {
  215. try fileURL.checkResourceIsReachable()
  216. isReachable = true
  217. } catch {
  218. // No-op
  219. }
  220. guard isReachable else {
  221. let error = errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
  222. setBodyPartError(error)
  223. return
  224. }
  225. //============================================================
  226. // Check 3 - is file URL a directory?
  227. //============================================================
  228. var isDirectory: ObjCBool = false
  229. guard let
  230. path = fileURL.path
  231. where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
  232. {
  233. let failureReason = "The file URL is a directory, not a file: \(fileURL)"
  234. let error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  235. setBodyPartError(error)
  236. return
  237. }
  238. //============================================================
  239. // Check 4 - can the file size be extracted?
  240. //============================================================
  241. var bodyContentLength: UInt64?
  242. do {
  243. if let
  244. path = fileURL.path,
  245. fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber
  246. {
  247. bodyContentLength = fileSize.unsignedLongLongValue
  248. }
  249. } catch {
  250. // No-op
  251. }
  252. guard let length = bodyContentLength else {
  253. let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
  254. let error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  255. setBodyPartError(error)
  256. return
  257. }
  258. //============================================================
  259. // Check 5 - can a stream be created from file URL?
  260. //============================================================
  261. guard let stream = NSInputStream(URL: fileURL) else {
  262. let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
  263. let error = errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
  264. setBodyPartError(error)
  265. return
  266. }
  267. appendBodyPart(stream: stream, length: length, headers: headers)
  268. }
  269. /**
  270. Creates a body part from the stream and appends it to the multipart form data object.
  271. The body part data will be encoded using the following format:
  272. - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  273. - `Content-Type: #{mimeType}` (HTTP Header)
  274. - Encoded stream data
  275. - Multipart form boundary
  276. - parameter stream: The input stream to encode in the multipart form data.
  277. - parameter length: The content length of the stream.
  278. - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
  279. - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
  280. - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
  281. */
  282. public func appendBodyPart(stream stream: NSInputStream, length: UInt64, name: String, fileName: String, mimeType: String) {
  283. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  284. appendBodyPart(stream: stream, length: length, headers: headers)
  285. }
  286. /**
  287. Creates a body part with the headers, stream and length and appends it to the multipart form data object.
  288. The body part data will be encoded using the following format:
  289. - HTTP headers
  290. - Encoded stream data
  291. - Multipart form boundary
  292. - parameter stream: The input stream to encode in the multipart form data.
  293. - parameter length: The content length of the stream.
  294. - parameter headers: The HTTP headers for the body part.
  295. */
  296. public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) {
  297. let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
  298. bodyParts.append(bodyPart)
  299. }
  300. // MARK: - Data Encoding
  301. /**
  302. Encodes all the appended body parts into a single `NSData` object.
  303. It is important to note that this method will load all the appended body parts into memory all at the same
  304. time. This method should only be used when the encoded data will have a small memory footprint. For large data
  305. cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
  306. - returns: EncodingResult containing an `NSData` object if the encoding succeeded, an `NSError` otherwise.
  307. */
  308. public func encode() -> EncodingResult {
  309. if let bodyPartError = bodyPartError {
  310. return .Failure(bodyPartError)
  311. }
  312. let encoded = NSMutableData()
  313. bodyParts.first?.hasInitialBoundary = true
  314. bodyParts.last?.hasFinalBoundary = true
  315. for bodyPart in bodyParts {
  316. let encodedDataResult = encodeBodyPart(bodyPart)
  317. switch encodedDataResult {
  318. case .Failure:
  319. return encodedDataResult
  320. case let .Success(data):
  321. encoded.appendData(data)
  322. }
  323. }
  324. return .Success(encoded)
  325. }
  326. /**
  327. Writes the appended body parts into the given file URL asynchronously and calls the `completionHandler`
  328. when finished.
  329. This process is facilitated by reading and writing with input and output streams, respectively. Thus,
  330. this approach is very memory efficient and should be used for large body part data.
  331. - parameter fileURL: The file URL to write the multipart form data into.
  332. - parameter completionHandler: A closure to be executed when writing is finished.
  333. */
  334. public func writeEncodedDataToDisk(fileURL: NSURL, completionHandler: (NSError?) -> Void) {
  335. if let bodyPartError = bodyPartError {
  336. completionHandler(bodyPartError)
  337. return
  338. }
  339. var error: NSError?
  340. if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
  341. let failureReason = "A file already exists at the given file URL: \(fileURL)"
  342. error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  343. } else if !fileURL.fileURL {
  344. let failureReason = "The URL does not point to a valid file: \(fileURL)"
  345. error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  346. }
  347. if let error = error {
  348. completionHandler(error)
  349. return
  350. }
  351. let outputStream: NSOutputStream
  352. if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
  353. outputStream = possibleOutputStream
  354. } else {
  355. let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
  356. let error = errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
  357. completionHandler(error)
  358. return
  359. }
  360. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
  361. outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  362. outputStream.open()
  363. self.bodyParts.first?.hasInitialBoundary = true
  364. self.bodyParts.last?.hasFinalBoundary = true
  365. var error: NSError?
  366. for bodyPart in self.bodyParts {
  367. if let writeError = self.writeBodyPart(bodyPart, toOutputStream: outputStream) {
  368. error = writeError
  369. break
  370. }
  371. }
  372. outputStream.close()
  373. outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  374. dispatch_async(dispatch_get_main_queue()) {
  375. completionHandler(error)
  376. }
  377. }
  378. }
  379. // MARK: - Private - Body Part Encoding
  380. private func encodeBodyPart(bodyPart: BodyPart) -> EncodingResult {
  381. let encoded = NSMutableData()
  382. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  383. encoded.appendData(initialData)
  384. let headerData = encodeHeaderDataForBodyPart(bodyPart)
  385. encoded.appendData(headerData)
  386. let bodyStreamResult = encodeBodyStreamDataForBodyPart(bodyPart)
  387. switch bodyStreamResult {
  388. case .Failure:
  389. return bodyStreamResult
  390. case let .Success(data):
  391. encoded.appendData(data)
  392. }
  393. if bodyPart.hasFinalBoundary {
  394. encoded.appendData(finalBoundaryData())
  395. }
  396. return .Success(encoded)
  397. }
  398. private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
  399. var headerText = ""
  400. for (key, value) in bodyPart.headers {
  401. headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
  402. }
  403. headerText += EncodingCharacters.CRLF
  404. return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  405. }
  406. private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) -> EncodingResult {
  407. let inputStream = bodyPart.bodyStream
  408. inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  409. inputStream.open()
  410. var error: NSError?
  411. let encoded = NSMutableData()
  412. while inputStream.hasBytesAvailable {
  413. var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
  414. let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
  415. if inputStream.streamError != nil {
  416. error = inputStream.streamError
  417. break
  418. }
  419. if bytesRead > 0 {
  420. encoded.appendBytes(buffer, length: bytesRead)
  421. } else if bytesRead < 0 {
  422. let failureReason = "Failed to read from input stream: \(inputStream)"
  423. error = errorWithCode(AlamofireInputStreamReadFailed, failureReason: failureReason)
  424. break
  425. } else {
  426. break
  427. }
  428. }
  429. inputStream.close()
  430. inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  431. if let error = error {
  432. return .Failure(error)
  433. }
  434. return .Success(encoded)
  435. }
  436. // MARK: - Private - Writing Body Part to Output Stream
  437. private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  438. if let error = writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) {
  439. return error
  440. }
  441. if let error = writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) {
  442. return error
  443. }
  444. if let error = writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) {
  445. return error
  446. }
  447. if let error = writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) {
  448. return error
  449. }
  450. return nil
  451. }
  452. private func writeInitialBoundaryDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  453. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  454. return writeData(initialData, toOutputStream: outputStream)
  455. }
  456. private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  457. let headerData = encodeHeaderDataForBodyPart(bodyPart)
  458. return writeData(headerData, toOutputStream: outputStream)
  459. }
  460. private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  461. var error: NSError?
  462. let inputStream = bodyPart.bodyStream
  463. inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  464. inputStream.open()
  465. while inputStream.hasBytesAvailable {
  466. var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
  467. let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
  468. if inputStream.streamError != nil {
  469. error = inputStream.streamError
  470. break
  471. }
  472. if bytesRead > 0 {
  473. if buffer.count != bytesRead {
  474. buffer = Array(buffer[0..<bytesRead])
  475. }
  476. if let writeError = writeBuffer(&buffer, toOutputStream: outputStream) {
  477. error = writeError
  478. break
  479. }
  480. } else if bytesRead < 0 {
  481. let failureReason = "Failed to read from input stream: \(inputStream)"
  482. error = errorWithCode(AlamofireInputStreamReadFailed, failureReason: failureReason)
  483. break
  484. } else {
  485. break
  486. }
  487. }
  488. inputStream.close()
  489. inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  490. return error
  491. }
  492. private func writeFinalBoundaryDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  493. if bodyPart.hasFinalBoundary {
  494. return writeData(finalBoundaryData(), toOutputStream: outputStream)
  495. }
  496. return nil
  497. }
  498. // MARK: - Private - Writing Buffered Data to Output Stream
  499. private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) -> NSError? {
  500. var buffer = [UInt8](count: data.length, repeatedValue: 0)
  501. data.getBytes(&buffer, length: data.length)
  502. return writeBuffer(&buffer, toOutputStream: outputStream)
  503. }
  504. private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) -> NSError? {
  505. var error: NSError?
  506. var bytesToWrite = buffer.count
  507. while bytesToWrite > 0 {
  508. if outputStream.hasSpaceAvailable {
  509. let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
  510. if outputStream.streamError != nil {
  511. error = outputStream.streamError
  512. break
  513. }
  514. if bytesWritten < 0 {
  515. let failureReason = "Failed to write to output stream: \(outputStream)"
  516. error = errorWithCode(AlamofireOutputStreamWriteFailed, failureReason: failureReason)
  517. break
  518. }
  519. bytesToWrite -= bytesWritten
  520. if bytesToWrite > 0 {
  521. buffer = Array(buffer[bytesWritten..<buffer.count])
  522. }
  523. } else if outputStream.streamError != nil {
  524. error = outputStream.streamError
  525. break
  526. }
  527. }
  528. return error
  529. }
  530. // MARK: - Private - Mime Type
  531. private func mimeTypeForPathExtension(pathExtension: String) -> String {
  532. if let
  533. id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),
  534. contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue()
  535. {
  536. return contentType as String
  537. }
  538. return "application/octet-stream"
  539. }
  540. // MARK: - Private - Content Headers
  541. private func contentHeaders(name name: String) -> [String: String] {
  542. return ["Content-Disposition": "form-data; name=\"\(name)\""]
  543. }
  544. private func contentHeaders(name name: String, mimeType: String) -> [String: String] {
  545. return [
  546. "Content-Disposition": "form-data; name=\"\(name)\"",
  547. "Content-Type": "\(mimeType)"
  548. ]
  549. }
  550. private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] {
  551. return [
  552. "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
  553. "Content-Type": "\(mimeType)"
  554. ]
  555. }
  556. // MARK: - Private - Boundary Encoding
  557. private func initialBoundaryData() -> NSData {
  558. return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary)
  559. }
  560. private func encapsulatedBoundaryData() -> NSData {
  561. return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary)
  562. }
  563. private func finalBoundaryData() -> NSData {
  564. return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary)
  565. }
  566. // MARK: - Private - Errors
  567. private func setBodyPartError(error: NSError) {
  568. if bodyPartError == nil {
  569. bodyPartError = error
  570. }
  571. }
  572. private func errorWithCode(code: Int, failureReason: String) -> NSError {
  573. let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
  574. return NSError(domain: AlamofireErrorDomain, code: code, userInfo: userInfo)
  575. }
  576. }