AFHTTPSessionManager.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. // AFHTTPSessionManager.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 "AFHTTPSessionManager.h"
  22. #import "AFURLRequestSerialization.h"
  23. #import "AFURLResponseSerialization.h"
  24. #import <Availability.h>
  25. #import <TargetConditionals.h>
  26. #import <Security/Security.h>
  27. #import <netinet/in.h>
  28. #import <netinet6/in6.h>
  29. #import <arpa/inet.h>
  30. #import <ifaddrs.h>
  31. #import <netdb.h>
  32. #if TARGET_OS_IOS || TARGET_OS_TV
  33. #import <UIKit/UIKit.h>
  34. #elif TARGET_OS_WATCH
  35. #import <WatchKit/WatchKit.h>
  36. #endif
  37. @interface AFHTTPSessionManager ()
  38. @property (readwrite, nonatomic, strong) NSURL *baseURL;
  39. @end
  40. @implementation AFHTTPSessionManager
  41. @dynamic responseSerializer;
  42. + (instancetype)manager {
  43. return [[[self class] alloc] initWithBaseURL:nil];
  44. }
  45. - (instancetype)init {
  46. return [self initWithBaseURL:nil];
  47. }
  48. - (instancetype)initWithBaseURL:(NSURL *)url {
  49. return [self initWithBaseURL:url sessionConfiguration:nil];
  50. }
  51. - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
  52. return [self initWithBaseURL:nil sessionConfiguration:configuration];
  53. }
  54. - (instancetype)initWithBaseURL:(NSURL *)url
  55. sessionConfiguration:(NSURLSessionConfiguration *)configuration
  56. {
  57. self = [super initWithSessionConfiguration:configuration];
  58. if (!self) {
  59. return nil;
  60. }
  61. // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
  62. if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
  63. url = [url URLByAppendingPathComponent:@""];
  64. }
  65. self.baseURL = url;
  66. self.requestSerializer = [AFHTTPRequestSerializer serializer];
  67. self.responseSerializer = [AFJSONResponseSerializer serializer];
  68. return self;
  69. }
  70. #pragma mark -
  71. - (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
  72. NSParameterAssert(requestSerializer);
  73. _requestSerializer = requestSerializer;
  74. }
  75. - (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
  76. NSParameterAssert(responseSerializer);
  77. [super setResponseSerializer:responseSerializer];
  78. }
  79. @dynamic securityPolicy;
  80. - (void)setSecurityPolicy:(AFSecurityPolicy *)securityPolicy {
  81. if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) {
  82. NSString *pinningMode = @"Unknown Pinning Mode";
  83. switch (securityPolicy.SSLPinningMode) {
  84. case AFSSLPinningModeNone: pinningMode = @"AFSSLPinningModeNone"; break;
  85. case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break;
  86. case AFSSLPinningModePublicKey: pinningMode = @"AFSSLPinningModePublicKey"; break;
  87. }
  88. NSString *reason = [NSString stringWithFormat:@"A security policy configured with `%@` can only be applied on a manager with a secure base URL (i.e. https)", pinningMode];
  89. @throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil];
  90. }
  91. [super setSecurityPolicy:securityPolicy];
  92. }
  93. #pragma mark -
  94. - (NSURLSessionDataTask *)GET:(NSString *)URLString
  95. parameters:(nullable id)parameters
  96. headers:(nullable NSDictionary <NSString *, NSString *> *)headers
  97. progress:(nullable void (^)(NSProgress * _Nonnull))downloadProgress
  98. success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
  99. failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
  100. {
  101. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
  102. URLString:URLString
  103. parameters:parameters
  104. headers:headers
  105. uploadProgress:nil
  106. downloadProgress:downloadProgress
  107. success:success
  108. failure:failure];
  109. [dataTask resume];
  110. return dataTask;
  111. }
  112. - (NSURLSessionDataTask *)HEAD:(NSString *)URLString
  113. parameters:(nullable id)parameters
  114. headers:(nullable NSDictionary<NSString *,NSString *> *)headers
  115. success:(nullable void (^)(NSURLSessionDataTask * _Nonnull))success
  116. failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
  117. {
  118. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) {
  119. if (success) {
  120. success(task);
  121. }
  122. } failure:failure];
  123. [dataTask resume];
  124. return dataTask;
  125. }
  126. - (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
  127. parameters:(nullable id)parameters
  128. headers:(nullable NSDictionary <NSString *, NSString *> *)headers
  129. progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
  130. success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
  131. failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
  132. {
  133. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters headers:headers uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];
  134. [dataTask resume];
  135. return dataTask;
  136. }
  137. - (NSURLSessionDataTask *)POST:(NSString *)URLString
  138. parameters:(nullable id)parameters
  139. headers:(nullable NSDictionary<NSString *,NSString *> *)headers
  140. constructingBodyWithBlock:(nullable void (^)(id<AFMultipartFormData> _Nonnull))block
  141. progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
  142. success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
  143. {
  144. NSError *serializationError = nil;
  145. NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
  146. for (NSString *headerField in headers.keyEnumerator) {
  147. [request setValue:headers[headerField] forHTTPHeaderField:headerField];
  148. }
  149. if (serializationError) {
  150. if (failure) {
  151. dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
  152. failure(nil, serializationError);
  153. });
  154. }
  155. return nil;
  156. }
  157. __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
  158. if (error) {
  159. if (failure) {
  160. failure(task, error);
  161. }
  162. } else {
  163. if (success) {
  164. success(task, responseObject);
  165. }
  166. }
  167. }];
  168. [task resume];
  169. return task;
  170. }
  171. - (NSURLSessionDataTask *)PUT:(NSString *)URLString
  172. parameters:(nullable id)parameters
  173. headers:(nullable NSDictionary<NSString *,NSString *> *)headers
  174. success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
  175. failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
  176. {
  177. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
  178. [dataTask resume];
  179. return dataTask;
  180. }
  181. - (NSURLSessionDataTask *)PATCH:(NSString *)URLString
  182. parameters:(nullable id)parameters
  183. headers:(nullable NSDictionary<NSString *,NSString *> *)headers
  184. success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
  185. failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
  186. {
  187. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
  188. [dataTask resume];
  189. return dataTask;
  190. }
  191. - (NSURLSessionDataTask *)DELETE:(NSString *)URLString
  192. parameters:(nullable id)parameters
  193. headers:(nullable NSDictionary<NSString *,NSString *> *)headers
  194. success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
  195. failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
  196. {
  197. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
  198. [dataTask resume];
  199. return dataTask;
  200. }
  201. - (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
  202. URLString:(NSString *)URLString
  203. parameters:(nullable id)parameters
  204. headers:(nullable NSDictionary <NSString *, NSString *> *)headers
  205. uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
  206. downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
  207. success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
  208. failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
  209. {
  210. NSError *serializationError = nil;
  211. NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
  212. for (NSString *headerField in headers.keyEnumerator) {
  213. [request setValue:headers[headerField] forHTTPHeaderField:headerField];
  214. }
  215. if (serializationError) {
  216. if (failure) {
  217. dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
  218. failure(nil, serializationError);
  219. });
  220. }
  221. return nil;
  222. }
  223. __block NSURLSessionDataTask *dataTask = nil;
  224. dataTask = [self dataTaskWithRequest:request
  225. uploadProgress:uploadProgress
  226. downloadProgress:downloadProgress
  227. completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
  228. if (error) {
  229. if (failure) {
  230. failure(dataTask, error);
  231. }
  232. } else {
  233. if (success) {
  234. success(dataTask, responseObject);
  235. }
  236. }
  237. }];
  238. return dataTask;
  239. }
  240. #pragma mark - NSObject
  241. - (NSString *)description {
  242. return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
  243. }
  244. #pragma mark - NSSecureCoding
  245. + (BOOL)supportsSecureCoding {
  246. return YES;
  247. }
  248. - (instancetype)initWithCoder:(NSCoder *)decoder {
  249. NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
  250. NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
  251. if (!configuration) {
  252. NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
  253. if (configurationIdentifier) {
  254. configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
  255. }
  256. }
  257. self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
  258. if (!self) {
  259. return nil;
  260. }
  261. self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
  262. self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
  263. AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))];
  264. if (decodedPolicy) {
  265. self.securityPolicy = decodedPolicy;
  266. }
  267. return self;
  268. }
  269. - (void)encodeWithCoder:(NSCoder *)coder {
  270. [super encodeWithCoder:coder];
  271. [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
  272. if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) {
  273. [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
  274. } else {
  275. [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"];
  276. }
  277. [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
  278. [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
  279. [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))];
  280. }
  281. #pragma mark - NSCopying
  282. - (instancetype)copyWithZone:(NSZone *)zone {
  283. AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
  284. HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
  285. HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
  286. HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone];
  287. return HTTPClient;
  288. }
  289. @end