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