File: Cronet.mm

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (319 lines) | stat: -rw-r--r-- 10,592 bytes parent folder | download
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "components/cronet/ios/Cronet.h"

#include <memory>

#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/mac/bundle_locations.h"
#include "base/mac/scoped_block.h"
#include "base/memory/ptr_util.h"
#include "base/memory/scoped_vector.h"
#include "base/strings/sys_string_conversions.h"
#include "base/synchronization/lock.h"
#include "components/cronet/ios/cronet_environment.h"
#include "components/cronet/url_request_context_config.h"
#include "ios/net/crn_http_protocol_handler.h"
#include "ios/net/empty_nsurlcache.h"
#include "net/cert/cert_verifier.h"
#include "net/url_request/url_request_context_getter.h"

namespace {

class CronetHttpProtocolHandlerDelegate;

// Currently there is one and only one instance of CronetEnvironment,
// which is leaked at the shutdown. We should consider allowing multiple
// instances if that makes sense in the future.
base::LazyInstance<std::unique_ptr<cronet::CronetEnvironment>>::Leaky
    gChromeNet = LAZY_INSTANCE_INITIALIZER;

BOOL gHttp2Enabled = YES;
BOOL gQuicEnabled = NO;
cronet::URLRequestContextConfig::HttpCacheType gHttpCache =
    cronet::URLRequestContextConfig::HttpCacheType::DISK;
ScopedVector<cronet::URLRequestContextConfig::QuicHint> gQuicHints;
NSString* gUserAgent = nil;
BOOL gUserAgentPartial = NO;
NSString* gSslKeyLogFileName = nil;
RequestFilterBlock gRequestFilterBlock = nil;
std::unique_ptr<CronetHttpProtocolHandlerDelegate> gHttpProtocolHandlerDelegate;
NSURLCache* gPreservedSharedURLCache = nil;
BOOL gEnableTestCertVerifierForTesting = FALSE;

// CertVerifier, which allows any certificates for testing.
class TestCertVerifier : public net::CertVerifier {
  int Verify(const RequestParams& params,
             net::CRLSet* crl_set,
             net::CertVerifyResult* verify_result,
             const net::CompletionCallback& callback,
             std::unique_ptr<Request>* out_req,
             const net::NetLogWithSource& net_log) override {
    net::Error result = net::OK;
    verify_result->verified_cert = params.certificate();
    verify_result->cert_status = net::MapNetErrorToCertStatus(result);
    return result;
  }
};

// net::HTTPProtocolHandlerDelegate for Cronet.
class CronetHttpProtocolHandlerDelegate
    : public net::HTTPProtocolHandlerDelegate {
 public:
  CronetHttpProtocolHandlerDelegate(net::URLRequestContextGetter* getter,
                                    RequestFilterBlock filter)
      : getter_(getter), filter_(filter, base::scoped_policy::RETAIN) {}

  void SetRequestFilterBlock(RequestFilterBlock filter) {
    base::AutoLock auto_lock(lock_);
    filter_.reset(filter, base::scoped_policy::RETAIN);
  }

 private:
  // net::HTTPProtocolHandlerDelegate implementation:
  bool CanHandleRequest(NSURLRequest* request) override {
    base::AutoLock auto_lock(lock_);
    if (filter_) {
      RequestFilterBlock block = filter_.get();
      return block(request);
    }
    return true;
  }

  bool IsRequestSupported(NSURLRequest* request) override {
    NSString* scheme = [[request URL] scheme];
    if (!scheme)
      return false;
    return [scheme caseInsensitiveCompare:@"data"] == NSOrderedSame ||
           [scheme caseInsensitiveCompare:@"http"] == NSOrderedSame ||
           [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame;
  }

  net::URLRequestContextGetter* GetDefaultURLRequestContext() override {
    return getter_.get();
  }

  scoped_refptr<net::URLRequestContextGetter> getter_;
  base::mac::ScopedBlock<RequestFilterBlock> filter_;
  base::Lock lock_;
};

}  // namespace

@implementation Cronet

+ (void)configureCronetEnvironmentForTesting:
    (cronet::CronetEnvironment*)cronetEnvironment {
  if (gEnableTestCertVerifierForTesting) {
    std::unique_ptr<TestCertVerifier> test_cert_verifier =
        base::MakeUnique<TestCertVerifier>();
    cronetEnvironment->set_mock_cert_verifier(std::move(test_cert_verifier));
  }
}

+ (NSString*)getAcceptLanguages {
  // Use the framework bundle to search for resources.
  NSBundle* frameworkBundle = [NSBundle bundleForClass:self];
  NSString* bundlePath =
      [frameworkBundle pathForResource:@"cronet_resources" ofType:@"bundle"];
  NSBundle* bundle = [NSBundle bundleWithPath:bundlePath];
  NSString* acceptLanguages = NSLocalizedStringWithDefaultValue(
      @"IDS_ACCEPT_LANGUAGES", @"Localizable", bundle, @"en-US,en",
      @"These values are copied from Chrome's .xtb files, so the same "
       "values are used in the |Accept-Language| header. Key name matches "
       "Chrome's.");
  if (acceptLanguages == Nil)
    acceptLanguages = @"";
  return acceptLanguages;
}

+ (void)checkNotStarted {
  CHECK(gChromeNet == NULL) << "Cronet is already started.";
}

+ (void)setHttp2Enabled:(BOOL)http2Enabled {
  [self checkNotStarted];
  gHttp2Enabled = http2Enabled;
}

+ (void)setQuicEnabled:(BOOL)quicEnabled {
  [self checkNotStarted];
  gQuicEnabled = quicEnabled;
}

+ (void)addQuicHint:(NSString*)host port:(int)port altPort:(int)altPort {
  [self checkNotStarted];
  gQuicHints.push_back(new cronet::URLRequestContextConfig::QuicHint(
      base::SysNSStringToUTF8(host), port, altPort));
}

+ (void)setUserAgent:(NSString*)userAgent partial:(BOOL)partial {
  [self checkNotStarted];
  gUserAgent = userAgent;
  gUserAgentPartial = partial;
}

+ (void)setSslKeyLogFileName:(NSString*)sslKeyLogFileName {
  [self checkNotStarted];
  gSslKeyLogFileName = sslKeyLogFileName;
}

+ (void)setHttpCacheType:(HttpCacheType)httpCacheType {
  [self checkNotStarted];
  switch (httpCacheType) {
    case DISABLED:
      gHttpCache = cronet::URLRequestContextConfig::HttpCacheType::DISABLED;
      break;
    case DISK:
      gHttpCache = cronet::URLRequestContextConfig::HttpCacheType::DISK;
      break;
    case MEMORY:
      gHttpCache = cronet::URLRequestContextConfig::HttpCacheType::MEMORY;
      break;
    default:
      DCHECK(NO) << "Invalid HTTP cache type: " << httpCacheType;
  }
}

+ (void)setRequestFilterBlock:(RequestFilterBlock)block {
  if (gHttpProtocolHandlerDelegate.get())
    gHttpProtocolHandlerDelegate.get()->SetRequestFilterBlock(block);
  else
    gRequestFilterBlock = block;
}

+ (void)startInternal {
  cronet::CronetEnvironment::Initialize();
  std::string user_agent = base::SysNSStringToUTF8(gUserAgent);
  gChromeNet.Get().reset(
      new cronet::CronetEnvironment(user_agent, gUserAgentPartial));
  gChromeNet.Get()->set_accept_language(
      base::SysNSStringToUTF8([self getAcceptLanguages]));

  gChromeNet.Get()->set_http2_enabled(gHttp2Enabled);
  gChromeNet.Get()->set_quic_enabled(gQuicEnabled);
  gChromeNet.Get()->set_http_cache(gHttpCache);
  gChromeNet.Get()->set_ssl_key_log_file_name(
      base::SysNSStringToUTF8(gSslKeyLogFileName));
  for (const auto* quicHint : gQuicHints) {
    gChromeNet.Get()->AddQuicHint(quicHint->host, quicHint->port,
                                  quicHint->alternate_port);
  }

  [self configureCronetEnvironmentForTesting:gChromeNet.Get().get()];
  gChromeNet.Get()->Start();
  gHttpProtocolHandlerDelegate.reset(new CronetHttpProtocolHandlerDelegate(
      gChromeNet.Get()->GetURLRequestContextGetter(), gRequestFilterBlock));
  net::HTTPProtocolHandlerDelegate::SetInstance(
      gHttpProtocolHandlerDelegate.get());
  gRequestFilterBlock = nil;
}

+ (void)start {
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    if (![NSThread isMainThread]) {
      dispatch_sync(dispatch_get_main_queue(), ^(void) {
        [self startInternal];
      });
    } else {
      [self startInternal];
    }
  });
}

+ (void)registerHttpProtocolHandler {
  if (gPreservedSharedURLCache == nil) {
    gPreservedSharedURLCache = [NSURLCache sharedURLCache];
  }
  // Disable the default cache.
  [NSURLCache setSharedURLCache:[EmptyNSURLCache emptyNSURLCache]];
  // Register the chrome http protocol handler to replace the default one.
  BOOL success =
      [NSURLProtocol registerClass:[CRNPauseableHTTPProtocolHandler class]];
  DCHECK(success);
}

+ (void)unregisterHttpProtocolHandler {
  // Set up SharedURLCache preserved in registerHttpProtocolHandler.
  if (gPreservedSharedURLCache != nil) {
    [NSURLCache setSharedURLCache:gPreservedSharedURLCache];
    gPreservedSharedURLCache = nil;
  }
  [NSURLProtocol unregisterClass:[CRNPauseableHTTPProtocolHandler class]];
}

+ (void)installIntoSessionConfiguration:(NSURLSessionConfiguration*)config {
  config.protocolClasses = @[ [CRNPauseableHTTPProtocolHandler class] ];
}

+ (NSString*)getNetLogPathForFile:(NSString*)fileName {
  return [[[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
                                                   inDomains:NSUserDomainMask]
      lastObject] URLByAppendingPathComponent:fileName] path];
}

+ (BOOL)startNetLogToFile:(NSString*)fileName logBytes:(BOOL)logBytes {
  if (gChromeNet.Get().get() && [fileName length] &&
      ![fileName isAbsolutePath]) {
    return gChromeNet.Get()->StartNetLog(
        base::SysNSStringToUTF8([self getNetLogPathForFile:fileName]),
        logBytes);
  }

  return NO;
}

+ (void)stopNetLog {
  if (gChromeNet.Get().get()) {
    gChromeNet.Get()->StopNetLog();
  }
}

+ (NSString*)getUserAgent {
  if (!gChromeNet.Get().get()) {
    return nil;
  }

  return [NSString stringWithCString:gChromeNet.Get()->user_agent().c_str()
                            encoding:[NSString defaultCStringEncoding]];
}

+ (stream_engine*)getGlobalEngine {
  DCHECK(gChromeNet.Get().get());
  if (gChromeNet.Get().get()) {
    static stream_engine engine;
    engine.obj = gChromeNet.Get()->GetURLRequestContextGetter();
    return &engine;
  }
  return nil;
}

+ (NSData*)getGlobalMetricsDeltas {
  if (!gChromeNet.Get().get()) {
    return nil;
  }
  std::vector<uint8_t> deltas(gChromeNet.Get()->GetHistogramDeltas());
  return [NSData dataWithBytes:deltas.data() length:deltas.size()];
}

+ (void)enableTestCertVerifierForTesting {
  gEnableTestCertVerifierForTesting = YES;
}

+ (void)setHostResolverRulesForTesting:(NSString*)hostResolverRulesForTesting {
  DCHECK(gChromeNet.Get().get());
  gChromeNet.Get()->SetHostResolverRules(
      base::SysNSStringToUTF8(hostResolverRulesForTesting));
}

// This is a non-public dummy method that prevents the linker from stripping out
// the otherwise non-referenced methods from 'bidirectional_stream.cc'.
+ (void)preventStrippingCronetBidirectionalStream {
  bidirectional_stream_create(NULL, 0, 0);
}

@end