AFURLRequestSerialization.m 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  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 self.mutableObservedChangedKeyPaths) {
  296. [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
  297. }
  298. mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];
  299. return mutableRequest;
  300. }
  301. - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
  302. URLString:(NSString *)URLString
  303. parameters:(NSDictionary *)parameters
  304. constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
  305. error:(NSError *__autoreleasing *)error
  306. {
  307. NSParameterAssert(method);
  308. NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
  309. NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error];
  310. __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];
  311. if (parameters) {
  312. for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
  313. NSData *data = nil;
  314. if ([pair.value isKindOfClass:[NSData class]]) {
  315. data = pair.value;
  316. } else if ([pair.value isEqual:[NSNull null]]) {
  317. data = [NSData data];
  318. } else {
  319. data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
  320. }
  321. if (data) {
  322. [formData appendPartWithFormData:data name:[pair.field description]];
  323. }
  324. }
  325. }
  326. if (block) {
  327. block(formData);
  328. }
  329. return [formData requestByFinalizingMultipartFormData];
  330. }
  331. - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
  332. writingStreamContentsToFile:(NSURL *)fileURL
  333. completionHandler:(void (^)(NSError *error))handler
  334. {
  335. NSParameterAssert(request.HTTPBodyStream);
  336. NSParameterAssert([fileURL isFileURL]);
  337. NSInputStream *inputStream = request.HTTPBodyStream;
  338. NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO];
  339. __block NSError *error = nil;
  340. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  341. [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  342. [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  343. [inputStream open];
  344. [outputStream open];
  345. while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) {
  346. uint8_t buffer[1024];
  347. NSInteger bytesRead = [inputStream read:buffer maxLength:1024];
  348. if (inputStream.streamError || bytesRead < 0) {
  349. error = inputStream.streamError;
  350. break;
  351. }
  352. NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead];
  353. if (outputStream.streamError || bytesWritten < 0) {
  354. error = outputStream.streamError;
  355. break;
  356. }
  357. if (bytesRead == 0 && bytesWritten == 0) {
  358. break;
  359. }
  360. }
  361. [outputStream close];
  362. [inputStream close];
  363. if (handler) {
  364. dispatch_async(dispatch_get_main_queue(), ^{
  365. handler(error);
  366. });
  367. }
  368. });
  369. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  370. mutableRequest.HTTPBodyStream = nil;
  371. return mutableRequest;
  372. }
  373. #pragma mark - AFURLRequestSerialization
  374. - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  375. withParameters:(id)parameters
  376. error:(NSError *__autoreleasing *)error
  377. {
  378. NSParameterAssert(request);
  379. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  380. [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  381. if (![request valueForHTTPHeaderField:field]) {
  382. [mutableRequest setValue:value forHTTPHeaderField:field];
  383. }
  384. }];
  385. NSString *query = nil;
  386. if (parameters) {
  387. if (self.queryStringSerialization) {
  388. NSError *serializationError;
  389. query = self.queryStringSerialization(request, parameters, &serializationError);
  390. if (serializationError) {
  391. if (error) {
  392. *error = serializationError;
  393. }
  394. return nil;
  395. }
  396. } else {
  397. switch (self.queryStringSerializationStyle) {
  398. case AFHTTPRequestQueryStringDefaultStyle:
  399. query = AFQueryStringFromParameters(parameters);
  400. break;
  401. }
  402. }
  403. }
  404. if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  405. if (query && query.length > 0) {
  406. mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
  407. }
  408. } else {
  409. // #2864: an empty string is a valid x-www-form-urlencoded payload
  410. if (!query) {
  411. query = @"";
  412. }
  413. if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  414. [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  415. }
  416. [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
  417. }
  418. return mutableRequest;
  419. }
  420. #pragma mark - NSKeyValueObserving
  421. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  422. if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) {
  423. return NO;
  424. }
  425. return [super automaticallyNotifiesObserversForKey:key];
  426. }
  427. - (void)observeValueForKeyPath:(NSString *)keyPath
  428. ofObject:(__unused id)object
  429. change:(NSDictionary *)change
  430. context:(void *)context
  431. {
  432. if (context == AFHTTPRequestSerializerObserverContext) {
  433. if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
  434. [self.mutableObservedChangedKeyPaths removeObject:keyPath];
  435. } else {
  436. [self.mutableObservedChangedKeyPaths addObject:keyPath];
  437. }
  438. }
  439. }
  440. #pragma mark - NSSecureCoding
  441. + (BOOL)supportsSecureCoding {
  442. return YES;
  443. }
  444. - (instancetype)initWithCoder:(NSCoder *)decoder {
  445. self = [self init];
  446. if (!self) {
  447. return nil;
  448. }
  449. self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy];
  450. self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue];
  451. return self;
  452. }
  453. - (void)encodeWithCoder:(NSCoder *)coder {
  454. dispatch_sync(self.requestHeaderModificationQueue, ^{
  455. [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))];
  456. });
  457. [coder encodeObject:@(self.queryStringSerializationStyle) forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))];
  458. }
  459. #pragma mark - NSCopying
  460. - (instancetype)copyWithZone:(NSZone *)zone {
  461. AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
  462. dispatch_sync(self.requestHeaderModificationQueue, ^{
  463. serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
  464. });
  465. serializer.queryStringSerializationStyle = self.queryStringSerializationStyle;
  466. serializer.queryStringSerialization = self.queryStringSerialization;
  467. return serializer;
  468. }
  469. @end
  470. #pragma mark -
  471. static NSString * AFCreateMultipartFormBoundary() {
  472. return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()];
  473. }
  474. static NSString * const kAFMultipartFormCRLF = @"\r\n";
  475. static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) {
  476. return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF];
  477. }
  478. static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) {
  479. return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
  480. }
  481. static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) {
  482. return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
  483. }
  484. static inline NSString * AFContentTypeForPathExtension(NSString *extension) {
  485. NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
  486. NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
  487. if (!contentType) {
  488. return @"application/octet-stream";
  489. } else {
  490. return contentType;
  491. }
  492. }
  493. NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16;
  494. NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
  495. @interface AFHTTPBodyPart : NSObject
  496. @property (nonatomic, assign) NSStringEncoding stringEncoding;
  497. @property (nonatomic, strong) NSDictionary *headers;
  498. @property (nonatomic, copy) NSString *boundary;
  499. @property (nonatomic, strong) id body;
  500. @property (nonatomic, assign) unsigned long long bodyContentLength;
  501. @property (nonatomic, strong) NSInputStream *inputStream;
  502. @property (nonatomic, assign) BOOL hasInitialBoundary;
  503. @property (nonatomic, assign) BOOL hasFinalBoundary;
  504. @property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable;
  505. @property (readonly, nonatomic, assign) unsigned long long contentLength;
  506. - (NSInteger)read:(uint8_t *)buffer
  507. maxLength:(NSUInteger)length;
  508. @end
  509. @interface AFMultipartBodyStream : NSInputStream <NSStreamDelegate>
  510. @property (nonatomic, assign) NSUInteger numberOfBytesInPacket;
  511. @property (nonatomic, assign) NSTimeInterval delay;
  512. @property (nonatomic, strong) NSInputStream *inputStream;
  513. @property (readonly, nonatomic, assign) unsigned long long contentLength;
  514. @property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty;
  515. - (instancetype)initWithStringEncoding:(NSStringEncoding)encoding;
  516. - (void)setInitialAndFinalBoundaries;
  517. - (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart;
  518. @end
  519. #pragma mark -
  520. @interface AFStreamingMultipartFormData ()
  521. @property (readwrite, nonatomic, copy) NSMutableURLRequest *request;
  522. @property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
  523. @property (readwrite, nonatomic, copy) NSString *boundary;
  524. @property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream;
  525. @end
  526. @implementation AFStreamingMultipartFormData
  527. - (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
  528. stringEncoding:(NSStringEncoding)encoding
  529. {
  530. self = [super init];
  531. if (!self) {
  532. return nil;
  533. }
  534. self.request = urlRequest;
  535. self.stringEncoding = encoding;
  536. self.boundary = AFCreateMultipartFormBoundary();
  537. self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding];
  538. return self;
  539. }
  540. - (void)setRequest:(NSMutableURLRequest *)request
  541. {
  542. _request = [request mutableCopy];
  543. }
  544. - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  545. name:(NSString *)name
  546. error:(NSError * __autoreleasing *)error
  547. {
  548. NSParameterAssert(fileURL);
  549. NSParameterAssert(name);
  550. NSString *fileName = [fileURL lastPathComponent];
  551. NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]);
  552. return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error];
  553. }
  554. - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  555. name:(NSString *)name
  556. fileName:(NSString *)fileName
  557. mimeType:(NSString *)mimeType
  558. error:(NSError * __autoreleasing *)error
  559. {
  560. NSParameterAssert(fileURL);
  561. NSParameterAssert(name);
  562. NSParameterAssert(fileName);
  563. NSParameterAssert(mimeType);
  564. if (![fileURL isFileURL]) {
  565. NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)};
  566. if (error) {
  567. *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
  568. }
  569. return NO;
  570. } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) {
  571. NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)};
  572. if (error) {
  573. *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
  574. }
  575. return NO;
  576. }
  577. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error];
  578. if (!fileAttributes) {
  579. return NO;
  580. }
  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 = fileURL;
  589. bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue];
  590. [self.bodyStream appendHTTPBodyPart:bodyPart];
  591. return YES;
  592. }
  593. - (void)appendPartWithInputStream:(NSInputStream *)inputStream
  594. name:(NSString *)name
  595. fileName:(NSString *)fileName
  596. length:(int64_t)length
  597. mimeType:(NSString *)mimeType
  598. {
  599. NSParameterAssert(name);
  600. NSParameterAssert(fileName);
  601. NSParameterAssert(mimeType);
  602. NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  603. [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
  604. [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
  605. AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
  606. bodyPart.stringEncoding = self.stringEncoding;
  607. bodyPart.headers = mutableHeaders;
  608. bodyPart.boundary = self.boundary;
  609. bodyPart.body = inputStream;
  610. bodyPart.bodyContentLength = (unsigned long long)length;
  611. [self.bodyStream appendHTTPBodyPart:bodyPart];
  612. }
  613. - (void)appendPartWithFileData:(NSData *)data
  614. name:(NSString *)name
  615. fileName:(NSString *)fileName
  616. mimeType:(NSString *)mimeType
  617. {
  618. NSParameterAssert(name);
  619. NSParameterAssert(fileName);
  620. NSParameterAssert(mimeType);
  621. NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  622. [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
  623. [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
  624. [self appendPartWithHeaders:mutableHeaders body:data];
  625. }
  626. - (void)appendPartWithFormData:(NSData *)data
  627. name:(NSString *)name
  628. {
  629. NSParameterAssert(name);
  630. NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  631. [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
  632. [self appendPartWithHeaders:mutableHeaders body:data];
  633. }
  634. - (void)appendPartWithHeaders:(NSDictionary *)headers
  635. body:(NSData *)body
  636. {
  637. NSParameterAssert(body);
  638. AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
  639. bodyPart.stringEncoding = self.stringEncoding;
  640. bodyPart.headers = headers;
  641. bodyPart.boundary = self.boundary;
  642. bodyPart.bodyContentLength = [body length];
  643. bodyPart.body = body;
  644. [self.bodyStream appendHTTPBodyPart:bodyPart];
  645. }
  646. - (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
  647. delay:(NSTimeInterval)delay
  648. {
  649. self.bodyStream.numberOfBytesInPacket = numberOfBytes;
  650. self.bodyStream.delay = delay;
  651. }
  652. - (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
  653. if ([self.bodyStream isEmpty]) {
  654. return self.request;
  655. }
  656. // Reset the initial and final boundaries to ensure correct Content-Length
  657. [self.bodyStream setInitialAndFinalBoundaries];
  658. [self.request setHTTPBodyStream:self.bodyStream];
  659. [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"];
  660. [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"];
  661. return self.request;
  662. }
  663. @end
  664. #pragma mark -
  665. @interface NSStream ()
  666. @property (readwrite) NSStreamStatus streamStatus;
  667. @property (readwrite, copy) NSError *streamError;
  668. @end
  669. @interface AFMultipartBodyStream () <NSCopying>
  670. @property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
  671. @property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts;
  672. @property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator;
  673. @property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart;
  674. @property (readwrite, nonatomic, strong) NSOutputStream *outputStream;
  675. @property (readwrite, nonatomic, strong) NSMutableData *buffer;
  676. @end
  677. @implementation AFMultipartBodyStream
  678. #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)
  679. @synthesize delegate;
  680. #endif
  681. @synthesize streamStatus;
  682. @synthesize streamError;
  683. - (instancetype)initWithStringEncoding:(NSStringEncoding)encoding {
  684. self = [super init];
  685. if (!self) {
  686. return nil;
  687. }
  688. self.stringEncoding = encoding;
  689. self.HTTPBodyParts = [NSMutableArray array];
  690. self.numberOfBytesInPacket = NSIntegerMax;
  691. return self;
  692. }
  693. - (void)setInitialAndFinalBoundaries {
  694. if ([self.HTTPBodyParts count] > 0) {
  695. for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
  696. bodyPart.hasInitialBoundary = NO;
  697. bodyPart.hasFinalBoundary = NO;
  698. }
  699. [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES];
  700. [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES];
  701. }
  702. }
  703. - (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart {
  704. [self.HTTPBodyParts addObject:bodyPart];
  705. }
  706. - (BOOL)isEmpty {
  707. return [self.HTTPBodyParts count] == 0;
  708. }
  709. #pragma mark - NSInputStream
  710. - (NSInteger)read:(uint8_t *)buffer
  711. maxLength:(NSUInteger)length
  712. {
  713. if ([self streamStatus] == NSStreamStatusClosed) {
  714. return 0;
  715. }
  716. NSInteger totalNumberOfBytesRead = 0;
  717. while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) {
  718. if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
  719. if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
  720. break;
  721. }
  722. } else {
  723. NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead;
  724. NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength];
  725. if (numberOfBytesRead == -1) {
  726. self.streamError = self.currentHTTPBodyPart.inputStream.streamError;
  727. break;
  728. } else {
  729. totalNumberOfBytesRead += numberOfBytesRead;
  730. if (self.delay > 0.0f) {
  731. [NSThread sleepForTimeInterval:self.delay];
  732. }
  733. }
  734. }
  735. }
  736. return totalNumberOfBytesRead;
  737. }
  738. - (BOOL)getBuffer:(__unused uint8_t **)buffer
  739. length:(__unused NSUInteger *)len
  740. {
  741. return NO;
  742. }
  743. - (BOOL)hasBytesAvailable {
  744. return [self streamStatus] == NSStreamStatusOpen;
  745. }
  746. #pragma mark - NSStream
  747. - (void)open {
  748. if (self.streamStatus == NSStreamStatusOpen) {
  749. return;
  750. }
  751. self.streamStatus = NSStreamStatusOpen;
  752. [self setInitialAndFinalBoundaries];
  753. self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator];
  754. }
  755. - (void)close {
  756. self.streamStatus = NSStreamStatusClosed;
  757. }
  758. - (id)propertyForKey:(__unused NSString *)key {
  759. return nil;
  760. }
  761. - (BOOL)setProperty:(__unused id)property
  762. forKey:(__unused NSString *)key
  763. {
  764. return NO;
  765. }
  766. - (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
  767. forMode:(__unused NSString *)mode
  768. {}
  769. - (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
  770. forMode:(__unused NSString *)mode
  771. {}
  772. - (unsigned long long)contentLength {
  773. unsigned long long length = 0;
  774. for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
  775. length += [bodyPart contentLength];
  776. }
  777. return length;
  778. }
  779. #pragma mark - Undocumented CFReadStream Bridged Methods
  780. - (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop
  781. forMode:(__unused CFStringRef)aMode
  782. {}
  783. - (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop
  784. forMode:(__unused CFStringRef)aMode
  785. {}
  786. - (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags
  787. callback:(__unused CFReadStreamClientCallBack)inCallback
  788. context:(__unused CFStreamClientContext *)inContext {
  789. return NO;
  790. }
  791. #pragma mark - NSCopying
  792. - (instancetype)copyWithZone:(NSZone *)zone {
  793. AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding];
  794. for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
  795. [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]];
  796. }
  797. [bodyStreamCopy setInitialAndFinalBoundaries];
  798. return bodyStreamCopy;
  799. }
  800. @end
  801. #pragma mark -
  802. typedef enum {
  803. AFEncapsulationBoundaryPhase = 1,
  804. AFHeaderPhase = 2,
  805. AFBodyPhase = 3,
  806. AFFinalBoundaryPhase = 4,
  807. } AFHTTPBodyPartReadPhase;
  808. @interface AFHTTPBodyPart () <NSCopying> {
  809. AFHTTPBodyPartReadPhase _phase;
  810. NSInputStream *_inputStream;
  811. unsigned long long _phaseReadOffset;
  812. }
  813. - (BOOL)transitionToNextPhase;
  814. - (NSInteger)readData:(NSData *)data
  815. intoBuffer:(uint8_t *)buffer
  816. maxLength:(NSUInteger)length;
  817. @end
  818. @implementation AFHTTPBodyPart
  819. - (instancetype)init {
  820. self = [super init];
  821. if (!self) {
  822. return nil;
  823. }
  824. [self transitionToNextPhase];
  825. return self;
  826. }
  827. - (void)dealloc {
  828. if (_inputStream) {
  829. [_inputStream close];
  830. _inputStream = nil;
  831. }
  832. }
  833. - (NSInputStream *)inputStream {
  834. if (!_inputStream) {
  835. if ([self.body isKindOfClass:[NSData class]]) {
  836. _inputStream = [NSInputStream inputStreamWithData:self.body];
  837. } else if ([self.body isKindOfClass:[NSURL class]]) {
  838. _inputStream = [NSInputStream inputStreamWithURL:self.body];
  839. } else if ([self.body isKindOfClass:[NSInputStream class]]) {
  840. _inputStream = self.body;
  841. } else {
  842. _inputStream = [NSInputStream inputStreamWithData:[NSData data]];
  843. }
  844. }
  845. return _inputStream;
  846. }
  847. - (NSString *)stringForHeaders {
  848. NSMutableString *headerString = [NSMutableString string];
  849. for (NSString *field in [self.headers allKeys]) {
  850. [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]];
  851. }
  852. [headerString appendString:kAFMultipartFormCRLF];
  853. return [NSString stringWithString:headerString];
  854. }
  855. - (unsigned long long)contentLength {
  856. unsigned long long length = 0;
  857. NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
  858. length += [encapsulationBoundaryData length];
  859. NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
  860. length += [headersData length];
  861. length += _bodyContentLength;
  862. NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
  863. length += [closingBoundaryData length];
  864. return length;
  865. }
  866. - (BOOL)hasBytesAvailable {
  867. // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer
  868. if (_phase == AFFinalBoundaryPhase) {
  869. return YES;
  870. }
  871. switch (self.inputStream.streamStatus) {
  872. case NSStreamStatusNotOpen:
  873. case NSStreamStatusOpening:
  874. case NSStreamStatusOpen:
  875. case NSStreamStatusReading:
  876. case NSStreamStatusWriting:
  877. return YES;
  878. case NSStreamStatusAtEnd:
  879. case NSStreamStatusClosed:
  880. case NSStreamStatusError:
  881. default:
  882. return NO;
  883. }
  884. }
  885. - (NSInteger)read:(uint8_t *)buffer
  886. maxLength:(NSUInteger)length
  887. {
  888. NSInteger totalNumberOfBytesRead = 0;
  889. if (_phase == AFEncapsulationBoundaryPhase) {
  890. NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
  891. totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  892. }
  893. if (_phase == AFHeaderPhase) {
  894. NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
  895. totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  896. }
  897. if (_phase == AFBodyPhase) {
  898. NSInteger numberOfBytesRead = 0;
  899. numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  900. if (numberOfBytesRead == -1) {
  901. return -1;
  902. } else {
  903. totalNumberOfBytesRead += numberOfBytesRead;
  904. if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) {
  905. [self transitionToNextPhase];
  906. }
  907. }
  908. }
  909. if (_phase == AFFinalBoundaryPhase) {
  910. NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
  911. totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  912. }
  913. return totalNumberOfBytesRead;
  914. }
  915. - (NSInteger)readData:(NSData *)data
  916. intoBuffer:(uint8_t *)buffer
  917. maxLength:(NSUInteger)length
  918. {
  919. NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length));
  920. [data getBytes:buffer range:range];
  921. _phaseReadOffset += range.length;
  922. if (((NSUInteger)_phaseReadOffset) >= [data length]) {
  923. [self transitionToNextPhase];
  924. }
  925. return (NSInteger)range.length;
  926. }
  927. - (BOOL)transitionToNextPhase {
  928. if (![[NSThread currentThread] isMainThread]) {
  929. dispatch_sync(dispatch_get_main_queue(), ^{
  930. [self transitionToNextPhase];
  931. });
  932. return YES;
  933. }
  934. switch (_phase) {
  935. case AFEncapsulationBoundaryPhase:
  936. _phase = AFHeaderPhase;
  937. break;
  938. case AFHeaderPhase:
  939. [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  940. [self.inputStream open];
  941. _phase = AFBodyPhase;
  942. break;
  943. case AFBodyPhase:
  944. [self.inputStream close];
  945. _phase = AFFinalBoundaryPhase;
  946. break;
  947. case AFFinalBoundaryPhase:
  948. default:
  949. _phase = AFEncapsulationBoundaryPhase;
  950. break;
  951. }
  952. _phaseReadOffset = 0;
  953. return YES;
  954. }
  955. #pragma mark - NSCopying
  956. - (instancetype)copyWithZone:(NSZone *)zone {
  957. AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
  958. bodyPart.stringEncoding = self.stringEncoding;
  959. bodyPart.headers = self.headers;
  960. bodyPart.bodyContentLength = self.bodyContentLength;
  961. bodyPart.body = self.body;
  962. bodyPart.boundary = self.boundary;
  963. return bodyPart;
  964. }
  965. @end
  966. #pragma mark -
  967. @implementation AFJSONRequestSerializer
  968. + (instancetype)serializer {
  969. return [self serializerWithWritingOptions:(NSJSONWritingOptions)0];
  970. }
  971. + (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
  972. {
  973. AFJSONRequestSerializer *serializer = [[self alloc] init];
  974. serializer.writingOptions = writingOptions;
  975. return serializer;
  976. }
  977. #pragma mark - AFURLRequestSerialization
  978. - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  979. withParameters:(id)parameters
  980. error:(NSError *__autoreleasing *)error
  981. {
  982. NSParameterAssert(request);
  983. if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  984. return [super requestBySerializingRequest:request withParameters:parameters error:error];
  985. }
  986. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  987. [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  988. if (![request valueForHTTPHeaderField:field]) {
  989. [mutableRequest setValue:value forHTTPHeaderField:field];
  990. }
  991. }];
  992. if (parameters) {
  993. if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  994. [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  995. }
  996. if (![NSJSONSerialization isValidJSONObject:parameters]) {
  997. if (error) {
  998. NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)};
  999. *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
  1000. }
  1001. return nil;
  1002. }
  1003. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error];
  1004. if (!jsonData) {
  1005. return nil;
  1006. }
  1007. [mutableRequest setHTTPBody:jsonData];
  1008. }
  1009. return mutableRequest;
  1010. }
  1011. #pragma mark - NSSecureCoding
  1012. - (instancetype)initWithCoder:(NSCoder *)decoder {
  1013. self = [super initWithCoder:decoder];
  1014. if (!self) {
  1015. return nil;
  1016. }
  1017. self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue];
  1018. return self;
  1019. }
  1020. - (void)encodeWithCoder:(NSCoder *)coder {
  1021. [super encodeWithCoder:coder];
  1022. [coder encodeObject:@(self.writingOptions) forKey:NSStringFromSelector(@selector(writingOptions))];
  1023. }
  1024. #pragma mark - NSCopying
  1025. - (instancetype)copyWithZone:(NSZone *)zone {
  1026. AFJSONRequestSerializer *serializer = [super copyWithZone:zone];
  1027. serializer.writingOptions = self.writingOptions;
  1028. return serializer;
  1029. }
  1030. @end
  1031. #pragma mark -
  1032. @implementation AFPropertyListRequestSerializer
  1033. + (instancetype)serializer {
  1034. return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0];
  1035. }
  1036. + (instancetype)serializerWithFormat:(NSPropertyListFormat)format
  1037. writeOptions:(NSPropertyListWriteOptions)writeOptions
  1038. {
  1039. AFPropertyListRequestSerializer *serializer = [[self alloc] init];
  1040. serializer.format = format;
  1041. serializer.writeOptions = writeOptions;
  1042. return serializer;
  1043. }
  1044. #pragma mark - AFURLRequestSerializer
  1045. - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  1046. withParameters:(id)parameters
  1047. error:(NSError *__autoreleasing *)error
  1048. {
  1049. NSParameterAssert(request);
  1050. if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  1051. return [super requestBySerializingRequest:request withParameters:parameters error:error];
  1052. }
  1053. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  1054. [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  1055. if (![request valueForHTTPHeaderField:field]) {
  1056. [mutableRequest setValue:value forHTTPHeaderField:field];
  1057. }
  1058. }];
  1059. if (parameters) {
  1060. if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  1061. [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"];
  1062. }
  1063. NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error];
  1064. if (!plistData) {
  1065. return nil;
  1066. }
  1067. [mutableRequest setHTTPBody:plistData];
  1068. }
  1069. return mutableRequest;
  1070. }
  1071. #pragma mark - NSSecureCoding
  1072. - (instancetype)initWithCoder:(NSCoder *)decoder {
  1073. self = [super initWithCoder:decoder];
  1074. if (!self) {
  1075. return nil;
  1076. }
  1077. self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
  1078. self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue];
  1079. return self;
  1080. }
  1081. - (void)encodeWithCoder:(NSCoder *)coder {
  1082. [super encodeWithCoder:coder];
  1083. [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
  1084. [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))];
  1085. }
  1086. #pragma mark - NSCopying
  1087. - (instancetype)copyWithZone:(NSZone *)zone {
  1088. AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone];
  1089. serializer.format = self.format;
  1090. serializer.writeOptions = self.writeOptions;
  1091. return serializer;
  1092. }
  1093. @end