AFURLRequestSerialization.m 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  1. // AFURLRequestSerialization.m
  2. // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. #import "AFURLRequestSerialization.h"
  22. #if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
  23. #import <MobileCoreServices/MobileCoreServices.h>
  24. #else
  25. #import <CoreServices/CoreServices.h>
  26. #endif
  27. NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request";
  28. NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response";
  29. typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error);
  30. /**
  31. Returns a percent-escaped string following RFC 3986 for a query string key or value.
  32. RFC 3986 states that the following characters are "reserved" characters.
  33. - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  34. - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  35. In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  36. query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  37. should be percent-escaped in the query string.
  38. - parameter string: The string to be percent-escaped.
  39. - returns: The percent-escaped string.
  40. */
  41. NSString * AFPercentEscapedStringFromString(NSString *string) {
  42. static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
  43. static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
  44. NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
  45. [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
  46. // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028
  47. // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
  48. static NSUInteger const batchSize = 50;
  49. NSUInteger index = 0;
  50. NSMutableString *escaped = @"".mutableCopy;
  51. while (index < string.length) {
  52. NSUInteger length = MIN(string.length - index, batchSize);
  53. NSRange range = NSMakeRange(index, length);
  54. // To avoid breaking up character sequences such as 👴🏻👮🏽
  55. range = [string rangeOfComposedCharacterSequencesForRange:range];
  56. NSString *substring = [string substringWithRange:range];
  57. NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
  58. [escaped appendString:encoded];
  59. index += range.length;
  60. }
  61. return escaped;
  62. }
  63. #pragma mark -
  64. @interface AFQueryStringPair : NSObject
  65. @property (readwrite, nonatomic, strong) id field;
  66. @property (readwrite, nonatomic, strong) id value;
  67. - (instancetype)initWithField:(id)field value:(id)value;
  68. - (NSString *)URLEncodedStringValue;
  69. @end
  70. @implementation AFQueryStringPair
  71. - (instancetype)initWithField:(id)field value:(id)value {
  72. self = [super init];
  73. if (!self) {
  74. return nil;
  75. }
  76. self.field = field;
  77. self.value = value;
  78. return self;
  79. }
  80. - (NSString *)URLEncodedStringValue {
  81. if (!self.value || [self.value isEqual:[NSNull null]]) {
  82. return AFPercentEscapedStringFromString([self.field description]);
  83. } else {
  84. return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])];
  85. }
  86. }
  87. @end
  88. #pragma mark -
  89. FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
  90. FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
  91. NSString * AFQueryStringFromParameters(NSDictionary *parameters) {
  92. NSMutableArray *mutablePairs = [NSMutableArray array];
  93. for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
  94. [mutablePairs addObject:[pair URLEncodedStringValue]];
  95. }
  96. return [mutablePairs componentsJoinedByString:@"&"];
  97. }
  98. NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
  99. return AFQueryStringPairsFromKeyAndValue(nil, dictionary);
  100. }
  101. NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
  102. NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
  103. NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];
  104. if ([value isKindOfClass:[NSDictionary class]]) {
  105. NSDictionary *dictionary = value;
  106. // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
  107. for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
  108. id nestedValue = dictionary[nestedKey];
  109. if (nestedValue) {
  110. [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
  111. }
  112. }
  113. } else if ([value isKindOfClass:[NSArray class]]) {
  114. NSArray *array = value;
  115. for (id nestedValue in array) {
  116. [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
  117. }
  118. } else if ([value isKindOfClass:[NSSet class]]) {
  119. NSSet *set = value;
  120. for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
  121. [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)];
  122. }
  123. } else {
  124. [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
  125. }
  126. return mutableQueryStringComponents;
  127. }
  128. #pragma mark -
  129. @interface AFStreamingMultipartFormData : NSObject <AFMultipartFormData>
  130. - (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
  131. stringEncoding:(NSStringEncoding)encoding;
  132. - (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
  133. @end
  134. #pragma mark -
  135. static NSArray * AFHTTPRequestSerializerObservedKeyPaths() {
  136. static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil;
  137. static dispatch_once_t onceToken;
  138. dispatch_once(&onceToken, ^{
  139. _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))];
  140. });
  141. return _AFHTTPRequestSerializerObservedKeyPaths;
  142. }
  143. static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext;
  144. @interface AFHTTPRequestSerializer ()
  145. @property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths;
  146. @property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders;
  147. @property (readwrite, nonatomic, strong) dispatch_queue_t requestHeaderModificationQueue;
  148. @property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle;
  149. @property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization;
  150. @end
  151. @implementation AFHTTPRequestSerializer
  152. + (instancetype)serializer {
  153. return [[self alloc] init];
  154. }
  155. - (instancetype)init {
  156. self = [super init];
  157. if (!self) {
  158. return nil;
  159. }
  160. self.stringEncoding = NSUTF8StringEncoding;
  161. self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary];
  162. self.requestHeaderModificationQueue = dispatch_queue_create("requestHeaderModificationQueue", DISPATCH_QUEUE_CONCURRENT);
  163. // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
  164. NSMutableArray *acceptLanguagesComponents = [NSMutableArray array];
  165. [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  166. float q = 1.0f - (idx * 0.1f);
  167. [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]];
  168. *stop = q <= 0.5f;
  169. }];
  170. [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"];
  171. NSString *userAgent = nil;
  172. #if TARGET_OS_IOS
  173. // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
  174. userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleVersion"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
  175. #elif TARGET_OS_WATCH
  176. // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
  177. userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleVersion"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]];
  178. #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
  179. userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleVersion"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]];
  180. #endif
  181. if (userAgent) {
  182. if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
  183. NSMutableString *mutableUserAgent = [userAgent mutableCopy];
  184. if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
  185. userAgent = mutableUserAgent;
  186. }
  187. }
  188. [self setValue:userAgent forHTTPHeaderField:@"User-Agent"];
  189. }
  190. // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
  191. self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
  192. self.mutableObservedChangedKeyPaths = [NSMutableSet set];
  193. for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
  194. if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
  195. [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
  196. }
  197. }
  198. return self;
  199. }
  200. - (void)dealloc {
  201. for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
  202. if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
  203. [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext];
  204. }
  205. }
  206. }
  207. #pragma mark -
  208. // Workarounds for crashing behavior using Key-Value Observing with XCTest
  209. // See https://github.com/AFNetworking/AFNetworking/issues/2523
  210. - (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess {
  211. [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
  212. _allowsCellularAccess = allowsCellularAccess;
  213. [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
  214. }
  215. - (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy {
  216. [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
  217. _cachePolicy = cachePolicy;
  218. [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
  219. }
  220. - (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies {
  221. [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
  222. _HTTPShouldHandleCookies = HTTPShouldHandleCookies;
  223. [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
  224. }
  225. - (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining {
  226. [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
  227. _HTTPShouldUsePipelining = HTTPShouldUsePipelining;
  228. [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
  229. }
  230. - (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType {
  231. [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
  232. _networkServiceType = networkServiceType;
  233. [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
  234. }
  235. - (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval {
  236. [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
  237. _timeoutInterval = timeoutInterval;
  238. [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
  239. }
  240. #pragma mark -
  241. - (NSDictionary *)HTTPRequestHeaders {
  242. NSDictionary __block *value;
  243. dispatch_sync(self.requestHeaderModificationQueue, ^{
  244. value = [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders];
  245. });
  246. return value;
  247. }
  248. - (void)setValue:(NSString *)value
  249. forHTTPHeaderField:(NSString *)field
  250. {
  251. dispatch_barrier_async(self.requestHeaderModificationQueue, ^{
  252. [self.mutableHTTPRequestHeaders setValue:value forKey:field];
  253. });
  254. }
  255. - (NSString *)valueForHTTPHeaderField:(NSString *)field {
  256. NSString __block *value;
  257. dispatch_sync(self.requestHeaderModificationQueue, ^{
  258. value = [self.mutableHTTPRequestHeaders valueForKey:field];
  259. });
  260. return value;
  261. }
  262. - (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
  263. password:(NSString *)password
  264. {
  265. NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
  266. NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
  267. [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"];
  268. }
  269. - (void)clearAuthorizationHeader {
  270. dispatch_barrier_async(self.requestHeaderModificationQueue, ^{
  271. [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"];
  272. });
  273. }
  274. #pragma mark -
  275. - (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style {
  276. self.queryStringSerializationStyle = style;
  277. self.queryStringSerialization = nil;
  278. }
  279. - (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block {
  280. self.queryStringSerialization = block;
  281. }
  282. #pragma mark -
  283. - (NSMutableURLRequest *)requestWithMethod:(NSString *)method
  284. URLString:(NSString *)URLString
  285. parameters:(id)parameters
  286. error:(NSError *__autoreleasing *)error
  287. {
  288. NSParameterAssert(method);
  289. NSParameterAssert(URLString);
  290. NSURL *url = [NSURL URLWithString:URLString];
  291. NSParameterAssert(url);
  292. NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
  293. mutableRequest.HTTPMethod = method;
  294. for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
  295. if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
  296. [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
  297. }
  298. }
  299. mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];
  300. return mutableRequest;
  301. }
  302. - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
  303. URLString:(NSString *)URLString
  304. parameters:(NSDictionary *)parameters
  305. constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
  306. error:(NSError *__autoreleasing *)error
  307. {
  308. NSParameterAssert(method);
  309. NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
  310. NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error];
  311. __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];
  312. if (parameters) {
  313. for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
  314. NSData *data = nil;
  315. if ([pair.value isKindOfClass:[NSData class]]) {
  316. data = pair.value;
  317. } else if ([pair.value isEqual:[NSNull null]]) {
  318. data = [NSData data];
  319. } else {
  320. data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
  321. }
  322. if (data) {
  323. [formData appendPartWithFormData:data name:[pair.field description]];
  324. }
  325. }
  326. }
  327. if (block) {
  328. block(formData);
  329. }
  330. return [formData requestByFinalizingMultipartFormData];
  331. }
  332. - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
  333. writingStreamContentsToFile:(NSURL *)fileURL
  334. completionHandler:(void (^)(NSError *error))handler
  335. {
  336. NSParameterAssert(request.HTTPBodyStream);
  337. NSParameterAssert([fileURL isFileURL]);
  338. NSInputStream *inputStream = request.HTTPBodyStream;
  339. NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO];
  340. __block NSError *error = nil;
  341. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  342. [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  343. [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  344. [inputStream open];
  345. [outputStream open];
  346. while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) {
  347. uint8_t buffer[1024];
  348. NSInteger bytesRead = [inputStream read:buffer maxLength:1024];
  349. if (inputStream.streamError || bytesRead < 0) {
  350. error = inputStream.streamError;
  351. break;
  352. }
  353. NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead];
  354. if (outputStream.streamError || bytesWritten < 0) {
  355. error = outputStream.streamError;
  356. break;
  357. }
  358. if (bytesRead == 0 && bytesWritten == 0) {
  359. break;
  360. }
  361. }
  362. [outputStream close];
  363. [inputStream close];
  364. if (handler) {
  365. dispatch_async(dispatch_get_main_queue(), ^{
  366. handler(error);
  367. });
  368. }
  369. });
  370. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  371. mutableRequest.HTTPBodyStream = nil;
  372. return mutableRequest;
  373. }
  374. #pragma mark - AFURLRequestSerialization
  375. - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  376. withParameters:(id)parameters
  377. error:(NSError *__autoreleasing *)error
  378. {
  379. NSParameterAssert(request);
  380. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  381. [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  382. if (![request valueForHTTPHeaderField:field]) {
  383. [mutableRequest setValue:value forHTTPHeaderField:field];
  384. }
  385. }];
  386. NSString *query = nil;
  387. if (parameters) {
  388. if (self.queryStringSerialization) {
  389. NSError *serializationError;
  390. query = self.queryStringSerialization(request, parameters, &serializationError);
  391. if (serializationError) {
  392. if (error) {
  393. *error = serializationError;
  394. }
  395. return nil;
  396. }
  397. } else {
  398. switch (self.queryStringSerializationStyle) {
  399. case AFHTTPRequestQueryStringDefaultStyle:
  400. query = AFQueryStringFromParameters(parameters);
  401. break;
  402. }
  403. }
  404. }
  405. if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  406. if (query && query.length > 0) {
  407. mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
  408. }
  409. } else {
  410. // #2864: an empty string is a valid x-www-form-urlencoded payload
  411. if (!query) {
  412. query = @"";
  413. }
  414. if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  415. [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  416. }
  417. [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
  418. }
  419. return mutableRequest;
  420. }
  421. #pragma mark - NSKeyValueObserving
  422. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  423. if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) {
  424. return NO;
  425. }
  426. return [super automaticallyNotifiesObserversForKey:key];
  427. }
  428. - (void)observeValueForKeyPath:(NSString *)keyPath
  429. ofObject:(__unused id)object
  430. change:(NSDictionary *)change
  431. context:(void *)context
  432. {
  433. if (context == AFHTTPRequestSerializerObserverContext) {
  434. if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
  435. [self.mutableObservedChangedKeyPaths removeObject:keyPath];
  436. } else {
  437. [self.mutableObservedChangedKeyPaths addObject:keyPath];
  438. }
  439. }
  440. }
  441. #pragma mark - NSSecureCoding
  442. + (BOOL)supportsSecureCoding {
  443. return YES;
  444. }
  445. - (instancetype)initWithCoder:(NSCoder *)decoder {
  446. self = [self init];
  447. if (!self) {
  448. return nil;
  449. }
  450. self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy];
  451. self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue];
  452. return self;
  453. }
  454. - (void)encodeWithCoder:(NSCoder *)coder {
  455. dispatch_sync(self.requestHeaderModificationQueue, ^{
  456. [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))];
  457. });
  458. [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))];
  459. }
  460. #pragma mark - NSCopying
  461. - (instancetype)copyWithZone:(NSZone *)zone {
  462. AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
  463. dispatch_sync(self.requestHeaderModificationQueue, ^{
  464. serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
  465. });
  466. serializer.queryStringSerializationStyle = self.queryStringSerializationStyle;
  467. serializer.queryStringSerialization = self.queryStringSerialization;
  468. return serializer;
  469. }
  470. @end
  471. #pragma mark -
  472. static NSString * AFCreateMultipartFormBoundary() {
  473. return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()];
  474. }
  475. static NSString * const kAFMultipartFormCRLF = @"\r\n";
  476. static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) {
  477. return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF];
  478. }
  479. static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) {
  480. return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
  481. }
  482. static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) {
  483. return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
  484. }
  485. static inline NSString * AFContentTypeForPathExtension(NSString *extension) {
  486. NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
  487. NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
  488. if (!contentType) {
  489. return @"application/octet-stream";
  490. } else {
  491. return contentType;
  492. }
  493. }
  494. NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16;
  495. NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
  496. @interface AFHTTPBodyPart : NSObject
  497. @property (nonatomic, assign) NSStringEncoding stringEncoding;
  498. @property (nonatomic, strong) NSDictionary *headers;
  499. @property (nonatomic, copy) NSString *boundary;
  500. @property (nonatomic, strong) id body;
  501. @property (nonatomic, assign) unsigned long long bodyContentLength;
  502. @property (nonatomic, strong) NSInputStream *inputStream;
  503. @property (nonatomic, assign) BOOL hasInitialBoundary;
  504. @property (nonatomic, assign) BOOL hasFinalBoundary;
  505. @property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable;
  506. @property (readonly, nonatomic, assign) unsigned long long contentLength;
  507. - (NSInteger)read:(uint8_t *)buffer
  508. maxLength:(NSUInteger)length;
  509. @end
  510. @interface AFMultipartBodyStream : NSInputStream <NSStreamDelegate>
  511. @property (nonatomic, assign) NSUInteger numberOfBytesInPacket;
  512. @property (nonatomic, assign) NSTimeInterval delay;
  513. @property (nonatomic, strong) NSInputStream *inputStream;
  514. @property (readonly, nonatomic, assign) unsigned long long contentLength;
  515. @property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty;
  516. - (instancetype)initWithStringEncoding:(NSStringEncoding)encoding;
  517. - (void)setInitialAndFinalBoundaries;
  518. - (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart;
  519. @end
  520. #pragma mark -
  521. @interface AFStreamingMultipartFormData ()
  522. @property (readwrite, nonatomic, copy) NSMutableURLRequest *request;
  523. @property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
  524. @property (readwrite, nonatomic, copy) NSString *boundary;
  525. @property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream;
  526. @end
  527. @implementation AFStreamingMultipartFormData
  528. - (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
  529. stringEncoding:(NSStringEncoding)encoding
  530. {
  531. self = [super init];
  532. if (!self) {
  533. return nil;
  534. }
  535. self.request = urlRequest;
  536. self.stringEncoding = encoding;
  537. self.boundary = AFCreateMultipartFormBoundary();
  538. self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding];
  539. return self;
  540. }
  541. - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  542. name:(NSString *)name
  543. error:(NSError * __autoreleasing *)error
  544. {
  545. NSParameterAssert(fileURL);
  546. NSParameterAssert(name);
  547. NSString *fileName = [fileURL lastPathComponent];
  548. NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]);
  549. return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error];
  550. }
  551. - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  552. name:(NSString *)name
  553. fileName:(NSString *)fileName
  554. mimeType:(NSString *)mimeType
  555. error:(NSError * __autoreleasing *)error
  556. {
  557. NSParameterAssert(fileURL);
  558. NSParameterAssert(name);
  559. NSParameterAssert(fileName);
  560. NSParameterAssert(mimeType);
  561. if (![fileURL isFileURL]) {
  562. NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)};
  563. if (error) {
  564. *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
  565. }
  566. return NO;
  567. } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) {
  568. NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)};
  569. if (error) {
  570. *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
  571. }
  572. return NO;
  573. }
  574. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error];
  575. if (!fileAttributes) {
  576. return NO;
  577. }
  578. NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  579. [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
  580. [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
  581. AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
  582. bodyPart.stringEncoding = self.stringEncoding;
  583. bodyPart.headers = mutableHeaders;
  584. bodyPart.boundary = self.boundary;
  585. bodyPart.body = fileURL;
  586. bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue];
  587. [self.bodyStream appendHTTPBodyPart:bodyPart];
  588. return YES;
  589. }
  590. - (void)appendPartWithInputStream:(NSInputStream *)inputStream
  591. name:(NSString *)name
  592. fileName:(NSString *)fileName
  593. length:(int64_t)length
  594. mimeType:(NSString *)mimeType
  595. {
  596. NSParameterAssert(name);
  597. NSParameterAssert(fileName);
  598. NSParameterAssert(mimeType);
  599. NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  600. [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
  601. [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
  602. AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
  603. bodyPart.stringEncoding = self.stringEncoding;
  604. bodyPart.headers = mutableHeaders;
  605. bodyPart.boundary = self.boundary;
  606. bodyPart.body = inputStream;
  607. bodyPart.bodyContentLength = (unsigned long long)length;
  608. [self.bodyStream appendHTTPBodyPart:bodyPart];
  609. }
  610. - (void)appendPartWithFileData:(NSData *)data
  611. name:(NSString *)name
  612. fileName:(NSString *)fileName
  613. mimeType:(NSString *)mimeType
  614. {
  615. NSParameterAssert(name);
  616. NSParameterAssert(fileName);
  617. NSParameterAssert(mimeType);
  618. NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  619. [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
  620. [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
  621. [self appendPartWithHeaders:mutableHeaders body:data];
  622. }
  623. - (void)appendPartWithFormData:(NSData *)data
  624. name:(NSString *)name
  625. {
  626. NSParameterAssert(name);
  627. NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  628. [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
  629. [self appendPartWithHeaders:mutableHeaders body:data];
  630. }
  631. - (void)appendPartWithHeaders:(NSDictionary *)headers
  632. body:(NSData *)body
  633. {
  634. NSParameterAssert(body);
  635. AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
  636. bodyPart.stringEncoding = self.stringEncoding;
  637. bodyPart.headers = headers;
  638. bodyPart.boundary = self.boundary;
  639. bodyPart.bodyContentLength = [body length];
  640. bodyPart.body = body;
  641. [self.bodyStream appendHTTPBodyPart:bodyPart];
  642. }
  643. - (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
  644. delay:(NSTimeInterval)delay
  645. {
  646. self.bodyStream.numberOfBytesInPacket = numberOfBytes;
  647. self.bodyStream.delay = delay;
  648. }
  649. - (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
  650. if ([self.bodyStream isEmpty]) {
  651. return self.request;
  652. }
  653. // Reset the initial and final boundaries to ensure correct Content-Length
  654. [self.bodyStream setInitialAndFinalBoundaries];
  655. [self.request setHTTPBodyStream:self.bodyStream];
  656. [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"];
  657. [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"];
  658. return self.request;
  659. }
  660. @end
  661. #pragma mark -
  662. @interface NSStream ()
  663. @property (readwrite) NSStreamStatus streamStatus;
  664. @property (readwrite, copy) NSError *streamError;
  665. @end
  666. @interface AFMultipartBodyStream () <NSCopying>
  667. @property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
  668. @property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts;
  669. @property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator;
  670. @property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart;
  671. @property (readwrite, nonatomic, strong) NSOutputStream *outputStream;
  672. @property (readwrite, nonatomic, strong) NSMutableData *buffer;
  673. @end
  674. @implementation AFMultipartBodyStream
  675. #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100)
  676. @synthesize delegate;
  677. #endif
  678. @synthesize streamStatus;
  679. @synthesize streamError;
  680. - (instancetype)initWithStringEncoding:(NSStringEncoding)encoding {
  681. self = [super init];
  682. if (!self) {
  683. return nil;
  684. }
  685. self.stringEncoding = encoding;
  686. self.HTTPBodyParts = [NSMutableArray array];
  687. self.numberOfBytesInPacket = NSIntegerMax;
  688. return self;
  689. }
  690. - (void)setInitialAndFinalBoundaries {
  691. if ([self.HTTPBodyParts count] > 0) {
  692. for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
  693. bodyPart.hasInitialBoundary = NO;
  694. bodyPart.hasFinalBoundary = NO;
  695. }
  696. [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES];
  697. [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES];
  698. }
  699. }
  700. - (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart {
  701. [self.HTTPBodyParts addObject:bodyPart];
  702. }
  703. - (BOOL)isEmpty {
  704. return [self.HTTPBodyParts count] == 0;
  705. }
  706. #pragma mark - NSInputStream
  707. - (NSInteger)read:(uint8_t *)buffer
  708. maxLength:(NSUInteger)length
  709. {
  710. if ([self streamStatus] == NSStreamStatusClosed) {
  711. return 0;
  712. }
  713. NSInteger totalNumberOfBytesRead = 0;
  714. while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) {
  715. if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
  716. if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
  717. break;
  718. }
  719. } else {
  720. NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead;
  721. NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength];
  722. if (numberOfBytesRead == -1) {
  723. self.streamError = self.currentHTTPBodyPart.inputStream.streamError;
  724. break;
  725. } else {
  726. totalNumberOfBytesRead += numberOfBytesRead;
  727. if (self.delay > 0.0f) {
  728. [NSThread sleepForTimeInterval:self.delay];
  729. }
  730. }
  731. }
  732. }
  733. return totalNumberOfBytesRead;
  734. }
  735. - (BOOL)getBuffer:(__unused uint8_t **)buffer
  736. length:(__unused NSUInteger *)len
  737. {
  738. return NO;
  739. }
  740. - (BOOL)hasBytesAvailable {
  741. return [self streamStatus] == NSStreamStatusOpen;
  742. }
  743. #pragma mark - NSStream
  744. - (void)open {
  745. if (self.streamStatus == NSStreamStatusOpen) {
  746. return;
  747. }
  748. self.streamStatus = NSStreamStatusOpen;
  749. [self setInitialAndFinalBoundaries];
  750. self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator];
  751. }
  752. - (void)close {
  753. self.streamStatus = NSStreamStatusClosed;
  754. }
  755. - (id)propertyForKey:(__unused NSString *)key {
  756. return nil;
  757. }
  758. - (BOOL)setProperty:(__unused id)property
  759. forKey:(__unused NSString *)key
  760. {
  761. return NO;
  762. }
  763. - (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
  764. forMode:(__unused NSString *)mode
  765. {}
  766. - (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
  767. forMode:(__unused NSString *)mode
  768. {}
  769. - (unsigned long long)contentLength {
  770. unsigned long long length = 0;
  771. for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
  772. length += [bodyPart contentLength];
  773. }
  774. return length;
  775. }
  776. #pragma mark - Undocumented CFReadStream Bridged Methods
  777. - (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop
  778. forMode:(__unused CFStringRef)aMode
  779. {}
  780. - (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop
  781. forMode:(__unused CFStringRef)aMode
  782. {}
  783. - (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags
  784. callback:(__unused CFReadStreamClientCallBack)inCallback
  785. context:(__unused CFStreamClientContext *)inContext {
  786. return NO;
  787. }
  788. #pragma mark - NSCopying
  789. - (instancetype)copyWithZone:(NSZone *)zone {
  790. AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding];
  791. for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
  792. [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]];
  793. }
  794. [bodyStreamCopy setInitialAndFinalBoundaries];
  795. return bodyStreamCopy;
  796. }
  797. @end
  798. #pragma mark -
  799. typedef enum {
  800. AFEncapsulationBoundaryPhase = 1,
  801. AFHeaderPhase = 2,
  802. AFBodyPhase = 3,
  803. AFFinalBoundaryPhase = 4,
  804. } AFHTTPBodyPartReadPhase;
  805. @interface AFHTTPBodyPart () <NSCopying> {
  806. AFHTTPBodyPartReadPhase _phase;
  807. NSInputStream *_inputStream;
  808. unsigned long long _phaseReadOffset;
  809. }
  810. - (BOOL)transitionToNextPhase;
  811. - (NSInteger)readData:(NSData *)data
  812. intoBuffer:(uint8_t *)buffer
  813. maxLength:(NSUInteger)length;
  814. @end
  815. @implementation AFHTTPBodyPart
  816. - (instancetype)init {
  817. self = [super init];
  818. if (!self) {
  819. return nil;
  820. }
  821. [self transitionToNextPhase];
  822. return self;
  823. }
  824. - (void)dealloc {
  825. if (_inputStream) {
  826. [_inputStream close];
  827. _inputStream = nil;
  828. }
  829. }
  830. - (NSInputStream *)inputStream {
  831. if (!_inputStream) {
  832. if ([self.body isKindOfClass:[NSData class]]) {
  833. _inputStream = [NSInputStream inputStreamWithData:self.body];
  834. } else if ([self.body isKindOfClass:[NSURL class]]) {
  835. _inputStream = [NSInputStream inputStreamWithURL:self.body];
  836. } else if ([self.body isKindOfClass:[NSInputStream class]]) {
  837. _inputStream = self.body;
  838. } else {
  839. _inputStream = [NSInputStream inputStreamWithData:[NSData data]];
  840. }
  841. }
  842. return _inputStream;
  843. }
  844. - (NSString *)stringForHeaders {
  845. NSMutableString *headerString = [NSMutableString string];
  846. for (NSString *field in [self.headers allKeys]) {
  847. [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]];
  848. }
  849. [headerString appendString:kAFMultipartFormCRLF];
  850. return [NSString stringWithString:headerString];
  851. }
  852. - (unsigned long long)contentLength {
  853. unsigned long long length = 0;
  854. NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
  855. length += [encapsulationBoundaryData length];
  856. NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
  857. length += [headersData length];
  858. length += _bodyContentLength;
  859. NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
  860. length += [closingBoundaryData length];
  861. return length;
  862. }
  863. - (BOOL)hasBytesAvailable {
  864. // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer
  865. if (_phase == AFFinalBoundaryPhase) {
  866. return YES;
  867. }
  868. switch (self.inputStream.streamStatus) {
  869. case NSStreamStatusNotOpen:
  870. case NSStreamStatusOpening:
  871. case NSStreamStatusOpen:
  872. case NSStreamStatusReading:
  873. case NSStreamStatusWriting:
  874. return YES;
  875. case NSStreamStatusAtEnd:
  876. case NSStreamStatusClosed:
  877. case NSStreamStatusError:
  878. default:
  879. return NO;
  880. }
  881. }
  882. - (NSInteger)read:(uint8_t *)buffer
  883. maxLength:(NSUInteger)length
  884. {
  885. NSInteger totalNumberOfBytesRead = 0;
  886. if (_phase == AFEncapsulationBoundaryPhase) {
  887. NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
  888. totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  889. }
  890. if (_phase == AFHeaderPhase) {
  891. NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
  892. totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  893. }
  894. if (_phase == AFBodyPhase) {
  895. NSInteger numberOfBytesRead = 0;
  896. numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  897. if (numberOfBytesRead == -1) {
  898. return -1;
  899. } else {
  900. totalNumberOfBytesRead += numberOfBytesRead;
  901. if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) {
  902. [self transitionToNextPhase];
  903. }
  904. }
  905. }
  906. if (_phase == AFFinalBoundaryPhase) {
  907. NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
  908. totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  909. }
  910. return totalNumberOfBytesRead;
  911. }
  912. - (NSInteger)readData:(NSData *)data
  913. intoBuffer:(uint8_t *)buffer
  914. maxLength:(NSUInteger)length
  915. {
  916. NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length));
  917. [data getBytes:buffer range:range];
  918. _phaseReadOffset += range.length;
  919. if (((NSUInteger)_phaseReadOffset) >= [data length]) {
  920. [self transitionToNextPhase];
  921. }
  922. return (NSInteger)range.length;
  923. }
  924. - (BOOL)transitionToNextPhase {
  925. if (![[NSThread currentThread] isMainThread]) {
  926. dispatch_sync(dispatch_get_main_queue(), ^{
  927. [self transitionToNextPhase];
  928. });
  929. return YES;
  930. }
  931. switch (_phase) {
  932. case AFEncapsulationBoundaryPhase:
  933. _phase = AFHeaderPhase;
  934. break;
  935. case AFHeaderPhase:
  936. [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  937. [self.inputStream open];
  938. _phase = AFBodyPhase;
  939. break;
  940. case AFBodyPhase:
  941. [self.inputStream close];
  942. _phase = AFFinalBoundaryPhase;
  943. break;
  944. case AFFinalBoundaryPhase:
  945. default:
  946. _phase = AFEncapsulationBoundaryPhase;
  947. break;
  948. }
  949. _phaseReadOffset = 0;
  950. return YES;
  951. }
  952. #pragma mark - NSCopying
  953. - (instancetype)copyWithZone:(NSZone *)zone {
  954. AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
  955. bodyPart.stringEncoding = self.stringEncoding;
  956. bodyPart.headers = self.headers;
  957. bodyPart.bodyContentLength = self.bodyContentLength;
  958. bodyPart.body = self.body;
  959. bodyPart.boundary = self.boundary;
  960. return bodyPart;
  961. }
  962. @end
  963. #pragma mark -
  964. @implementation AFJSONRequestSerializer
  965. + (instancetype)serializer {
  966. return [self serializerWithWritingOptions:(NSJSONWritingOptions)0];
  967. }
  968. + (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
  969. {
  970. AFJSONRequestSerializer *serializer = [[self alloc] init];
  971. serializer.writingOptions = writingOptions;
  972. return serializer;
  973. }
  974. #pragma mark - AFURLRequestSerialization
  975. - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  976. withParameters:(id)parameters
  977. error:(NSError *__autoreleasing *)error
  978. {
  979. NSParameterAssert(request);
  980. if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  981. return [super requestBySerializingRequest:request withParameters:parameters error:error];
  982. }
  983. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  984. [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  985. if (![request valueForHTTPHeaderField:field]) {
  986. [mutableRequest setValue:value forHTTPHeaderField:field];
  987. }
  988. }];
  989. if (parameters) {
  990. if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  991. [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  992. }
  993. if (![NSJSONSerialization isValidJSONObject:parameters]) {
  994. if (error) {
  995. NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)};
  996. *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
  997. }
  998. return nil;
  999. }
  1000. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error];
  1001. if (!jsonData) {
  1002. return nil;
  1003. }
  1004. [mutableRequest setHTTPBody:jsonData];
  1005. }
  1006. return mutableRequest;
  1007. }
  1008. #pragma mark - NSSecureCoding
  1009. - (instancetype)initWithCoder:(NSCoder *)decoder {
  1010. self = [super initWithCoder:decoder];
  1011. if (!self) {
  1012. return nil;
  1013. }
  1014. self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue];
  1015. return self;
  1016. }
  1017. - (void)encodeWithCoder:(NSCoder *)coder {
  1018. [super encodeWithCoder:coder];
  1019. [coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))];
  1020. }
  1021. #pragma mark - NSCopying
  1022. - (instancetype)copyWithZone:(NSZone *)zone {
  1023. AFJSONRequestSerializer *serializer = [super copyWithZone:zone];
  1024. serializer.writingOptions = self.writingOptions;
  1025. return serializer;
  1026. }
  1027. @end
  1028. #pragma mark -
  1029. @implementation AFPropertyListRequestSerializer
  1030. + (instancetype)serializer {
  1031. return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0];
  1032. }
  1033. + (instancetype)serializerWithFormat:(NSPropertyListFormat)format
  1034. writeOptions:(NSPropertyListWriteOptions)writeOptions
  1035. {
  1036. AFPropertyListRequestSerializer *serializer = [[self alloc] init];
  1037. serializer.format = format;
  1038. serializer.writeOptions = writeOptions;
  1039. return serializer;
  1040. }
  1041. #pragma mark - AFURLRequestSerializer
  1042. - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  1043. withParameters:(id)parameters
  1044. error:(NSError *__autoreleasing *)error
  1045. {
  1046. NSParameterAssert(request);
  1047. if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  1048. return [super requestBySerializingRequest:request withParameters:parameters error:error];
  1049. }
  1050. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  1051. [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  1052. if (![request valueForHTTPHeaderField:field]) {
  1053. [mutableRequest setValue:value forHTTPHeaderField:field];
  1054. }
  1055. }];
  1056. if (parameters) {
  1057. if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  1058. [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"];
  1059. }
  1060. NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error];
  1061. if (!plistData) {
  1062. return nil;
  1063. }
  1064. [mutableRequest setHTTPBody:plistData];
  1065. }
  1066. return mutableRequest;
  1067. }
  1068. #pragma mark - NSSecureCoding
  1069. - (instancetype)initWithCoder:(NSCoder *)decoder {
  1070. self = [super initWithCoder:decoder];
  1071. if (!self) {
  1072. return nil;
  1073. }
  1074. self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
  1075. self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue];
  1076. return self;
  1077. }
  1078. - (void)encodeWithCoder:(NSCoder *)coder {
  1079. [super encodeWithCoder:coder];
  1080. [coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))];
  1081. [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))];
  1082. }
  1083. #pragma mark - NSCopying
  1084. - (instancetype)copyWithZone:(NSZone *)zone {
  1085. AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone];
  1086. serializer.format = self.format;
  1087. serializer.writeOptions = self.writeOptions;
  1088. return serializer;
  1089. }
  1090. @end