AFURLRequestSerialization.m 50 KB

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