Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

AFURLRequestSerialization.m 49KB

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