Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(63)

Side by Side Diff: components/cronet/android/api/src/org/chromium/net/CronetEngine.java

Issue 2339223002: Cronet API Refactoring (Closed)
Patch Set: Moved CronetSampleApp to AppCompat Created 4 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2015 The Chromium Authors. All rights reserved. 1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 package org.chromium.net; 5 package org.chromium.net;
6 6
7 import android.annotation.SuppressLint;
8 import android.content.Context; 7 import android.content.Context;
9 import android.net.http.HttpResponseCache; 8 import android.net.http.HttpResponseCache;
10 import android.support.annotation.IntDef;
11 import android.support.annotation.VisibleForTesting;
12 import android.util.Log;
13 9
14 import java.io.File;
15 import java.io.IOException; 10 import java.io.IOException;
16 import java.lang.annotation.Retention;
17 import java.lang.annotation.RetentionPolicy;
18 import java.lang.reflect.Constructor; 11 import java.lang.reflect.Constructor;
19 import java.net.IDN;
20 import java.net.Proxy;
21 import java.net.URL; 12 import java.net.URL;
22 import java.net.URLConnection; 13 import java.net.URLConnection;
23 import java.net.URLStreamHandlerFactory; 14 import java.net.URLStreamHandlerFactory;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Date; 15 import java.util.Date;
27 import java.util.HashSet;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Set; 16 import java.util.Set;
32 import java.util.concurrent.Executor; 17 import java.util.concurrent.Executor;
33 import java.util.regex.Pattern;
34 18
35 import javax.net.ssl.HttpsURLConnection; 19 import javax.net.ssl.HttpsURLConnection;
36
37 /** 20 /**
38 * An engine to process {@link UrlRequest}s, which uses the best HTTP stack 21 * An engine to process {@link UrlRequest}s, which uses the best HTTP stack
39 * available on the current platform. 22 * available on the current platform.
40 */ 23 */
41 public abstract class CronetEngine { 24 public abstract class CronetEngine {
42 /** 25 /**
43 * A builder for {@link CronetEngine}s, which allows runtime configuration o f 26 * A builder for {@link CronetEngine}s, which allows runtime configuration o f
44 * {@code CronetEngine}. Configuration options are set on the builder and 27 * {@code CronetEngine}. Configuration options are set on the builder and
45 * then {@link #build} is called to create the {@code CronetEngine}. 28 * then {@link #build} is called to create the {@code CronetEngine}.
46 */ 29 */
47 public static class Builder { 30 public static class Builder {
31 // The class name of the Cronet Engine Builder implementation.
32 private static final String CRONET_ENGINE_BUILDER_IMPL =
33 "org.chromium.net.impl.CronetEngineBuilderImpl";
34
48 /** 35 /**
49 * A class which provides a method for loading the cronet native library . Apps needing to 36 * A class which provides a method for loading the cronet native library . Apps needing to
50 * implement custom library loading logic can inherit from this class an d pass an instance 37 * implement custom library loading logic can inherit from this class an d pass an instance
51 * to {@link CronetEngine.Builder#setLibraryLoader}. For example, this m ight be required 38 * to {@link CronetEngine.Builder#setLibraryLoader}. For example, this m ight be required
52 * to work around {@code UnsatisfiedLinkError}s caused by flaky installa tion on certain 39 * to work around {@code UnsatisfiedLinkError}s caused by flaky installa tion on certain
53 * older devices. 40 * older devices.
54 */ 41 */
55 public abstract static class LibraryLoader { 42 public abstract static class LibraryLoader {
56 /** 43 /**
57 * Loads the native library. 44 * Loads the native library.
58 * @param libName name of the library to load 45 * @param libName name of the library to load
59 */ 46 */
60 public abstract void loadLibrary(String libName); 47 public abstract void loadLibrary(String libName);
61 } 48 }
62 49
63 /** 50 // Reference to the actual builder implementation.
pauljensen 2016/09/23 19:00:54 extra spaces after "to"
kapishnikov 2016/09/23 21:26:39 Done.
64 * A hint that a host supports QUIC. 51 protected final ICronetEngineBuilder mBuilderDelegate;
65 * @hide only used by internal implementation.
66 */
67 public static class QuicHint {
68 // The host.
69 public final String mHost;
70 // Port of the server that supports QUIC.
71 public final int mPort;
72 // Alternate protocol port.
73 public final int mAlternatePort;
74
75 QuicHint(String host, int port, int alternatePort) {
76 mHost = host;
77 mPort = port;
78 mAlternatePort = alternatePort;
79 }
80 }
81
82 /**
83 * A public key pin.
84 * @hide only used by internal implementation.
85 */
86 public static class Pkp {
87 // Host to pin for.
88 public final String mHost;
89 // Array of SHA-256 hashes of keys.
90 public final byte[][] mHashes;
91 // Should pin apply to subdomains?
92 public final boolean mIncludeSubdomains;
93 // When the pin expires.
94 public final Date mExpirationDate;
95
96 Pkp(String host, byte[][] hashes, boolean includeSubdomains, Date ex pirationDate) {
97 mHost = host;
98 mHashes = hashes;
99 mIncludeSubdomains = includeSubdomains;
100 mExpirationDate = expirationDate;
101 }
102 }
103
104 private static final Pattern INVALID_PKP_HOST_NAME = Pattern.compile("^[ 0-9\\.]*$");
105
106 // Private fields are simply storage of configuration for the resulting CronetEngine.
107 // See setters below for verbose descriptions.
108 private final Context mContext;
109 private final List<QuicHint> mQuicHints = new LinkedList<QuicHint>();
110 private final List<Pkp> mPkps = new LinkedList<>();
111 private boolean mPublicKeyPinningBypassForLocalTrustAnchorsEnabled;
112 private String mUserAgent;
113 private String mStoragePath;
114 private boolean mLegacyModeEnabled;
115 private LibraryLoader mLibraryLoader;
116 private String mLibraryName;
117 private boolean mQuicEnabled;
118 private boolean mHttp2Enabled;
119 private boolean mSdchEnabled;
120 private String mDataReductionProxyKey;
121 private String mDataReductionProxyPrimaryProxy;
122 private String mDataReductionProxyFallbackProxy;
123 private String mDataReductionProxySecureProxyCheckUrl;
124 private boolean mDisableCache;
125 private int mHttpCacheMode;
126 private long mHttpCacheMaxSize;
127 private String mExperimentalOptions;
128 private long mMockCertVerifier;
129 private boolean mNetworkQualityEstimatorEnabled;
130 private String mCertVerifierData;
131 52
132 /** 53 /**
133 * Default config enables SPDY, disables QUIC, SDCH and HTTP cache. 54 * Default config enables SPDY, disables QUIC, SDCH and HTTP cache.
134 * @param context Android {@link Context} for engine to use. 55 * @param context Android {@link Context} for engine to use.
135 */ 56 */
136 public Builder(Context context) { 57 public Builder(Context context) {
137 mContext = context; 58 try {
138 setLibraryName("cronet"); 59 Class<? extends ICronetEngineBuilder> delegateImplClass =
139 enableLegacyMode(false); 60 Class.forName(CRONET_ENGINE_BUILDER_IMPL)
140 enableQuic(false); 61 .asSubclass(ICronetEngineBuilder.class);
141 enableHttp2(true); 62 Constructor<? extends ICronetEngineBuilder> ctor =
142 enableSdch(false); 63 delegateImplClass.getConstructor(Context.class);
143 enableHttpCache(HTTP_CACHE_DISABLED, 0); 64 mBuilderDelegate = ctor.newInstance(context);
144 enableNetworkQualityEstimator(false); 65 } catch (Exception e) {
145 enablePublicKeyPinningBypassForLocalTrustAnchors(true); 66 throw new RuntimeException(
67 "Unable to construct the implementation of the Cronet En gine Builder: "
68 + CRONET_ENGINE_BUILDER_IMPL,
69 e);
70 }
146 } 71 }
147 72
148 /** 73 /**
149 * Constructs a User-Agent string including application name and version , 74 * Constructs a User-Agent string including application name and version ,
150 * system build version, model and id, and Cronet version. 75 * system build version, model and id, and Cronet version.
151 * 76 *
152 * @return User-Agent string. 77 * @return User-Agent string.
153 */ 78 */
154 public String getDefaultUserAgent() { 79 public String getDefaultUserAgent() {
155 return UserAgent.from(mContext); 80 return mBuilderDelegate.getDefaultUserAgent();
156 } 81 }
157 82
158 /** 83 /**
159 * Overrides the User-Agent header for all requests. An explicitly 84 * Overrides the User-Agent header for all requests. An explicitly
160 * set User-Agent header (set using 85 * set User-Agent header (set using
161 * {@link UrlRequest.Builder#addHeader}) will override a value set 86 * {@link UrlRequest.Builder#addHeader}) will override a value set
162 * using this function. 87 * using this function.
163 * 88 *
164 * @param userAgent the User-Agent string to use for all requests. 89 * @param userAgent the User-Agent string to use for all requests.
165 * @return the builder to facilitate chaining. 90 * @return the builder to facilitate chaining.
166 */ 91 */
167 public Builder setUserAgent(String userAgent) { 92 public Builder setUserAgent(String userAgent) {
168 mUserAgent = userAgent; 93 mBuilderDelegate.setUserAgent(userAgent);
169 return this; 94 return this;
170 } 95 }
171 96
172 /** 97 /**
173 * @hide only used by internal implementation.
174 */
175 public String getUserAgent() {
176 return mUserAgent;
177 }
178
179 /**
180 * Sets directory for HTTP Cache and Cookie Storage. The directory must 98 * Sets directory for HTTP Cache and Cookie Storage. The directory must
181 * exist. 99 * exist.
182 * <p> 100 * <p>
183 * <b>NOTE:</b> Do not use the same storage directory with more than one 101 * <b>NOTE:</b> Do not use the same storage directory with more than one
184 * {@code CronetEngine} at a time. Access to the storage directory does 102 * {@code CronetEngine} at a time. Access to the storage directory does
185 * not support concurrent access by multiple {@code CronetEngine}s. 103 * not support concurrent access by multiple {@code CronetEngine}s.
186 * 104 *
187 * @param value path to existing directory. 105 * @param value path to existing directory.
188 * @return the builder to facilitate chaining. 106 * @return the builder to facilitate chaining.
189 */ 107 */
190 public Builder setStoragePath(String value) { 108 public Builder setStoragePath(String value) {
191 if (!new File(value).isDirectory()) { 109 mBuilderDelegate.setStoragePath(value);
192 throw new IllegalArgumentException(
193 "Storage path must be set to existing directory");
194 }
195 mStoragePath = value;
196 return this; 110 return this;
197 } 111 }
198 112
199 /** 113 /**
200 * @hide only used by internal implementation.
201 */
202 public String storagePath() {
203 return mStoragePath;
204 }
205
206 /**
207 * Sets whether the resulting {@link CronetEngine} uses an
208 * implementation based on the system's
209 * {@link java.net.HttpURLConnection} implementation, or if this is
210 * only done as a backup if the native implementation fails to load.
211 * Defaults to disabled.
212 * @param value {@code true} makes the resulting {@link CronetEngine}
213 * use an implementation based on the system's
214 * {@link java.net.HttpURLConnection} implementation
215 * without trying to load the native implementation.
216 * {@code false} makes the resulting {@code CronetEngine}
217 * use the native implementation, or if that fails to load,
218 * falls back to an implementation based on the system's
219 * {@link java.net.HttpURLConnection} implementation.
220 * @return the builder to facilitate chaining.
221 * @deprecated Not supported by the new API.
222 * @hide
223 */
224 @Deprecated
225 public Builder enableLegacyMode(boolean value) {
226 mLegacyModeEnabled = value;
227 return this;
228 }
229
230 /**
231 * @hide only used by internal implementation.
232 */
233 public boolean legacyMode() {
234 return mLegacyModeEnabled;
235 }
236
237 /**
238 * Overrides the name of the native library backing Cronet.
239 * @param libName the name of the native library backing Cronet.
240 * @return the builder to facilitate chaining.
241 * @hide only used by internal implementation.
242 */
243 public Builder setLibraryName(String libName) {
244 mLibraryName = libName;
245 return this;
246 }
247
248 /**
249 * @hide only used by internal implementation.
250 */
251 public String libraryName() {
252 return mLibraryName;
253 }
254
255 /**
256 * Sets a {@link LibraryLoader} to be used to load the native library. 114 * Sets a {@link LibraryLoader} to be used to load the native library.
257 * If not set, the library will be loaded using {@link System#loadLibrar y}. 115 * If not set, the library will be loaded using {@link System#loadLibrar y}.
258 * @param loader {@code LibraryLoader} to be used to load the native lib rary. 116 * @param loader {@code LibraryLoader} to be used to load the native lib rary.
259 * @return the builder to facilitate chaining. 117 * @return the builder to facilitate chaining.
260 */ 118 */
261 public Builder setLibraryLoader(LibraryLoader loader) { 119 public Builder setLibraryLoader(LibraryLoader loader) {
262 mLibraryLoader = loader; 120 mBuilderDelegate.setLibraryLoader(loader);
263 return this; 121 return this;
264 } 122 }
265 123
266 /** 124 /**
267 * @hide only used by internal implementation.
268 */
269 public LibraryLoader libraryLoader() {
270 return mLibraryLoader;
271 }
272
273 /**
274 * Sets whether <a href="https://www.chromium.org/quic">QUIC</a> protoco l 125 * Sets whether <a href="https://www.chromium.org/quic">QUIC</a> protoco l
275 * is enabled. Defaults to disabled. If QUIC is enabled, then QUIC User Agent Id 126 * is enabled. Defaults to disabled. If QUIC is enabled, then QUIC User Agent Id
276 * containing application name and Cronet version is sent to the server. 127 * containing application name and Cronet version is sent to the server.
277 * @param value {@code true} to enable QUIC, {@code false} to disable. 128 * @param value {@code true} to enable QUIC, {@code false} to disable.
278 * @return the builder to facilitate chaining. 129 * @return the builder to facilitate chaining.
279 */ 130 */
280 public Builder enableQuic(boolean value) { 131 public Builder enableQuic(boolean value) {
281 mQuicEnabled = value; 132 mBuilderDelegate.enableQuic(value);
282 return this; 133 return this;
283 } 134 }
284 135
285 /** 136 /**
286 * @hide only used by internal implementation.
287 */
288 public boolean quicEnabled() {
289 return mQuicEnabled;
290 }
291
292 /**
293 * Constructs default QUIC User Agent Id string including application na me
294 * and Cronet version. Returns empty string if QUIC is not enabled.
295 *
296 * @param context Android {@link Context} to get package name from.
297 * @return QUIC User Agent ID string.
298 * @hide only used by internal implementation.
299 */
300 // TODO(mef): remove |context| parameter when legacy ChromiumUrlRequestC ontext is removed.
301 public String getDefaultQuicUserAgentId(Context context) {
302 return mQuicEnabled ? UserAgent.getQuicUserAgentIdFrom(context) : "" ;
303 }
304
305 /**
306 * Sets whether <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> 137 * Sets whether <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a>
307 * protocol is enabled. Defaults to enabled. 138 * protocol is enabled. Defaults to enabled.
308 * @param value {@code true} to enable HTTP/2, {@code false} to disable. 139 * @param value {@code true} to enable HTTP/2, {@code false} to disable.
309 * @return the builder to facilitate chaining. 140 * @return the builder to facilitate chaining.
310 */ 141 */
311 public Builder enableHttp2(boolean value) { 142 public Builder enableHttp2(boolean value) {
312 mHttp2Enabled = value; 143 mBuilderDelegate.enableHttp2(value);
313 return this; 144 return this;
314 } 145 }
315 146
316 /** 147 /**
317 * @hide only used by internal implementation.
318 */
319 public boolean http2Enabled() {
320 return mHttp2Enabled;
321 }
322
323 /**
324 * Sets whether 148 * Sets whether
325 * <a 149 * <a
326 * href="https://lists.w3.org/Archives/Public/ietf-http-wg/2008JulSep/at t-0441/Shared_Dictionary_Compression_over_HTTP.pdf"> 150 * href="https://lists.w3.org/Archives/Public/ietf-http-wg/2008JulSep/at t-0441/Shared_Dictionary_Compression_over_HTTP.pdf">
327 * SDCH</a> compression is enabled. Defaults to disabled. 151 * SDCH</a> compression is enabled. Defaults to disabled.
328 * @param value {@code true} to enable SDCH, {@code false} to disable. 152 * @param value {@code true} to enable SDCH, {@code false} to disable.
329 * @return the builder to facilitate chaining. 153 * @return the builder to facilitate chaining.
330 */ 154 */
331 public Builder enableSdch(boolean value) { 155 public Builder enableSdch(boolean value) {
332 mSdchEnabled = value; 156 mBuilderDelegate.enableSdch(value);
333 return this; 157 return this;
334 } 158 }
335 159
336 /** 160 /**
337 * @hide only used by internal implementation.
338 */
339 public boolean sdchEnabled() {
340 return mSdchEnabled;
341 }
342
343 /**
344 * Enables 161 * Enables
345 * <a href="https://developer.chrome.com/multidevice/data-compression">D ata 162 * <a href="https://developer.chrome.com/multidevice/data-compression">D ata
346 * Reduction Proxy</a>. Defaults to disabled. 163 * Reduction Proxy</a>. Defaults to disabled.
347 * @param key key to use when authenticating with the proxy. 164 * @param key key to use when authenticating with the proxy.
348 * @return the builder to facilitate chaining. 165 * @return the builder to facilitate chaining.
349 */ 166 */
350 public Builder enableDataReductionProxy(String key) { 167 public Builder enableDataReductionProxy(String key) {
351 mDataReductionProxyKey = key; 168 mBuilderDelegate.enableDataReductionProxy(key);
352 return this; 169 return this;
353 } 170 }
354 171
355 /** 172 /**
356 * @hide only used by internal implementation. 173 * Sets whether the resulting {@link CronetEngine} uses an
174 * implementation based on the system's
175 * {@link java.net.HttpURLConnection} implementation, or if this is
176 * only done as a backup if the native implementation fails to load.
177 * Defaults to disabled.
178 * @param value {@code true} makes the resulting {@link CronetEngine}
179 * use an implementation based on the system's
180 * {@link java.net.HttpURLConnection} implementation
181 * without trying to load the native implementation.
182 * {@code false} makes the resulting {@code CronetEngine}
183 * use the native implementation, or if that fails to load,
184 * falls back to an implementation based on the system's
185 * {@link java.net.HttpURLConnection} implementation.
186 * @return the builder to facilitate chaining.
357 */ 187 */
358 public String dataReductionProxyKey() { 188 public Builder enableLegacyMode(boolean value) {
359 return mDataReductionProxyKey; 189 mBuilderDelegate.enableLegacyMode(value);
360 }
361
362 /**
363 * Overrides
364 * <a href="https://developer.chrome.com/multidevice/data-compression">
365 * Data Reduction Proxy</a> configuration parameters with a primary
366 * proxy name, fallback proxy name, and a secure proxy check URL. Proxie s
367 * are specified as [scheme://]host[:port]. Used for testing.
368 * @param primaryProxy the primary data reduction proxy to use.
369 * @param fallbackProxy a fallback data reduction proxy to use.
370 * @param secureProxyCheckUrl a URL to fetch to determine if using a sec ure
371 * proxy is allowed.
372 * @return the builder to facilitate chaining.
373 * @hide as it's a prototype.
374 */
375 public Builder setDataReductionProxyOptions(
376 String primaryProxy, String fallbackProxy, String secureProxyChe ckUrl) {
377 if (primaryProxy.isEmpty() || fallbackProxy.isEmpty()
378 || secureProxyCheckUrl.isEmpty()) {
379 throw new IllegalArgumentException(
380 "Primary and fallback proxies and check url must be set" );
381 }
382 mDataReductionProxyPrimaryProxy = primaryProxy;
383 mDataReductionProxyFallbackProxy = fallbackProxy;
384 mDataReductionProxySecureProxyCheckUrl = secureProxyCheckUrl;
385 return this; 190 return this;
386 } 191 }
387 192
388 /** 193 /**
389 * @hide only used by internal implementation.
390 */
391 public String dataReductionProxyPrimaryProxy() {
392 return mDataReductionProxyPrimaryProxy;
393 }
394
395 /**
396 * @hide only used by internal implementation.
397 */
398 public String dataReductionProxyFallbackProxy() {
399 return mDataReductionProxyFallbackProxy;
400 }
401
402 /**
403 * @hide only used by internal implementation.
404 */
405 public String dataReductionProxySecureProxyCheckUrl() {
406 return mDataReductionProxySecureProxyCheckUrl;
407 }
408
409 /** @hide */
410 @IntDef({
411 HTTP_CACHE_DISABLED, HTTP_CACHE_IN_MEMORY, HTTP_CACHE_DISK_NO_HT TP, HTTP_CACHE_DISK,
412 })
413 @Retention(RetentionPolicy.SOURCE)
414 public @interface HttpCacheSetting {}
415
416 /**
417 * Setting to disable HTTP cache. Some data may still be temporarily sto red in memory. 194 * Setting to disable HTTP cache. Some data may still be temporarily sto red in memory.
418 * Passed to {@link #enableHttpCache}. 195 * Passed to {@link #enableHttpCache}.
419 */ 196 */
420 public static final int HTTP_CACHE_DISABLED = 0; 197 public static final int HTTP_CACHE_DISABLED = 0;
421 198
422 /** 199 /**
423 * Setting to enable in-memory HTTP cache, including HTTP data. 200 * Setting to enable in-memory HTTP cache, including HTTP data.
424 * Passed to {@link #enableHttpCache}. 201 * Passed to {@link #enableHttpCache}.
425 */ 202 */
426 public static final int HTTP_CACHE_IN_MEMORY = 1; 203 public static final int HTTP_CACHE_IN_MEMORY = 1;
(...skipping 14 matching lines...) Expand all
441 218
442 /** 219 /**
443 * Enables or disables caching of HTTP data and other information like Q UIC 220 * Enables or disables caching of HTTP data and other information like Q UIC
444 * server information. 221 * server information.
445 * @param cacheMode control location and type of cached data. Must be on e of 222 * @param cacheMode control location and type of cached data. Must be on e of
446 * {@link #HTTP_CACHE_DISABLED HTTP_CACHE_*}. 223 * {@link #HTTP_CACHE_DISABLED HTTP_CACHE_*}.
447 * @param maxSize maximum size in bytes used to cache data (advisory and maybe 224 * @param maxSize maximum size in bytes used to cache data (advisory and maybe
448 * exceeded at times). 225 * exceeded at times).
449 * @return the builder to facilitate chaining. 226 * @return the builder to facilitate chaining.
450 */ 227 */
451 public Builder enableHttpCache(@HttpCacheSetting int cacheMode, long max Size) { 228 public Builder enableHttpCache(int cacheMode, long maxSize) {
452 if (cacheMode == HTTP_CACHE_DISK || cacheMode == HTTP_CACHE_DISK_NO_ HTTP) { 229 mBuilderDelegate.enableHttpCache(cacheMode, maxSize);
453 if (storagePath() == null) {
454 throw new IllegalArgumentException("Storage path must be set ");
455 }
456 } else {
457 if (storagePath() != null) {
458 throw new IllegalArgumentException("Storage path must not be set");
459 }
460 }
461 mDisableCache =
462 (cacheMode == HTTP_CACHE_DISABLED || cacheMode == HTTP_CACHE _DISK_NO_HTTP);
463 mHttpCacheMaxSize = maxSize;
464
465 switch (cacheMode) {
466 case HTTP_CACHE_DISABLED:
467 mHttpCacheMode = HttpCacheType.DISABLED;
468 break;
469 case HTTP_CACHE_DISK_NO_HTTP:
470 case HTTP_CACHE_DISK:
471 mHttpCacheMode = HttpCacheType.DISK;
472 break;
473 case HTTP_CACHE_IN_MEMORY:
474 mHttpCacheMode = HttpCacheType.MEMORY;
475 break;
476 default:
477 throw new IllegalArgumentException("Unknown cache mode");
478 }
479 return this; 230 return this;
480 } 231 }
481 232
482 /** 233 /**
483 * @hide only used by internal implementation.
484 */
485 public boolean cacheDisabled() {
486 return mDisableCache;
487 }
488
489 /**
490 * @hide only used by internal implementation.
491 */
492 public long httpCacheMaxSize() {
493 return mHttpCacheMaxSize;
494 }
495
496 /**
497 * @hide only used by internal implementation.
498 */
499 public int httpCacheMode() {
500 return mHttpCacheMode;
501 }
502
503 /**
504 * Adds hint that {@code host} supports QUIC. 234 * Adds hint that {@code host} supports QUIC.
505 * Note that {@link #enableHttpCache enableHttpCache} 235 * Note that {@link #enableHttpCache enableHttpCache}
506 * ({@link #HTTP_CACHE_DISK}) is needed to take advantage of 0-RTT 236 * ({@link #HTTP_CACHE_DISK}) is needed to take advantage of 0-RTT
507 * connection establishment between sessions. 237 * connection establishment between sessions.
508 * 238 *
509 * @param host hostname of the server that supports QUIC. 239 * @param host hostname of the server that supports QUIC.
510 * @param port host of the server that supports QUIC. 240 * @param port host of the server that supports QUIC.
511 * @param alternatePort alternate port to use for QUIC. 241 * @param alternatePort alternate port to use for QUIC.
512 * @return the builder to facilitate chaining. 242 * @return the builder to facilitate chaining.
513 */ 243 */
514 public Builder addQuicHint(String host, int port, int alternatePort) { 244 public Builder addQuicHint(String host, int port, int alternatePort) {
515 if (host.contains("/")) { 245 mBuilderDelegate.addQuicHint(host, port, alternatePort);
516 throw new IllegalArgumentException("Illegal QUIC Hint Host: " + host);
517 }
518 mQuicHints.add(new QuicHint(host, port, alternatePort));
519 return this; 246 return this;
520 } 247 }
521 248
522 /** 249 /**
523 * @hide only used by internal implementation.
524 */
525 public List<QuicHint> quicHints() {
526 return mQuicHints;
527 }
528
529 /**
530 * <p> 250 * <p>
531 * Pins a set of public keys for a given host. By pinning a set of publi c keys, 251 * Pins a set of public keys for a given host. By pinning a set of publi c keys,
532 * {@code pinsSha256}, communication with {@code hostName} is required t o 252 * {@code pinsSha256}, communication with {@code hostName} is required t o
533 * authenticate with a certificate with a public key from the set of pin ned ones. 253 * authenticate with a certificate with a public key from the set of pin ned ones.
534 * An app can pin the public key of the root certificate, any of the int ermediate 254 * An app can pin the public key of the root certificate, any of the int ermediate
535 * certificates or the end-entry certificate. Authentication will fail a nd secure 255 * certificates or the end-entry certificate. Authentication will fail a nd secure
536 * communication will not be established if none of the public keys is p resent in the 256 * communication will not be established if none of the public keys is p resent in the
537 * host's certificate chain, even if the host attempts to authenticate w ith a 257 * host's certificate chain, even if the host attempts to authenticate w ith a
538 * certificate allowed by the device's trusted store of certificates. 258 * certificate allowed by the device's trusted store of certificates.
539 * </p> 259 * </p>
(...skipping 22 matching lines...) Expand all
562 * subdomains of {@code hostName}. 282 * subdomains of {@code hostName}.
563 * @param expirationDate specifies the expiration date for the pins. 283 * @param expirationDate specifies the expiration date for the pins.
564 * @return the builder to facilitate chaining. 284 * @return the builder to facilitate chaining.
565 * @throws NullPointerException if any of the input parameters are {@cod e null}. 285 * @throws NullPointerException if any of the input parameters are {@cod e null}.
566 * @throws IllegalArgumentException if the given host name is invalid or {@code pinsSha256} 286 * @throws IllegalArgumentException if the given host name is invalid or {@code pinsSha256}
567 * contains a byte array that does not represent a valid 287 * contains a byte array that does not represent a valid
568 * SHA-256 hash. 288 * SHA-256 hash.
569 */ 289 */
570 public Builder addPublicKeyPins(String hostName, Set<byte[]> pinsSha256, 290 public Builder addPublicKeyPins(String hostName, Set<byte[]> pinsSha256,
571 boolean includeSubdomains, Date expirationDate) { 291 boolean includeSubdomains, Date expirationDate) {
572 if (hostName == null) { 292 mBuilderDelegate.addPublicKeyPins(
573 throw new NullPointerException("The hostname cannot be null"); 293 hostName, pinsSha256, includeSubdomains, expirationDate);
574 }
575 if (pinsSha256 == null) {
576 throw new NullPointerException("The set of SHA256 pins cannot be null");
577 }
578 if (expirationDate == null) {
579 throw new NullPointerException("The pin expiration date cannot b e null");
580 }
581 String idnHostName = validateHostNameForPinningAndConvert(hostName);
582 // Convert the pin to BASE64 encoding. The hash set will eliminate d uplications.
583 Set<byte[]> hashes = new HashSet<>(pinsSha256.size());
584 for (byte[] pinSha256 : pinsSha256) {
585 if (pinSha256 == null || pinSha256.length != 32) {
586 throw new IllegalArgumentException("Public key pin is invali d");
587 }
588 hashes.add(pinSha256);
589 }
590 // Add new element to PKP list.
591 mPkps.add(new Pkp(idnHostName, hashes.toArray(new byte[hashes.size() ][]),
592 includeSubdomains, expirationDate));
593 return this; 294 return this;
594 } 295 }
595 296
596 /** 297 /**
597 * Returns list of public key pins.
598 * @return list of public key pins.
599 * @hide only used by internal implementation.
600 */
601 public List<Pkp> publicKeyPins() {
602 return mPkps;
603 }
604
605 /**
606 * Enables or disables public key pinning bypass for local trust anchors . Disabling the 298 * Enables or disables public key pinning bypass for local trust anchors . Disabling the
607 * bypass for local trust anchors is highly discouraged since it may pro hibit the app 299 * bypass for local trust anchors is highly discouraged since it may pro hibit the app
608 * from communicating with the pinned hosts. E.g., a user may want to se nd all traffic 300 * from communicating with the pinned hosts. E.g., a user may want to se nd all traffic
609 * through an SSL enabled proxy by changing the device proxy settings an d adding the 301 * through an SSL enabled proxy by changing the device proxy settings an d adding the
610 * proxy certificate to the list of local trust anchor. Disabling the by pass will most 302 * proxy certificate to the list of local trust anchor. Disabling the by pass will most
611 * likly prevent the app from sending any traffic to the pinned hosts. F or more 303 * likly prevent the app from sending any traffic to the pinned hosts. F or more
612 * information see 'How does key pinning interact with local proxies and filters?' at 304 * information see 'How does key pinning interact with local proxies and filters?' at
613 * https://www.chromium.org/Home/chromium-security/security-faq 305 * https://www.chromium.org/Home/chromium-security/security-faq
614 * 306 *
615 * @param value {@code true} to enable the bypass, {@code false} to disa ble. 307 * @param value {@code true} to enable the bypass, {@code false} to disa ble.
616 * @return the builder to facilitate chaining. 308 * @return the builder to facilitate chaining.
617 */ 309 */
618 public Builder enablePublicKeyPinningBypassForLocalTrustAnchors(boolean value) { 310 public Builder enablePublicKeyPinningBypassForLocalTrustAnchors(boolean value) {
619 mPublicKeyPinningBypassForLocalTrustAnchorsEnabled = value; 311 mBuilderDelegate.enablePublicKeyPinningBypassForLocalTrustAnchors(va lue);
620 return this; 312 return this;
621 } 313 }
622 314
623 /** 315 /**
624 * @hide only used by internal implementation.
625 */
626 public boolean publicKeyPinningBypassForLocalTrustAnchorsEnabled() {
627 return mPublicKeyPinningBypassForLocalTrustAnchorsEnabled;
628 }
629
630 /**
631 * Checks whether a given string represents a valid host name for PKP an d converts it
632 * to ASCII Compatible Encoding representation according to RFC 1122, RF C 1123 and
633 * RFC 3490. This method is more restrictive than required by RFC 7469. Thus, a host
634 * that contains digits and the dot character only is considered invalid .
635 *
636 * Note: Currently Cronet doesn't have native implementation of host nam e validation that
637 * can be used. There is code that parses a provided URL but doesn 't ensure its
638 * correctness. The implementation relies on {@code getaddrinfo} f unction.
639 *
640 * @param hostName host name to check and convert.
641 * @return true if the string is a valid host name.
642 * @throws IllegalArgumentException if the the given string does not rep resent a valid
643 * hostname.
644 */
645 private static String validateHostNameForPinningAndConvert(String hostNa me)
646 throws IllegalArgumentException {
647 if (INVALID_PKP_HOST_NAME.matcher(hostName).matches()) {
648 throw new IllegalArgumentException("Hostname " + hostName + " is illegal."
649 + " A hostname should not consist of digits and/or dots only.");
650 }
651 // Workaround for crash, see crbug.com/634914
652 if (hostName.length() > 255) {
653 throw new IllegalArgumentException("Hostname " + hostName + " is too long."
654 + " The name of the host does not comply with RFC 1122 a nd RFC 1123.");
655 }
656 try {
657 return IDN.toASCII(hostName, IDN.USE_STD3_ASCII_RULES);
658 } catch (IllegalArgumentException ex) {
659 throw new IllegalArgumentException("Hostname " + hostName + " is illegal."
660 + " The name of the host does not comply with RFC 1122 a nd RFC 1123.");
661 }
662 }
663
664 /**
665 * Sets experimental options to be used in Cronet. 316 * Sets experimental options to be used in Cronet.
666 * 317 *
667 * @param options JSON formatted experimental options. 318 * @param options JSON formatted experimental options.
668 * @return the builder to facilitate chaining. 319 * @return the builder to facilitate chaining.
669 */ 320 */
670 public Builder setExperimentalOptions(String options) { 321 public Builder setExperimentalOptions(String options) {
671 mExperimentalOptions = options; 322 mBuilderDelegate.setExperimentalOptions(options);
672 return this; 323 return this;
673 } 324 }
674 325
675 /** 326 /**
676 * @hide only used by internal implementation.
677 */
678 public String experimentalOptions() {
679 return mExperimentalOptions;
680 }
681
682 /**
683 * Sets a native MockCertVerifier for testing. See
684 * {@code MockCertVerifier.createMockCertVerifier} for a method that
685 * can be used to create a MockCertVerifier.
686 * @param mockCertVerifier pointer to native MockCertVerifier.
687 * @return the builder to facilitate chaining.
688 * @hide
689 */
690 @VisibleForTesting
691 public Builder setMockCertVerifierForTesting(long mockCertVerifier) {
692 mMockCertVerifier = mockCertVerifier;
693 return this;
694 }
695
696 /**
697 * @hide only used by internal implementation.
698 */
699 public long mockCertVerifier() {
700 return mMockCertVerifier;
701 }
702
703 /**
704 * Enables the network quality estimator, which collects and reports
705 * measurements of round trip time (RTT) and downstream throughput at
706 * various layers of the network stack. After enabling the estimator,
707 * listeners of RTT and throughput can be added with
708 * {@link #addRttListener} and {@link #addThroughputListener} and
709 * removed with {@link #removeRttListener} and
710 * {@link #removeThroughputListener}. The estimator uses memory and CPU
711 * only when enabled.
712 * @param value {@code true} to enable network quality estimator,
713 * {@code false} to disable.
714 * @hide as it's a prototype.
715 * @return the builder to facilitate chaining.
716 */
717 public Builder enableNetworkQualityEstimator(boolean value) {
718 mNetworkQualityEstimatorEnabled = value;
719 return this;
720 }
721
722 /**
723 * @return true if the network quality estimator has been enabled for
724 * this builder.
725 * @hide as it's a prototype and only used by internal implementation.
726 */
727 public boolean networkQualityEstimatorEnabled() {
728 return mNetworkQualityEstimatorEnabled;
729 }
730
731 /**
732 * Initializes CachingCertVerifier's cache with certVerifierData which h as
733 * the results of certificate verification.
734 * @param certVerifierData a serialized representation of certificate
735 * verification results.
736 * @return the builder to facilitate chaining.
737 */
738 public Builder setCertVerifierData(String certVerifierData) {
739 mCertVerifierData = certVerifierData;
740 return this;
741 }
742
743 /**
744 * @hide only used by internal implementation.
745 */
746 public String certVerifierData() {
747 return mCertVerifierData;
748 }
749
750 /**
751 * Returns {@link Context} for builder.
752 *
753 * @return {@link Context} for builder.
754 * @hide only used by internal implementation.
755 */
756 public Context getContext() {
757 return mContext;
758 }
759
760 /**
761 * Build a {@link CronetEngine} using this builder's configuration. 327 * Build a {@link CronetEngine} using this builder's configuration.
762 * @return constructed {@link CronetEngine}. 328 * @return constructed {@link CronetEngine}.
763 */ 329 */
764 public CronetEngine build() { 330 public CronetEngine build() {
765 if (getUserAgent() == null) { 331 return mBuilderDelegate.build();
766 setUserAgent(getDefaultUserAgent()); 332 }
767 } 333
768 CronetEngine cronetEngine = null; 334 ICronetEngineBuilder getBuilderDelegate() {
769 if (!legacyMode()) { 335 return mBuilderDelegate;
770 cronetEngine = createCronetEngine(this);
771 }
772 if (cronetEngine == null) {
773 cronetEngine = new JavaCronetEngine(getUserAgent());
774 }
775 Log.i(TAG, "Using network stack: " + cronetEngine.getVersionString() );
776 // Clear MOCK_CERT_VERIFIER reference if there is any, since
777 // the ownership has been transferred to the engine.
778 mMockCertVerifier = 0;
779 return cronetEngine;
780 } 336 }
781 } 337 }
782 338
783 private static final String TAG = "UrlRequestFactory";
784 private static final String CRONET_URL_REQUEST_CONTEXT =
785 "org.chromium.net.impl.CronetUrlRequestContext";
786
787 /**
788 * Creates a {@link UrlRequest} object. All callbacks will
789 * be called on {@code executor}'s thread. {@code executor} must not run
790 * tasks on the current thread to prevent blocking networking operations
791 * and causing exceptions during shutdown. Request is given medium priority,
792 * see {@link UrlRequest.Builder#REQUEST_PRIORITY_MEDIUM}. To specify other
793 * priorities see {@link #createRequest(String, UrlRequest.Callback,
794 * Executor, int priority)}.
795 *
796 * @param url {@link URL} for the request.
797 * @param callback callback object that gets invoked on different events.
798 * @param executor {@link Executor} on which all callbacks will be invoked.
799 * @return new request.
800 * @deprecated Use {@link UrlRequest.Builder#build}.
801 * @hide
802 */
803 @Deprecated
804 @SuppressLint("WrongConstant") // TODO(jbudorick): Remove this after rolling to the N SDK.
805 public final UrlRequest createRequest(
806 String url, UrlRequest.Callback callback, Executor executor) {
807 return createRequest(url, callback, executor, UrlRequest.Builder.REQUEST _PRIORITY_MEDIUM);
808 }
809
810 /**
811 * Creates a {@link UrlRequest} object. All callbacks will
812 * be called on {@code executor}'s thread. {@code executor} must not run
813 * tasks on the current thread to prevent blocking networking operations
814 * and causing exceptions during shutdown.
815 *
816 * @param url {@link URL} for the request.
817 * @param callback callback object that gets invoked on different events.
818 * @param executor {@link Executor} on which all callbacks will be invoked.
819 * @param priority priority of the request which should be one of the
820 * {@link UrlRequest.Builder#REQUEST_PRIORITY_IDLE REQUEST_PRIORITY_ *}
821 * values.
822 * @return new request.
823 * @deprecated Use {@link UrlRequest.Builder#build}.
824 * @hide
825 */
826 @Deprecated
827 public final UrlRequest createRequest(String url, UrlRequest.Callback callba ck,
828 Executor executor, @UrlRequest.Builder.RequestPriority int priority) {
829 return createRequest(
830 url, callback, executor, priority, Collections.emptyList(), fals e, false, false);
831 }
832
833 /**
834 * Creates a {@link UrlRequest} object. All callbacks will
835 * be called on {@code executor}'s thread. {@code executor} must not run
836 * tasks on the current thread to prevent blocking networking operations
837 * and causing exceptions during shutdown.
838 *
839 * @param url {@link URL} for the request.
840 * @param callback callback object that gets invoked on different events.
841 * @param executor {@link Executor} on which all callbacks will be invoked.
842 * @param priority priority of the request which should be one of the
843 * {@link UrlRequest.Builder#REQUEST_PRIORITY_IDLE REQUEST_PRIORITY_ *}
844 * values.
845 * @param requestAnnotations Objects to pass on to {@link RequestFinishedInf o.Listener}.
846 * @param disableCache disables cache for the request.
847 * If context is not set up to use cache this param has no effect.
848 * @param disableConnectionMigration disables connection migration for this
849 * request if it is enabled for the session.
850 * @param allowDirectExecutor whether executors used by this request are per mitted
851 * to execute submitted tasks inline.
852 * @return new request.
853 * @deprecated Use {@link UrlRequest.Builder#build}.
854 * @hide as it references hidden RequestFinishedInfo.Listener
855 */
856 @Deprecated
857 protected abstract UrlRequest createRequest(String url, UrlRequest.Callback callback,
858 Executor executor, int priority, Collection<Object> requestAnnotatio ns,
859 boolean disableCache, boolean disableConnectionMigration, boolean al lowDirectExecutor);
860
861 /**
862 * Creates a {@link BidirectionalStream} object. {@code callback} methods wi ll
863 * be invoked on {@code executor}. {@code executor} must not run
864 * tasks on the current thread to prevent blocking networking operations
865 * and causing exceptions during shutdown.
866 *
867 * @param url the URL for the stream
868 * @param callback the object whose methods get invoked upon different event s
869 * @param executor the {@link Executor} on which all callbacks will be calle d
870 * @param httpMethod the HTTP method to use for the stream
871 * @param requestHeaders the list of request headers
872 * @param priority priority of the stream which should be one of the
873 * {@link BidirectionalStream.Builder#STREAM_PRIORITY_IDLE STREAM_PR IORITY_*}
874 * values.
875 * @param delayRequestHeadersUntilFirstFlush whether to delay sending reques t
876 * headers until flush() is called, and try to combine them
877 * with the next data frame.
878 * @param requestAnnotations Objects to pass on to {@link RequestFinishedInf o.Listener}.
879 * @return a new stream.
880 * @hide only used by internal implementation.
881 */
882 public abstract BidirectionalStream createBidirectionalStream(String url,
883 BidirectionalStream.Callback callback, Executor executor, String htt pMethod,
884 List<Map.Entry<String, String>> requestHeaders,
885 @BidirectionalStream.Builder.StreamPriority int priority,
886 boolean delayRequestHeadersUntilFirstFlush, Collection<Object> reque stAnnotations);
887
888 /**
889 * @return {@code true} if the engine is enabled.
890 * @hide only used by internal implementation.
891 */
892 public abstract boolean isEnabled();
893
894 /** 339 /**
895 * @return a human-readable version string of the engine. 340 * @return a human-readable version string of the engine.
896 */ 341 */
897 public abstract String getVersionString(); 342 public abstract String getVersionString();
898 343
899 /** 344 /**
900 * Shuts down the {@link CronetEngine} if there are no active requests, 345 * Shuts down the {@link CronetEngine} if there are no active requests,
901 * otherwise throws an exception. 346 * otherwise throws an exception.
902 * 347 *
903 * Cannot be called on network thread - the thread Cronet calls into 348 * Cannot be called on network thread - the thread Cronet calls into
(...skipping 14 matching lines...) Expand all
918 * @param logAll {@code true} to include basic events, user cookies, 363 * @param logAll {@code true} to include basic events, user cookies,
919 * credentials and all transferred bytes in the log. This option presents 364 * credentials and all transferred bytes in the log. This option presents
920 * a privacy risk, since it exposes the user's credentials, and s hould 365 * a privacy risk, since it exposes the user's credentials, and s hould
921 * only be used with the user's consent and in situations where t he log 366 * only be used with the user's consent and in situations where t he log
922 * won't be public. 367 * won't be public.
923 * {@code false} to just include basic events. 368 * {@code false} to just include basic events.
924 */ 369 */
925 public abstract void startNetLogToFile(String fileName, boolean logAll); 370 public abstract void startNetLogToFile(String fileName, boolean logAll);
926 371
927 /** 372 /**
928 * Starts NetLog logging to a specified directory with a bounded size. The N etLog will contain
929 * events emitted by all live CronetEngines. The NetLog is useful for debugg ing.
930 * The log can be viewed by stitching the files using net/log/stitch_net_log _files.py and
931 * using a Chrome browser navigated to chrome://net-internals/#import
932 * @param dirPath the directory where the log files will be created. It must already exist.
933 * NetLog files must not already exist in the directory. If activ ely logging,
934 * this method is ignored.
935 * @param logAll {@code true} to include basic events, user cookies,
936 * credentials and all transferred bytes in the log. This option presents a
937 * privacy risk, since it exposes the user's credentials, and sho uld only be
938 * used with the user's consent and in situations where the log w on't be public.
939 * {@code false} to just include basic events.
940 * @param maxSize the maximum total disk space in bytes that should be used by NetLog. Actual
941 * disk space usage may exceed this limit slightly.
942 */
943 public abstract void startNetLogToDisk(String dirPath, boolean logAll, int m axSize);
944
945 /**
946 * Stops NetLog logging and flushes file to disk. If a logging session is 373 * Stops NetLog logging and flushes file to disk. If a logging session is
947 * not in progress, this call is ignored. 374 * not in progress, this call is ignored.
948 */ 375 */
949 public abstract void stopNetLog(); 376 public abstract void stopNetLog();
950 377
951 /** 378 /**
952 * Returns serialized representation of certificate verifier's cache 379 * Returns serialized representation of certificate verifier's cache
953 * which contains the list of hosts/certificates and the certificate 380 * which contains the list of hosts/certificates and the certificate
954 * verification results. May block until data is received from the network 381 * verification results. May block until data is received from the network
955 * thread (will timeout after the specified timeout). In case of timeout, it 382 * thread (will timeout after the specified timeout). In case of timeout, it
956 * returns the previous saved value. 383 * returns the previous saved value.
957 * 384 *
958 * @param timeout in milliseconds. If timeout is 0, it will use default valu e. 385 * @param timeout in milliseconds. If timeout is 0, it will use default valu e.
959 * @return serialized representation of certificate verification results 386 * @return serialized representation of certificate verification results
960 * data. 387 * data.
961 */ 388 */
962 public abstract String getCertVerifierData(long timeout); 389 public abstract String getCertVerifierData(long timeout);
963 390
964 /** 391 /**
965 * Returns differences in metrics collected by Cronet since the last call to 392 * Returns differences in metrics collected by Cronet since the last call to
966 * {@link #getGlobalMetricsDeltas}. 393 * this method.
967 * <p> 394 * <p>
968 * Cronet collects these metrics globally. This means deltas returned by 395 * Cronet collects these metrics globally. This means deltas returned by
969 * {@code getGlobalMetricsDeltas()} will include measurements of requests 396 * {@code getGlobalMetricsDeltas()} will include measurements of requests
970 * processed by other {@link CronetEngine} instances. Since this function 397 * processed by other {@link CronetEngine} instances. Since this function
971 * returns differences in metrics collected since the last call, and these 398 * returns differences in metrics collected since the last call, and these
972 * metrics are collected globally, a call to any {@code CronetEngine} 399 * metrics are collected globally, a call to any {@code CronetEngine}
973 * instance's {@code getGlobalMetricsDeltas()} method will affect the deltas 400 * instance's {@code getGlobalMetricsDeltas()} method will affect the deltas
974 * returned by any other {@code CronetEngine} instance's 401 * returned by any other {@code CronetEngine} instance's
975 * {@code getGlobalMetricsDeltas()}. 402 * {@code getGlobalMetricsDeltas()}.
976 * <p> 403 * <p>
977 * Cronet starts collecting these metrics after the first call to 404 * Cronet starts collecting these metrics after the first call to
978 * {@code getGlobalMetricsDeltras()}, so the first call returns no 405 * {@code getGlobalMetricsDeltras()}, so the first call returns no
979 * useful data as no metrics have yet been collected. 406 * useful data as no metrics have yet been collected.
980 * 407 *
981 * @return differences in metrics collected by Cronet, since the last call 408 * @return differences in metrics collected by Cronet, since the last call
982 * to {@code getGlobalMetricsDeltas()}, serialized as a 409 * to {@code getGlobalMetricsDeltas()}, serialized as a
983 * <a href=https://developers.google.com/protocol-buffers>protobuf 410 * <a href=https://developers.google.com/protocol-buffers>protobuf
984 * </a>. 411 * </a>.
985 */ 412 */
986 public abstract byte[] getGlobalMetricsDeltas(); 413 public abstract byte[] getGlobalMetricsDeltas();
987 414
988 /** 415 /**
989 * Returns the effective connection type computed by the network quality
990 * estimator.
991 * @hide as it's a prototype.
992 */
993 public abstract int getEffectiveConnectionType();
994
995 /**
996 * Configures the network quality estimator for testing. This must be called
997 * before round trip time and throughput listeners are added, and after the
998 * network quality estimator has been enabled.
999 * @param useLocalHostRequests include requests to localhost in estimates.
1000 * @param useSmallerResponses include small responses in throughput
1001 * estimates.
1002 * @hide as it's a prototype.
1003 */
1004 public abstract void configureNetworkQualityEstimatorForTesting(
1005 boolean useLocalHostRequests, boolean useSmallerResponses);
1006
1007 /**
1008 * Registers a listener that gets called whenever the network quality
1009 * estimator witnesses a sample round trip time. This must be called
1010 * after {@link #enableNetworkQualityEstimator}, and with throw an
1011 * exception otherwise. Round trip times may be recorded at various layers
1012 * of the network stack, including TCP, QUIC, and at the URL request layer.
1013 * The listener is called on the {@link java.util.concurrent.Executor} that
1014 * is passed to {@link #enableNetworkQualityEstimator}.
1015 * @param listener the listener of round trip times.
1016 * @hide as it's a prototype.
1017 */
1018 public abstract void addRttListener(NetworkQualityRttListener listener);
1019
1020 /**
1021 * Removes a listener of round trip times if previously registered with
1022 * {@link #addRttListener}. This should be called after a
1023 * {@link NetworkQualityRttListener} is added in order to stop receiving
1024 * observations.
1025 * @param listener the listener of round trip times.
1026 * @hide as it's a prototype.
1027 */
1028 public abstract void removeRttListener(NetworkQualityRttListener listener);
1029
1030 /**
1031 * Registers a listener that gets called whenever the network quality
1032 * estimator witnesses a sample throughput measurement. This must be called
1033 * after {@link #enableNetworkQualityEstimator}. Throughput observations
1034 * are computed by measuring bytes read over the active network interface
1035 * at times when at least one URL response is being received. The listener
1036 * is called on the {@link java.util.concurrent.Executor} that is passed to
1037 * {@link #enableNetworkQualityEstimator}.
1038 * @param listener the listener of throughput.
1039 * @hide as it's a prototype.
1040 */
1041 public abstract void addThroughputListener(NetworkQualityThroughputListener listener);
1042
1043 /**
1044 * Removes a listener of throughput. This should be called after a
1045 * {@link NetworkQualityThroughputListener} is added with
1046 * {@link #addThroughputListener} in order to stop receiving observations.
1047 * @param listener the listener of throughput.
1048 * @hide as it's a prototype.
1049 */
1050 public abstract void removeThroughputListener(NetworkQualityThroughputListen er listener);
1051
1052 /**
1053 * Establishes a new connection to the resource specified by the {@link URL} {@code url}. 416 * Establishes a new connection to the resource specified by the {@link URL} {@code url}.
1054 * <p> 417 * <p>
1055 * <b>Note:</b> Cronet's {@link java.net.HttpURLConnection} implementation i s subject to certain 418 * <b>Note:</b> Cronet's {@link java.net.HttpURLConnection} implementation i s subject to certain
1056 * limitations, see {@link #createURLStreamHandlerFactory} for details. 419 * limitations, see {@link #createURLStreamHandlerFactory} for details.
1057 * 420 *
1058 * @param url URL of resource to connect to. 421 * @param url URL of resource to connect to.
1059 * @return an {@link java.net.HttpURLConnection} instance implemented by thi s CronetEngine. 422 * @return an {@link java.net.HttpURLConnection} instance implemented by thi s CronetEngine.
1060 * @throws IOException if an error occurs while opening the connection. 423 * @throws IOException if an error occurs while opening the connection.
1061 */ 424 */
1062 public abstract URLConnection openConnection(URL url) throws IOException; 425 public abstract URLConnection openConnection(URL url) throws IOException;
1063 426
1064 /** 427 /**
1065 * Establishes a new connection to the resource specified by the {@link URL} {@code url}
1066 * using the given proxy.
1067 * <p>
1068 * <b>Note:</b> Cronet's {@link java.net.HttpURLConnection} implementation i s subject to certain
1069 * limitations, see {@link #createURLStreamHandlerFactory} for details.
1070 *
1071 * @param url URL of resource to connect to.
1072 * @param proxy proxy to use when establishing connection.
1073 * @return an {@link java.net.HttpURLConnection} instance implemented by thi s CronetEngine.
1074 * @throws IOException if an error occurs while opening the connection.
1075 * @hide TODO(pauljensen): Expose once implemented, http://crbug.com/418111
1076 */
1077 public abstract URLConnection openConnection(URL url, Proxy proxy) throws IO Exception;
1078
1079 /**
1080 * Creates a {@link URLStreamHandlerFactory} to handle HTTP and HTTPS 428 * Creates a {@link URLStreamHandlerFactory} to handle HTTP and HTTPS
1081 * traffic. An instance of this class can be installed via 429 * traffic. An instance of this class can be installed via
1082 * {@link URL#setURLStreamHandlerFactory} thus using this CronetEngine by de fault for 430 * {@link URL#setURLStreamHandlerFactory} thus using this CronetEngine by de fault for
1083 * all requests created via {@link URL#openConnection}. 431 * all requests created via {@link URL#openConnection}.
1084 * <p> 432 * <p>
1085 * Cronet does not use certain HTTP features provided via the system: 433 * Cronet does not use certain HTTP features provided via the system:
1086 * <ul> 434 * <ul>
1087 * <li>the HTTP cache installed via 435 * <li>the HTTP cache installed via
1088 * {@link HttpResponseCache#install(java.io.File, long) HttpResponseCach e.install()}</li> 436 * {@link HttpResponseCache#install(java.io.File, long) HttpResponseCach e.install()}</li>
1089 * <li>the HTTP authentication method installed via 437 * <li>the HTTP authentication method installed via
(...skipping 12 matching lines...) Expand all
1102 * <li>the HTTPS socket factory installed via {@link 450 * <li>the HTTPS socket factory installed via {@link
1103 * HttpsURLConnection#setDefaultSSLSocketFactory(javax.net.ssl.SSLSocketFa ctory) 451 * HttpsURLConnection#setDefaultSSLSocketFactory(javax.net.ssl.SSLSocketFa ctory)
1104 * HttpsURLConnection.setDefaultSSLSocketFactory()}</li> 452 * HttpsURLConnection.setDefaultSSLSocketFactory()}</li>
1105 * </ul> 453 * </ul>
1106 * 454 *
1107 * @return an {@link URLStreamHandlerFactory} instance implemented by this 455 * @return an {@link URLStreamHandlerFactory} instance implemented by this
1108 * CronetEngine. 456 * CronetEngine.
1109 */ 457 */
1110 public abstract URLStreamHandlerFactory createURLStreamHandlerFactory(); 458 public abstract URLStreamHandlerFactory createURLStreamHandlerFactory();
1111 459
1112 private static CronetEngine createCronetEngine(Builder builder) {
1113 CronetEngine cronetEngine = null;
1114 try {
1115 Class<? extends CronetEngine> engineClass =
1116 builder.getContext()
1117 .getClassLoader()
1118 .loadClass(CRONET_URL_REQUEST_CONTEXT)
1119 .asSubclass(CronetEngine.class);
1120 Constructor<? extends CronetEngine> constructor =
1121 engineClass.getConstructor(Builder.class);
1122 CronetEngine possibleEngine = constructor.newInstance(builder);
1123 if (possibleEngine.isEnabled()) {
1124 cronetEngine = possibleEngine;
1125 }
1126 } catch (ClassNotFoundException e) {
1127 // Leave as null.
1128 } catch (Exception e) {
1129 throw new IllegalStateException("Cannot instantiate: " + CRONET_URL_ REQUEST_CONTEXT, e);
1130 }
1131 return cronetEngine;
1132 }
1133
1134 /** 460 /**
1135 * Registers a listener that gets called after the end of each request with the request info. 461 * Creates a builder for {@link UrlRequest} objects. All callbacks for
462 * generated {@link UrlRequest} objects will be invoked on
463 * {@code executor}'s thread. {@code executor} must not run tasks on the
464 * current thread to prevent blocking networking operations and causing
465 * exceptions during shutdown.
1136 * 466 *
1137 * <p>This must be called after {@link #enableNetworkQualityEstimator} and w ill throw an 467 * @param url {@link java.net.URL} for the generated requests.
1138 * exception otherwise. 468 * @param callback callback object that gets invoked on different events.
1139 * 469 * @param executor {@link Executor} on which all callbacks will be invoked.
1140 * <p>The listener is called on the {@link java.util.concurrent.Executor} th at
1141 * is passed to {@link #enableNetworkQualityEstimator}.
1142 *
1143 * @param listener the listener for finished requests.
1144 *
1145 * @hide as it's a prototype.
1146 */ 470 */
1147 public abstract void addRequestFinishedListener(RequestFinishedInfo.Listener listener); 471 public abstract UrlRequest.Builder newUrlRequestBuilder(
1148 472 String url, UrlRequest.Callback callback, Executor executor);
1149 /**
1150 * Removes a finished request listener.
1151 *
1152 * @param listener the listener to remove.
1153 *
1154 * @hide it's a prototype.
1155 */
1156 public abstract void removeRequestFinishedListener(RequestFinishedInfo.Liste ner listener);
1157 } 473 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698