AFURLRequestSerialization.m 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. // AFURLRequestSerialization.m
  2. // Copyright (c) 2011–2015 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 __IPHONE_OS_VERSION_MIN_REQUIRED
  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. static NSString * AFBase64EncodedStringFromString(NSString *string) {
  31. NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
  32. NSUInteger length = [data length];
  33. NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
  34. uint8_t *input = (uint8_t *)[data bytes];
  35. uint8_t *output = (uint8_t *)[mutableData mutableBytes];
  36. for (NSUInteger i = 0; i < length; i += 3) {
  37. NSUInteger value = 0;
  38. for (NSUInteger j = i; j < (i + 3); j++) {
  39. value <<= 8;
  40. if (j < length) {
  41. value |= (0xFF & input[j]);
  42. }
  43. }
  44. static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  45. NSUInteger idx = (i / 3) * 4;
  46. output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
  47. output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
  48. output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '=';
  49. output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
  50. }
  51. return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
  52. }
  53. static NSString * const kAFCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*";
  54. static NSString * AFPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
  55. static NSString * const kAFCharactersToLeaveUnescapedInQueryStringPairKey = @"[].";
  56. return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
  57. }
  58. static NSString * AFPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
  59. return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
  60. }
  61. #pragma mark -
  62. @interface AFQueryStringPair : NSObject
  63. @property (readwrite, nonatomic, strong) id field;
  64. @property (readwrite, nonatomic, strong) id value;
  65. - (id)initWithField:(id)field value:(id)value;
  66. - (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding;
  67. @end
  68. @implementation AFQueryStringPair
  69. - (id)initWithField:(id)field value:(id)value {
  70. self = [super init];
  71. if (!self) {
  72. return nil;
  73. }
  74. self.field = field;
  75. self.value = value;
  76. return self;
  77. }
  78. - (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding {
  79. if (!self.value || [self.value isEqual:[NSNull null]]) {
  80. return AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding);
  81. } else {
  82. return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding), AFPercentEscapedQueryStringValueFromStringWithEncoding([self.value description], stringEncoding)];
  83. }
  84. }
  85. @end
  86. #pragma mark -
  87. extern NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
  88. extern NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
  89. static NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) {
  90. NSMutableArray *mutablePairs = [NSMutableArray array];
  91. for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
  92. [mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]];
  93. }
  94. return [mutablePairs componentsJoinedByString:@"&"];
  95. }
  96. NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
  97. return AFQueryStringPairsFromKeyAndValue(nil, dictionary);
  98. }
  99. NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
  100. NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
  101. NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];
  102. if ([value isKindOfClass:[NSDictionary class]]) {
  103. NSDictionary *dictionary = value;
  104. // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
  105. for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
  106. id nestedValue = [dictionary objectForKey:nestedKey];
  107. if (nestedValue) {
  108. [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
  109. }
  110. }
  111. } else if ([value isKindOfClass:[NSArray class]]) {
  112. NSArray *array = value;
  113. for (id nestedValue in array) {
  114. [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
  115. }
  116. } else if ([value isKindOfClass:[NSSet class]]) {
  117. NSSet *set = value;
  118. for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
  119. [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)];
  120. }
  121. } else {
  122. [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
  123. }
  124. return mutableQueryStringComponents;
  125. }
  126. #pragma mark -
  127. @interface AFStreamingMultipartFormData : NSObject <AFMultipartFormData>
  128. - (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
  129. stringEncoding:(NSStringEncoding)encoding;
  130. - (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
  131. @end
  132. #pragma mark -
  133. static NSArray * AFHTTPRequestSerializerObservedKeyPaths() {
  134. static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil;
  135. static dispatch_once_t onceToken;
  136. dispatch_once(&onceToken, ^{
  137. _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))];
  138. });
  139. return _AFHTTPRequestSerializerObservedKeyPaths;
  140. }
  141. static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext;
  142. @interface AFHTTPRequestSerializer ()
  143. @property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths;
  144. @property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders;
  145. @property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle;
  146. @property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization;
  147. @end
  148. @implementation AFHTTPRequestSerializer
  149. + (instancetype)serializer {
  150. return [[self alloc] init];
  151. }
  152. - (instancetype)init {
  153. self = [super init];
  154. if (!self) {
  155. return nil;
  156. }
  157. self.stringEncoding = NSUTF8StringEncoding;
  158. self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary];
  159. // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
  160. NSMutableArray *acceptLanguagesComponents = [NSMutableArray array];
  161. [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  162. float q = 1.0f - (idx * 0.1f);
  163. [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]];
  164. *stop = q <= 0.5f;
  165. }];
  166. [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"];
  167. NSString *userAgent = nil;
  168. #pragma clang diagnostic push
  169. #pragma clang diagnostic ignored "-Wgnu"
  170. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
  171. // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
  172. userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
  173. #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
  174. userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]];
  175. #endif
  176. #pragma clang diagnostic pop
  177. if (userAgent) {
  178. if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
  179. NSMutableString *mutableUserAgent = [userAgent mutableCopy];
  180. if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
  181. userAgent = mutableUserAgent;
  182. }
  183. }
  184. [self setValue:userAgent forHTTPHeaderField:@"User-Agent"];
  185. }
  186. // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
  187. self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
  188. self.mutableObservedChangedKeyPaths = [NSMutableSet set];
  189. for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
  190. if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
  191. [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
  192. }
  193. }
  194. return self;
  195. }
  196. - (void)dealloc {
  197. for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
  198. if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
  199. [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext];
  200. }
  201. }
  202. }
  203. #pragma mark -
  204. // Workarounds for crashing behavior using Key-Value Observing with XCTest
  205. // See https://github.com/AFNetworking/AFNetworking/issues/2523
  206. - (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess {
  207. [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
  208. _allowsCellularAccess = allowsCellularAccess;
  209. [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
  210. }
  211. - (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy {
  212. [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
  213. _cachePolicy = cachePolicy;
  214. [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
  215. }
  216. - (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies {
  217. [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
  218. _HTTPShouldHandleCookies = HTTPShouldHandleCookies;
  219. [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
  220. }
  221. - (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining {
  222. [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
  223. _HTTPShouldUsePipelining = HTTPShouldUsePipelining;
  224. [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
  225. }
  226. - (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType {
  227. [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
  228. _networkServiceType = networkServiceType;
  229. [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
  230. }
  231. - (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval {
  232. [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
  233. _timeoutInterval = timeoutInterval;
  234. [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
  235. }
  236. #pragma mark -
  237. - (NSDictionary *)HTTPRequestHeaders {
  238. return [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders];
  239. }
  240. - (void)setValue:(NSString *)value
  241. forHTTPHeaderField:(NSString *)field
  242. {
  243. [self.mutableHTTPRequestHeaders setValue:value forKey:field];
  244. }
  245. - (NSString *)valueForHTTPHeaderField:(NSString *)field {
  246. return [self.mutableHTTPRequestHeaders valueForKey:field];
  247. }
  248. - (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
  249. password:(NSString *)password
  250. {
  251. NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
  252. [self setValue:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)] forHTTPHeaderField:@"Authorization"];
  253. }
  254. - (void)setAuthorizationHeaderFieldWithToken:(NSString *)token {
  255. [self setValue:[NSString stringWithFormat:@"Token token=\"%@\"", token] forHTTPHeaderField:@"Authorization"];
  256. }
  257. - (void)clearAuthorizationHeader {
  258. [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"];
  259. }
  260. #pragma mark -
  261. - (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style {
  262. self.queryStringSerializationStyle = style;
  263. self.queryStringSerialization = nil;
  264. }
  265. - (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block {
  266. self.queryStringSerialization = block;
  267. }
  268. #pragma mark -
  269. - (NSMutableURLRequest *)requestWithMethod:(NSString *)method
  270. URLString:(NSString *)URLString
  271. parameters:(id)parameters
  272. {
  273. return [self requestWithMethod:method URLString:URLString parameters:parameters error:nil];
  274. }
  275. - (NSMutableURLRequest *)requestWithMethod:(NSString *)method
  276. URLString:(NSString *)URLString
  277. parameters:(id)parameters
  278. error:(NSError *__autoreleasing *)error
  279. {
  280. NSParameterAssert(method);
  281. NSParameterAssert(URLString);
  282. NSURL *url = [NSURL URLWithString:URLString];
  283. NSParameterAssert(url);
  284. NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
  285. mutableRequest.HTTPMethod = method;
  286. for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
  287. if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
  288. [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
  289. }
  290. }
  291. mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];
  292. return mutableRequest;
  293. }
  294. - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
  295. URLString:(NSString *)URLString
  296. parameters:(NSDictionary *)parameters
  297. constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
  298. {
  299. return [self multipartFormRequestWithMethod:method URLString:URLString parameters:parameters constructingBodyWithBlock:block error:nil];
  300. }
  301. - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
  302. URLString:(NSString *)URLString
  303. parameters:(NSDictionary *)parameters
  304. constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
  305. error:(NSError *__autoreleasing *)error
  306. {
  307. NSParameterAssert(method);
  308. NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
  309. NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error];
  310. __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];
  311. if (parameters) {
  312. for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
  313. NSData *data = nil;
  314. if ([pair.value isKindOfClass:[NSData class]]) {
  315. data = pair.value;
  316. } else if ([pair.value isEqual:[NSNull null]]) {
  317. data = [NSData data];
  318. } else {
  319. data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
  320. }
  321. if (data) {
  322. [formData appendPartWithFormData:data name:[pair.field description]];
  323. }
  324. }
  325. }
  326. if (block) {
  327. block(formData);
  328. }
  329. return [formData requestByFinalizingMultipartFormData];
  330. }
  331. - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
  332. writingStreamContentsToFile:(NSURL *)fileURL
  333. completionHandler:(void (^)(NSError *error))handler
  334. {
  335. NSParameterAssert(request.HTTPBodyStream);
  336. NSParameterAssert([fileURL isFileURL]);
  337. NSInputStream *inputStream = request.HTTPBodyStream;
  338. NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO];
  339. __block NSError *error = nil;
  340. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  341. [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  342. [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  343. [inputStream open];
  344. [outputStream open];
  345. while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) {
  346. uint8_t buffer[1024];
  347. NSInteger bytesRead = [inputStream read:buffer maxLength:1024];
  348. if (inputStream.streamError || bytesRead < 0) {
  349. error = inputStream.streamError;
  350. break;
  351. }
  352. NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead];
  353. if (outputStream.streamError || bytesWritten < 0) {
  354. error = outputStream.streamError;
  355. break;
  356. }
  357. if (bytesRead == 0 && bytesWritten == 0) {
  358. break;
  359. }
  360. }
  361. [outputStream close];
  362. [inputStream close];
  363. if (handler) {
  364. dispatch_async(dispatch_get_main_queue(), ^{
  365. handler(error);
  366. });
  367. }
  368. });
  369. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  370. mutableRequest.HTTPBodyStream = nil;
  371. return mutableRequest;
  372. }
  373. #pragma mark - AFURLRequestSerialization
  374. - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  375. withParameters:(id)parameters
  376. error:(NSError *__autoreleasing *)error
  377. {
  378. NSParameterAssert(request);
  379. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  380. [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  381. if (![request valueForHTTPHeaderField:field]) {
  382. [mutableRequest setValue:value forHTTPHeaderField:field];
  383. }
  384. }];
  385. if (parameters) {
  386. NSString *query = nil;
  387. if (self.queryStringSerialization) {
  388. NSError *serializationError;
  389. query = self.queryStringSerialization(request, parameters, &serializationError);
  390. if (serializationError) {
  391. if (error) {
  392. *error = serializationError;
  393. }
  394. return nil;
  395. }
  396. } else {
  397. switch (self.queryStringSerializationStyle) {
  398. case AFHTTPRequestQueryStringDefaultStyle:
  399. query = AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding);
  400. break;
  401. }
  402. }
  403. if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  404. mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
  405. } else {
  406. if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  407. [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  408. }
  409. [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
  410. }
  411. }
  412. return mutableRequest;
  413. }
  414. #pragma mark - NSKeyValueObserving
  415. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  416. if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) {
  417. return NO;
  418. }
  419. return [super automaticallyNotifiesObserversForKey:key];
  420. }
  421. - (void)observeValueForKeyPath:(NSString *)keyPath
  422. ofObject:(__unused id)object
  423. change:(NSDictionary *)change
  424. context:(void *)context
  425. {
  426. if (context == AFHTTPRequestSerializerObserverContext) {
  427. if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
  428. [self.mutableObservedChangedKeyPaths removeObject:keyPath];
  429. } else {
  430. [self.mutableObservedChangedKeyPaths addObject:keyPath];
  431. }
  432. }
  433. }
  434. #pragma mark - NSSecureCoding
  435. + (BOOL)supportsSecureCoding {
  436. return YES;
  437. }
  438. - (id)initWithCoder:(NSCoder *)decoder {
  439. self = [self init];
  440. if (!self) {
  441. return nil;
  442. }
  443. self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy];
  444. self.queryStringSerializationStyle = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue];
  445. return self;
  446. }
  447. - (void)encodeWithCoder:(NSCoder *)coder {
  448. [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))];
  449. [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))];
  450. }
  451. #pragma mark - NSCopying
  452. - (id)copyWithZone:(NSZone *)zone {
  453. AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
  454. serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
  455. serializer.queryStringSerializationStyle = self.queryStringSerializationStyle;
  456. serializer.queryStringSerialization = self.queryStringSerialization;
  457. return serializer;
  458. }
  459. @end
  460. #pragma mark -
  461. static NSString * AFCreateMultipartFormBoundary() {
  462. return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()];
  463. }
  464. static NSString * const kAFMultipartFormCRLF = @"\r\n";
  465. static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) {
  466. return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF];
  467. }
  468. static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) {
  469. return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
  470. }
  471. static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) {
  472. return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
  473. }
  474. static inline NSString * AFContentTypeForPathExtension(NSString *extension) {
  475. #ifdef __UTTYPE__
  476. NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
  477. NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
  478. if (!contentType) {
  479. return @"application/octet-stream";
  480. } else {
  481. return contentType;
  482. }
  483. #else
  484. #pragma unused (extension)
  485. return @"application/octet-stream";
  486. #endif
  487. }
  488. NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16;
  489. NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
  490. @interface AFHTTPBodyPart : NSObject
  491. @property (nonatomic, assign) NSStringEncoding stringEncoding;
  492. @property (nonatomic, strong) NSDictionary *headers;
  493. @property (nonatomic, copy) NSString *boundary;
  494. @property (nonatomic, strong) id body;
  495. @property (nonatomic, assign) unsigned long long bodyContentLength;
  496. @property (nonatomic, strong) NSInputStream *inputStream;
  497. @property (nonatomic, assign) BOOL hasInitialBoundary;
  498. @property (nonatomic, assign) BOOL hasFinalBoundary;
  499. @property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable;
  500. @property (readonly, nonatomic, assign) unsigned long long contentLength;
  501. - (NSInteger)read:(uint8_t *)buffer
  502. maxLength:(NSUInteger)length;
  503. @end
  504. @interface AFMultipartBodyStream : NSInputStream <NSStreamDelegate>
  505. @property (nonatomic, assign) NSUInteger numberOfBytesInPacket;
  506. @property (nonatomic, assign) NSTimeInterval delay;
  507. @property (nonatomic, strong) NSInputStream *inputStream;
  508. @property (readonly, nonatomic, assign) unsigned long long contentLength;
  509. @property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty;
  510. - (id)initWithStringEncoding:(NSStringEncoding)encoding;
  511. - (void)setInitialAndFinalBoundaries;
  512. - (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart;
  513. @end
  514. #pragma mark -
  515. @interface AFStreamingMultipartFormData ()
  516. @property (readwrite, nonatomic, copy) NSMutableURLRequest *request;
  517. @property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
  518. @property (readwrite, nonatomic, copy) NSString *boundary;
  519. @property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream;
  520. @end
  521. @implementation AFStreamingMultipartFormData
  522. - (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest
  523. stringEncoding:(NSStringEncoding)encoding
  524. {
  525. self = [super init];
  526. if (!self) {
  527. return nil;
  528. }
  529. self.request = urlRequest;
  530. self.stringEncoding = encoding;
  531. self.boundary = AFCreateMultipartFormBoundary();
  532. self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding];
  533. return self;
  534. }
  535. - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  536. name:(NSString *)name
  537. error:(NSError * __autoreleasing *)error
  538. {
  539. NSParameterAssert(fileURL);
  540. NSParameterAssert(name);
  541. NSString *fileName = [fileURL lastPathComponent];
  542. NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]);
  543. return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error];
  544. }
  545. - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  546. name:(NSString *)name
  547. fileName:(NSString *)fileName
  548. mimeType:(NSString *)mimeType
  549. error:(NSError * __autoreleasing *)error
  550. {
  551. NSParameterAssert(fileURL);
  552. NSParameterAssert(name);
  553. NSParameterAssert(fileName);
  554. NSParameterAssert(mimeType);
  555. if (![fileURL isFileURL]) {
  556. NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)};
  557. if (error) {
  558. *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
  559. }
  560. return NO;
  561. } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) {
  562. NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)};
  563. if (error) {
  564. *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
  565. }
  566. return NO;
  567. }
  568. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error];
  569. if (!fileAttributes) {
  570. return NO;
  571. }
  572. NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  573. [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
  574. [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
  575. AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
  576. bodyPart.stringEncoding = self.stringEncoding;
  577. bodyPart.headers = mutableHeaders;
  578. bodyPart.boundary = self.boundary;
  579. bodyPart.body = fileURL;
  580. bodyPart.bodyContentLength = [[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue];
  581. [self.bodyStream appendHTTPBodyPart:bodyPart];
  582. return YES;
  583. }
  584. - (void)appendPartWithInputStream:(NSInputStream *)inputStream
  585. name:(NSString *)name
  586. fileName:(NSString *)fileName
  587. length:(int64_t)length
  588. mimeType:(NSString *)mimeType
  589. {
  590. NSParameterAssert(name);
  591. NSParameterAssert(fileName);
  592. NSParameterAssert(mimeType);
  593. NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  594. [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
  595. [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
  596. AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
  597. bodyPart.stringEncoding = self.stringEncoding;
  598. bodyPart.headers = mutableHeaders;
  599. bodyPart.boundary = self.boundary;
  600. bodyPart.body = inputStream;
  601. bodyPart.bodyContentLength = (unsigned long long)length;
  602. [self.bodyStream appendHTTPBodyPart:bodyPart];
  603. }
  604. - (void)appendPartWithFileData:(NSData *)data
  605. name:(NSString *)name
  606. fileName:(NSString *)fileName
  607. mimeType:(NSString *)mimeType
  608. {
  609. NSParameterAssert(name);
  610. NSParameterAssert(fileName);
  611. NSParameterAssert(mimeType);
  612. NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  613. [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
  614. [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
  615. [self appendPartWithHeaders:mutableHeaders body:data];
  616. }
  617. - (void)appendPartWithFormData:(NSData *)data
  618. name:(NSString *)name
  619. {
  620. NSParameterAssert(name);
  621. NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  622. [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
  623. [self appendPartWithHeaders:mutableHeaders body:data];
  624. }
  625. - (void)appendPartWithHeaders:(NSDictionary *)headers
  626. body:(NSData *)body
  627. {
  628. NSParameterAssert(body);
  629. AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
  630. bodyPart.stringEncoding = self.stringEncoding;
  631. bodyPart.headers = headers;
  632. bodyPart.boundary = self.boundary;
  633. bodyPart.bodyContentLength = [body length];
  634. bodyPart.body = body;
  635. [self.bodyStream appendHTTPBodyPart:bodyPart];
  636. }
  637. - (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
  638. delay:(NSTimeInterval)delay
  639. {
  640. self.bodyStream.numberOfBytesInPacket = numberOfBytes;
  641. self.bodyStream.delay = delay;
  642. }
  643. - (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
  644. if ([self.bodyStream isEmpty]) {
  645. return self.request;
  646. }
  647. // Reset the initial and final boundaries to ensure correct Content-Length
  648. [self.bodyStream setInitialAndFinalBoundaries];
  649. [self.request setHTTPBodyStream:self.bodyStream];
  650. [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"];
  651. [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"];
  652. return self.request;
  653. }
  654. @end
  655. #pragma mark -
  656. @interface NSStream ()
  657. @property (readwrite) NSStreamStatus streamStatus;
  658. @property (readwrite, copy) NSError *streamError;
  659. @end
  660. @interface AFMultipartBodyStream () <NSCopying>
  661. @property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
  662. @property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts;
  663. @property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator;
  664. @property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart;
  665. @property (readwrite, nonatomic, strong) NSOutputStream *outputStream;
  666. @property (readwrite, nonatomic, strong) NSMutableData *buffer;
  667. @end
  668. @implementation AFMultipartBodyStream
  669. #pragma clang diagnostic push
  670. #pragma clang diagnostic ignored "-Wimplicit-atomic-properties"
  671. #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)
  672. @synthesize delegate;
  673. #endif
  674. @synthesize streamStatus;
  675. @synthesize streamError;
  676. #pragma clang diagnostic pop
  677. - (id)initWithStringEncoding:(NSStringEncoding)encoding {
  678. self = [super init];
  679. if (!self) {
  680. return nil;
  681. }
  682. self.stringEncoding = encoding;
  683. self.HTTPBodyParts = [NSMutableArray array];
  684. self.numberOfBytesInPacket = NSIntegerMax;
  685. return self;
  686. }
  687. - (void)setInitialAndFinalBoundaries {
  688. if ([self.HTTPBodyParts count] > 0) {
  689. for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
  690. bodyPart.hasInitialBoundary = NO;
  691. bodyPart.hasFinalBoundary = NO;
  692. }
  693. [[self.HTTPBodyParts objectAtIndex:0] setHasInitialBoundary:YES];
  694. [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES];
  695. }
  696. }
  697. - (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart {
  698. [self.HTTPBodyParts addObject:bodyPart];
  699. }
  700. - (BOOL)isEmpty {
  701. return [self.HTTPBodyParts count] == 0;
  702. }
  703. #pragma mark - NSInputStream
  704. - (NSInteger)read:(uint8_t *)buffer
  705. maxLength:(NSUInteger)length
  706. {
  707. if ([self streamStatus] == NSStreamStatusClosed) {
  708. return 0;
  709. }
  710. NSInteger totalNumberOfBytesRead = 0;
  711. #pragma clang diagnostic push
  712. #pragma clang diagnostic ignored "-Wgnu"
  713. while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) {
  714. if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
  715. if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
  716. break;
  717. }
  718. } else {
  719. NSUInteger maxLength = length - (NSUInteger)totalNumberOfBytesRead;
  720. NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength];
  721. if (numberOfBytesRead == -1) {
  722. self.streamError = self.currentHTTPBodyPart.inputStream.streamError;
  723. break;
  724. } else {
  725. totalNumberOfBytesRead += numberOfBytesRead;
  726. if (self.delay > 0.0f) {
  727. [NSThread sleepForTimeInterval:self.delay];
  728. }
  729. }
  730. }
  731. }
  732. #pragma clang diagnostic pop
  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. -(id)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. - (id)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. #pragma clang diagnostic push
  869. #pragma clang diagnostic ignored "-Wcovered-switch-default"
  870. switch (self.inputStream.streamStatus) {
  871. case NSStreamStatusNotOpen:
  872. case NSStreamStatusOpening:
  873. case NSStreamStatusOpen:
  874. case NSStreamStatusReading:
  875. case NSStreamStatusWriting:
  876. return YES;
  877. case NSStreamStatusAtEnd:
  878. case NSStreamStatusClosed:
  879. case NSStreamStatusError:
  880. default:
  881. return NO;
  882. }
  883. #pragma clang diagnostic pop
  884. }
  885. - (NSInteger)read:(uint8_t *)buffer
  886. maxLength:(NSUInteger)length
  887. {
  888. NSInteger totalNumberOfBytesRead = 0;
  889. if (_phase == AFEncapsulationBoundaryPhase) {
  890. NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
  891. totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  892. }
  893. if (_phase == AFHeaderPhase) {
  894. NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
  895. totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  896. }
  897. if (_phase == AFBodyPhase) {
  898. NSInteger numberOfBytesRead = 0;
  899. numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  900. if (numberOfBytesRead == -1) {
  901. return -1;
  902. } else {
  903. totalNumberOfBytesRead += numberOfBytesRead;
  904. if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) {
  905. [self transitionToNextPhase];
  906. }
  907. }
  908. }
  909. if (_phase == AFFinalBoundaryPhase) {
  910. NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
  911. totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  912. }
  913. return totalNumberOfBytesRead;
  914. }
  915. - (NSInteger)readData:(NSData *)data
  916. intoBuffer:(uint8_t *)buffer
  917. maxLength:(NSUInteger)length
  918. {
  919. #pragma clang diagnostic push
  920. #pragma clang diagnostic ignored "-Wgnu"
  921. NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length));
  922. [data getBytes:buffer range:range];
  923. #pragma clang diagnostic pop
  924. _phaseReadOffset += range.length;
  925. if (((NSUInteger)_phaseReadOffset) >= [data length]) {
  926. [self transitionToNextPhase];
  927. }
  928. return (NSInteger)range.length;
  929. }
  930. - (BOOL)transitionToNextPhase {
  931. if (![[NSThread currentThread] isMainThread]) {
  932. dispatch_sync(dispatch_get_main_queue(), ^{
  933. [self transitionToNextPhase];
  934. });
  935. return YES;
  936. }
  937. #pragma clang diagnostic push
  938. #pragma clang diagnostic ignored "-Wcovered-switch-default"
  939. switch (_phase) {
  940. case AFEncapsulationBoundaryPhase:
  941. _phase = AFHeaderPhase;
  942. break;
  943. case AFHeaderPhase:
  944. [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  945. [self.inputStream open];
  946. _phase = AFBodyPhase;
  947. break;
  948. case AFBodyPhase:
  949. [self.inputStream close];
  950. _phase = AFFinalBoundaryPhase;
  951. break;
  952. case AFFinalBoundaryPhase:
  953. default:
  954. _phase = AFEncapsulationBoundaryPhase;
  955. break;
  956. }
  957. _phaseReadOffset = 0;
  958. #pragma clang diagnostic pop
  959. return YES;
  960. }
  961. #pragma mark - NSCopying
  962. - (id)copyWithZone:(NSZone *)zone {
  963. AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
  964. bodyPart.stringEncoding = self.stringEncoding;
  965. bodyPart.headers = self.headers;
  966. bodyPart.bodyContentLength = self.bodyContentLength;
  967. bodyPart.body = self.body;
  968. bodyPart.boundary = self.boundary;
  969. return bodyPart;
  970. }
  971. @end
  972. #pragma mark -
  973. @implementation AFJSONRequestSerializer
  974. + (instancetype)serializer {
  975. return [self serializerWithWritingOptions:(NSJSONWritingOptions)0];
  976. }
  977. + (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
  978. {
  979. AFJSONRequestSerializer *serializer = [[self alloc] init];
  980. serializer.writingOptions = writingOptions;
  981. return serializer;
  982. }
  983. #pragma mark - AFURLRequestSerialization
  984. - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  985. withParameters:(id)parameters
  986. error:(NSError *__autoreleasing *)error
  987. {
  988. NSParameterAssert(request);
  989. if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  990. return [super requestBySerializingRequest:request withParameters:parameters error:error];
  991. }
  992. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  993. [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  994. if (![request valueForHTTPHeaderField:field]) {
  995. [mutableRequest setValue:value forHTTPHeaderField:field];
  996. }
  997. }];
  998. if (parameters) {
  999. if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  1000. [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  1001. }
  1002. [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
  1003. }
  1004. return mutableRequest;
  1005. }
  1006. #pragma mark - NSSecureCoding
  1007. - (id)initWithCoder:(NSCoder *)decoder {
  1008. self = [super initWithCoder:decoder];
  1009. if (!self) {
  1010. return nil;
  1011. }
  1012. self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue];
  1013. return self;
  1014. }
  1015. - (void)encodeWithCoder:(NSCoder *)coder {
  1016. [super encodeWithCoder:coder];
  1017. [coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))];
  1018. }
  1019. #pragma mark - NSCopying
  1020. - (id)copyWithZone:(NSZone *)zone {
  1021. AFJSONRequestSerializer *serializer = [super copyWithZone:zone];
  1022. serializer.writingOptions = self.writingOptions;
  1023. return serializer;
  1024. }
  1025. @end
  1026. #pragma mark -
  1027. @implementation AFPropertyListRequestSerializer
  1028. + (instancetype)serializer {
  1029. return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0];
  1030. }
  1031. + (instancetype)serializerWithFormat:(NSPropertyListFormat)format
  1032. writeOptions:(NSPropertyListWriteOptions)writeOptions
  1033. {
  1034. AFPropertyListRequestSerializer *serializer = [[self alloc] init];
  1035. serializer.format = format;
  1036. serializer.writeOptions = writeOptions;
  1037. return serializer;
  1038. }
  1039. #pragma mark - AFURLRequestSerializer
  1040. - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  1041. withParameters:(id)parameters
  1042. error:(NSError *__autoreleasing *)error
  1043. {
  1044. NSParameterAssert(request);
  1045. if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  1046. return [super requestBySerializingRequest:request withParameters:parameters error:error];
  1047. }
  1048. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  1049. [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  1050. if (![request valueForHTTPHeaderField:field]) {
  1051. [mutableRequest setValue:value forHTTPHeaderField:field];
  1052. }
  1053. }];
  1054. if (parameters) {
  1055. if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  1056. [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"];
  1057. }
  1058. [mutableRequest setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]];
  1059. }
  1060. return mutableRequest;
  1061. }
  1062. #pragma mark - NSSecureCoding
  1063. - (id)initWithCoder:(NSCoder *)decoder {
  1064. self = [super initWithCoder:decoder];
  1065. if (!self) {
  1066. return nil;
  1067. }
  1068. self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
  1069. self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue];
  1070. return self;
  1071. }
  1072. - (void)encodeWithCoder:(NSCoder *)coder {
  1073. [super encodeWithCoder:coder];
  1074. [coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))];
  1075. [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))];
  1076. }
  1077. #pragma mark - NSCopying
  1078. - (id)copyWithZone:(NSZone *)zone {
  1079. AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone];
  1080. serializer.format = self.format;
  1081. serializer.writeOptions = self.writeOptions;
  1082. return serializer;
  1083. }
  1084. @end