AFURLRequestSerialization.m 51 KB

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