AFURLRequestSerialization.m 52 KB

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