Blame view

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