AFURLRequestSerialization.m 50 KB

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