HttpAsynConnection-apple.m 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. /****************************************************************************
  2. Copyright (c) 2013-2017 Chukong Technologies Inc.
  3. http://www.cocos2d-x.org
  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. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. #include "platform/CCPlatformConfig.h"
  21. #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  22. #import "network/HttpAsynConnection-apple.h"
  23. @interface HttpAsynConnection ()
  24. @property (readwrite) NSString *statusString;
  25. @end
  26. @implementation HttpAsynConnection
  27. @synthesize srcURL = srcURL;
  28. @synthesize sslFile = sslFile;
  29. @synthesize responseHeader = responseHeader;
  30. @synthesize responseData = responseData;
  31. @synthesize getDataTime = getDataTime;
  32. @synthesize responseCode = responseCode;
  33. @synthesize statusString = statusString;
  34. @synthesize responseError = responseError;
  35. @synthesize connError = connError;
  36. @synthesize conn = conn;
  37. @synthesize finish = finish;
  38. @synthesize runLoop = runLoop;
  39. - (void)dealloc
  40. {
  41. [srcURL release];
  42. [sslFile release];
  43. [responseHeader release];
  44. [responseData release];
  45. [responseError release];
  46. [conn release];
  47. [runLoop release];
  48. [connError release];
  49. [super dealloc];
  50. }
  51. - (void) startRequest:(NSURLRequest *)request
  52. {
  53. #ifdef COCOS2D_DEBUG
  54. NSLog(@"Starting to load %@", srcURL);
  55. #endif
  56. finish = false;
  57. self.responseData = [NSMutableData data];
  58. getDataTime = 0;
  59. self.responseError = nil;
  60. self.connError = nil;
  61. // create the connection with the target request and this class as the delegate
  62. self.conn = [[[NSURLConnection alloc] initWithRequest:request
  63. delegate:self
  64. startImmediately:NO] autorelease];
  65. [self.conn scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  66. // start the connection
  67. [self.conn start];
  68. }
  69. #pragma mark NSURLConnectionDelegate methods
  70. /**
  71. * This delegate method is called when the NSURLConnection connects to the server. It contains the
  72. * NSURLResponse object with the headers returned by the server. This method may be called multiple times.
  73. * Therefore, it is important to reset the data on each call. Do not assume that it is the first call
  74. * of this method.
  75. **/
  76. - (void) connection:(NSURLConnection *)connection
  77. didReceiveResponse:(NSURLResponse *)response {
  78. #ifdef COCOS2D_DEBUG
  79. NSLog(@"Received response from request to url %@", srcURL);
  80. #endif
  81. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  82. //NSLog(@"All headers = %@", [httpResponse allHeaderFields]);
  83. self.responseHeader = [httpResponse allHeaderFields];
  84. responseCode = httpResponse.statusCode;
  85. self.statusString = [NSHTTPURLResponse localizedStringForStatusCode:responseCode];
  86. if(responseCode == 200)
  87. self.statusString = @"OK";
  88. /*The individual values of the numeric status codes defined for HTTP/1.1
  89. | "200" ; OK
  90. | "201" ; Created
  91. | "202" ; Accepted
  92. | "203" ; Non-Authoritative Information
  93. | "204" ; No Content
  94. | "205" ; Reset Content
  95. | "206" ; Partial Content
  96. */
  97. if (responseCode < 200 || responseCode >= 300)
  98. {// something went wrong, abort the whole thing
  99. self.responseError = [NSError errorWithDomain:@"CCBackendDomain"
  100. code:responseCode
  101. userInfo:@{NSLocalizedDescriptionKey: @"Bad HTTP Response Code"}];
  102. }
  103. [responseData setLength:0];
  104. }
  105. /**
  106. * This delegate method is called for each chunk of data received from the server. The chunk size
  107. * is dependent on the network type and the server configuration.
  108. */
  109. - (void)connection:(NSURLConnection *)connection
  110. didReceiveData:(NSData *)data
  111. {
  112. //NSLog(@"get some data");
  113. [responseData appendData:data];
  114. getDataTime++;
  115. }
  116. /**
  117. * This delegate method is called if the connection cannot be established to the server.
  118. * The error object will have a description of the error
  119. **/
  120. - (void)connection:(NSURLConnection *)connection
  121. didFailWithError:(NSError *)error
  122. {
  123. //NSLog(@"Load failed with error %@", [error localizedDescription]);
  124. self.connError = error;
  125. finish = true;
  126. }
  127. /**
  128. * This delegate method is called when the data load is complete. The delegate will be released
  129. * following this call
  130. **/
  131. - (void)connectionDidFinishLoading:(NSURLConnection *)connection
  132. {
  133. finish = true;
  134. }
  135. - (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten
  136. totalBytesWritten:(NSInteger)totalBytesWritten
  137. totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
  138. {
  139. NSLog(@"Received response from request to url didSendBodyData");
  140. }
  141. //Server evaluates client's certificate
  142. - (BOOL) shouldTrustProtectionSpace:(NSURLProtectionSpace*)protectionSpace
  143. {
  144. if(sslFile == nil)
  145. return YES;
  146. //load the bundle client certificate
  147. NSString *certPath = [[NSBundle mainBundle] pathForResource:sslFile ofType:@"der"];
  148. NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath];
  149. CFDataRef certDataRef = (CFDataRef)certData;
  150. SecCertificateRef cert = SecCertificateCreateWithData(NULL, certDataRef);
  151. //Establish a chain of trust anchored on our bundled certificate
  152. CFArrayRef certArrayRef = CFArrayCreate(NULL, (void*)&cert, 1, NULL);
  153. SecTrustRef serverTrust = protectionSpace.serverTrust;
  154. SecTrustSetAnchorCertificates(serverTrust, certArrayRef);
  155. //Verify that trust
  156. SecTrustResultType trustResult;
  157. SecTrustEvaluate(serverTrust, &trustResult);
  158. if(trustResult == kSecTrustResultRecoverableTrustFailure)
  159. {
  160. CFDataRef errDataRef = SecTrustCopyExceptions(serverTrust);
  161. SecTrustSetExceptions(serverTrust, errDataRef);
  162. SecTrustEvaluate(serverTrust, &trustResult);
  163. CFRelease(errDataRef);
  164. }
  165. [certData release];
  166. if (cert)
  167. {
  168. CFRelease(cert);
  169. }
  170. if (certArrayRef)
  171. {
  172. CFRelease(certArrayRef);
  173. }
  174. //Did our custom trust chain evaluate successfully?
  175. return trustResult == kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed;
  176. }
  177. - (void) connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
  178. {
  179. id <NSURLAuthenticationChallengeSender> sender = challenge.sender;
  180. NSURLProtectionSpace *protectionSpace = challenge.protectionSpace;
  181. //Should server trust client?
  182. if([self shouldTrustProtectionSpace:protectionSpace])
  183. {
  184. SecTrustRef trust = [protectionSpace serverTrust];
  185. //
  186. // SecCertificateRef certificate = SecTrustGetCertificateAtIndex(trust, 0);
  187. //
  188. // NSData *serverCertificateData = (NSData*)SecCertificateCopyData(certificate);
  189. // NSString *serverCertificateDataHash = [[serverCertificateData base64EncodedString] ]
  190. NSURLCredential *credential = [NSURLCredential credentialForTrust:trust];
  191. [sender useCredential:credential forAuthenticationChallenge:challenge];
  192. }
  193. else
  194. {
  195. [sender cancelAuthenticationChallenge:challenge];
  196. }
  197. }
  198. @end
  199. #endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)