AFURLRequestSerialization.m 51 KB

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