OLD | NEW |
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. An instance of this class can be created |
| 23 * using {@link Builder}. |
40 */ | 24 */ |
41 public abstract class CronetEngine { | 25 public abstract class CronetEngine { |
42 /** | 26 /** |
43 * A builder for {@link CronetEngine}s, which allows runtime configuration o
f | 27 * A builder for {@link CronetEngine}s, which allows runtime configuration o
f |
44 * {@code CronetEngine}. Configuration options are set on the builder and | 28 * {@code CronetEngine}. Configuration options are set on the builder and |
45 * then {@link #build} is called to create the {@code CronetEngine}. | 29 * then {@link #build} is called to create the {@code CronetEngine}. |
46 */ | 30 */ |
| 31 // NOTE(kapishnikov): In order to avoid breaking the existing API clients, a
ll future methods |
| 32 // added to this class and other API classes must have default implementatio
n. |
47 public static class Builder { | 33 public static class Builder { |
| 34 // The class name of the Cronet Engine Builder implementation. |
| 35 private static final String CRONET_ENGINE_BUILDER_IMPL = |
| 36 "org.chromium.net.impl.CronetEngineBuilderImpl"; |
| 37 |
48 /** | 38 /** |
49 * A class which provides a method for loading the cronet native library
. Apps needing to | 39 * 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 | 40 * 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 | 41 * 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 | 42 * to work around {@code UnsatisfiedLinkError}s caused by flaky installa
tion on certain |
53 * older devices. | 43 * older devices. |
54 */ | 44 */ |
55 public abstract static class LibraryLoader { | 45 public abstract static class LibraryLoader { |
56 /** | 46 /** |
57 * Loads the native library. | 47 * Loads the native library. |
58 * @param libName name of the library to load | 48 * @param libName name of the library to load |
59 */ | 49 */ |
60 public abstract void loadLibrary(String libName); | 50 public abstract void loadLibrary(String libName); |
61 } | 51 } |
62 | 52 |
63 /** | 53 /** |
64 * A hint that a host supports QUIC. | 54 * Reference to the actual builder implementation. |
65 * @hide only used by internal implementation. | 55 * {@hide exclude from JavaDoc}. |
66 */ | 56 */ |
67 public static class QuicHint { | 57 protected final ICronetEngineBuilder mBuilderDelegate; |
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 | 58 |
132 /** | 59 /** |
133 * Default config enables SPDY, disables QUIC, SDCH and HTTP cache. | 60 * Default config enables SPDY, disables QUIC, SDCH and HTTP cache. |
134 * @param context Android {@link Context} for engine to use. | 61 * @param context Android {@link Context} for engine to use. |
135 */ | 62 */ |
136 public Builder(Context context) { | 63 public Builder(Context context) { |
137 mContext = context; | 64 try { |
138 setLibraryName("cronet"); | 65 Class<? extends ICronetEngineBuilder> delegateImplClass = |
139 enableLegacyMode(false); | 66 Class.forName(CRONET_ENGINE_BUILDER_IMPL) |
140 enableQuic(false); | 67 .asSubclass(ICronetEngineBuilder.class); |
141 enableHttp2(true); | 68 Constructor<? extends ICronetEngineBuilder> ctor = |
142 enableSdch(false); | 69 delegateImplClass.getConstructor(Context.class); |
143 enableHttpCache(HTTP_CACHE_DISABLED, 0); | 70 mBuilderDelegate = ctor.newInstance(context); |
144 enableNetworkQualityEstimator(false); | 71 } catch (Exception e) { |
145 enablePublicKeyPinningBypassForLocalTrustAnchors(true); | 72 throw new RuntimeException( |
| 73 "Unable to construct the implementation of the Cronet En
gine Builder: " |
| 74 + CRONET_ENGINE_BUILDER_IMPL, |
| 75 e); |
| 76 } |
146 } | 77 } |
147 | 78 |
148 /** | 79 /** |
149 * Constructs a User-Agent string including application name and version
, | 80 * Constructs a User-Agent string including application name and version
, |
150 * system build version, model and id, and Cronet version. | 81 * system build version, model and id, and Cronet version. |
151 * | 82 * |
152 * @return User-Agent string. | 83 * @return User-Agent string. |
153 */ | 84 */ |
154 public String getDefaultUserAgent() { | 85 public String getDefaultUserAgent() { |
155 return UserAgent.from(mContext); | 86 return mBuilderDelegate.getDefaultUserAgent(); |
156 } | 87 } |
157 | 88 |
158 /** | 89 /** |
159 * Overrides the User-Agent header for all requests. An explicitly | 90 * Overrides the User-Agent header for all requests. An explicitly |
160 * set User-Agent header (set using | 91 * set User-Agent header (set using |
161 * {@link UrlRequest.Builder#addHeader}) will override a value set | 92 * {@link UrlRequest.Builder#addHeader}) will override a value set |
162 * using this function. | 93 * using this function. |
163 * | 94 * |
164 * @param userAgent the User-Agent string to use for all requests. | 95 * @param userAgent the User-Agent string to use for all requests. |
165 * @return the builder to facilitate chaining. | 96 * @return the builder to facilitate chaining. |
166 */ | 97 */ |
167 public Builder setUserAgent(String userAgent) { | 98 public Builder setUserAgent(String userAgent) { |
168 mUserAgent = userAgent; | 99 mBuilderDelegate.setUserAgent(userAgent); |
169 return this; | 100 return this; |
170 } | 101 } |
171 | 102 |
172 /** | 103 /** |
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 | 104 * Sets directory for HTTP Cache and Cookie Storage. The directory must |
181 * exist. | 105 * exist. |
182 * <p> | 106 * <p> |
183 * <b>NOTE:</b> Do not use the same storage directory with more than one | 107 * <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 | 108 * {@code CronetEngine} at a time. Access to the storage directory does |
185 * not support concurrent access by multiple {@code CronetEngine}s. | 109 * not support concurrent access by multiple {@code CronetEngine}s. |
186 * | 110 * |
187 * @param value path to existing directory. | 111 * @param value path to existing directory. |
188 * @return the builder to facilitate chaining. | 112 * @return the builder to facilitate chaining. |
189 */ | 113 */ |
190 public Builder setStoragePath(String value) { | 114 public Builder setStoragePath(String value) { |
191 if (!new File(value).isDirectory()) { | 115 mBuilderDelegate.setStoragePath(value); |
192 throw new IllegalArgumentException( | |
193 "Storage path must be set to existing directory"); | |
194 } | |
195 mStoragePath = value; | |
196 return this; | 116 return this; |
197 } | 117 } |
198 | 118 |
199 /** | 119 /** |
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. | 120 * 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}. | 121 * 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. | 122 * @param loader {@code LibraryLoader} to be used to load the native lib
rary. |
259 * @return the builder to facilitate chaining. | 123 * @return the builder to facilitate chaining. |
260 */ | 124 */ |
261 public Builder setLibraryLoader(LibraryLoader loader) { | 125 public Builder setLibraryLoader(LibraryLoader loader) { |
262 mLibraryLoader = loader; | 126 mBuilderDelegate.setLibraryLoader(loader); |
263 return this; | 127 return this; |
264 } | 128 } |
265 | 129 |
266 /** | 130 /** |
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 | 131 * 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 | 132 * 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. | 133 * containing application name and Cronet version is sent to the server. |
277 * @param value {@code true} to enable QUIC, {@code false} to disable. | 134 * @param value {@code true} to enable QUIC, {@code false} to disable. |
278 * @return the builder to facilitate chaining. | 135 * @return the builder to facilitate chaining. |
279 */ | 136 */ |
280 public Builder enableQuic(boolean value) { | 137 public Builder enableQuic(boolean value) { |
281 mQuicEnabled = value; | 138 mBuilderDelegate.enableQuic(value); |
282 return this; | 139 return this; |
283 } | 140 } |
284 | 141 |
285 /** | 142 /** |
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> | 143 * Sets whether <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> |
307 * protocol is enabled. Defaults to enabled. | 144 * protocol is enabled. Defaults to enabled. |
308 * @param value {@code true} to enable HTTP/2, {@code false} to disable. | 145 * @param value {@code true} to enable HTTP/2, {@code false} to disable. |
309 * @return the builder to facilitate chaining. | 146 * @return the builder to facilitate chaining. |
310 */ | 147 */ |
311 public Builder enableHttp2(boolean value) { | 148 public Builder enableHttp2(boolean value) { |
312 mHttp2Enabled = value; | 149 mBuilderDelegate.enableHttp2(value); |
313 return this; | 150 return this; |
314 } | 151 } |
315 | 152 |
316 /** | 153 /** |
317 * @hide only used by internal implementation. | |
318 */ | |
319 public boolean http2Enabled() { | |
320 return mHttp2Enabled; | |
321 } | |
322 | |
323 /** | |
324 * Sets whether | 154 * Sets whether |
325 * <a | 155 * <a |
326 * href="https://lists.w3.org/Archives/Public/ietf-http-wg/2008JulSep/at
t-0441/Shared_Dictionary_Compression_over_HTTP.pdf"> | 156 * 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. | 157 * SDCH</a> compression is enabled. Defaults to disabled. |
328 * @param value {@code true} to enable SDCH, {@code false} to disable. | 158 * @param value {@code true} to enable SDCH, {@code false} to disable. |
329 * @return the builder to facilitate chaining. | 159 * @return the builder to facilitate chaining. |
330 */ | 160 */ |
331 public Builder enableSdch(boolean value) { | 161 public Builder enableSdch(boolean value) { |
332 mSdchEnabled = value; | 162 mBuilderDelegate.enableSdch(value); |
333 return this; | 163 return this; |
334 } | 164 } |
335 | 165 |
336 /** | 166 /** |
337 * @hide only used by internal implementation. | |
338 */ | |
339 public boolean sdchEnabled() { | |
340 return mSdchEnabled; | |
341 } | |
342 | |
343 /** | |
344 * Enables | |
345 * <a href="https://developer.chrome.com/multidevice/data-compression">D
ata | |
346 * Reduction Proxy</a>. Defaults to disabled. | |
347 * @param key key to use when authenticating with the proxy. | |
348 * @return the builder to facilitate chaining. | |
349 */ | |
350 public Builder enableDataReductionProxy(String key) { | |
351 mDataReductionProxyKey = key; | |
352 return this; | |
353 } | |
354 | |
355 /** | |
356 * @hide only used by internal implementation. | |
357 */ | |
358 public String dataReductionProxyKey() { | |
359 return mDataReductionProxyKey; | |
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; | |
386 } | |
387 | |
388 /** | |
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. | 167 * Setting to disable HTTP cache. Some data may still be temporarily sto
red in memory. |
418 * Passed to {@link #enableHttpCache}. | 168 * Passed to {@link #enableHttpCache}. |
419 */ | 169 */ |
420 public static final int HTTP_CACHE_DISABLED = 0; | 170 public static final int HTTP_CACHE_DISABLED = 0; |
421 | 171 |
422 /** | 172 /** |
423 * Setting to enable in-memory HTTP cache, including HTTP data. | 173 * Setting to enable in-memory HTTP cache, including HTTP data. |
424 * Passed to {@link #enableHttpCache}. | 174 * Passed to {@link #enableHttpCache}. |
425 */ | 175 */ |
426 public static final int HTTP_CACHE_IN_MEMORY = 1; | 176 public static final int HTTP_CACHE_IN_MEMORY = 1; |
(...skipping 14 matching lines...) Expand all Loading... |
441 | 191 |
442 /** | 192 /** |
443 * Enables or disables caching of HTTP data and other information like Q
UIC | 193 * Enables or disables caching of HTTP data and other information like Q
UIC |
444 * server information. | 194 * server information. |
445 * @param cacheMode control location and type of cached data. Must be on
e of | 195 * @param cacheMode control location and type of cached data. Must be on
e of |
446 * {@link #HTTP_CACHE_DISABLED HTTP_CACHE_*}. | 196 * {@link #HTTP_CACHE_DISABLED HTTP_CACHE_*}. |
447 * @param maxSize maximum size in bytes used to cache data (advisory and
maybe | 197 * @param maxSize maximum size in bytes used to cache data (advisory and
maybe |
448 * exceeded at times). | 198 * exceeded at times). |
449 * @return the builder to facilitate chaining. | 199 * @return the builder to facilitate chaining. |
450 */ | 200 */ |
451 public Builder enableHttpCache(@HttpCacheSetting int cacheMode, long max
Size) { | 201 public Builder enableHttpCache(int cacheMode, long maxSize) { |
452 if (cacheMode == HTTP_CACHE_DISK || cacheMode == HTTP_CACHE_DISK_NO_
HTTP) { | 202 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; | 203 return this; |
480 } | 204 } |
481 | 205 |
482 /** | 206 /** |
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. | 207 * Adds hint that {@code host} supports QUIC. |
505 * Note that {@link #enableHttpCache enableHttpCache} | 208 * Note that {@link #enableHttpCache enableHttpCache} |
506 * ({@link #HTTP_CACHE_DISK}) is needed to take advantage of 0-RTT | 209 * ({@link #HTTP_CACHE_DISK}) is needed to take advantage of 0-RTT |
507 * connection establishment between sessions. | 210 * connection establishment between sessions. |
508 * | 211 * |
509 * @param host hostname of the server that supports QUIC. | 212 * @param host hostname of the server that supports QUIC. |
510 * @param port host of the server that supports QUIC. | 213 * @param port host of the server that supports QUIC. |
511 * @param alternatePort alternate port to use for QUIC. | 214 * @param alternatePort alternate port to use for QUIC. |
512 * @return the builder to facilitate chaining. | 215 * @return the builder to facilitate chaining. |
513 */ | 216 */ |
514 public Builder addQuicHint(String host, int port, int alternatePort) { | 217 public Builder addQuicHint(String host, int port, int alternatePort) { |
515 if (host.contains("/")) { | 218 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; | 219 return this; |
520 } | 220 } |
521 | 221 |
522 /** | 222 /** |
523 * @hide only used by internal implementation. | |
524 */ | |
525 public List<QuicHint> quicHints() { | |
526 return mQuicHints; | |
527 } | |
528 | |
529 /** | |
530 * <p> | 223 * <p> |
531 * Pins a set of public keys for a given host. By pinning a set of publi
c keys, | 224 * 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 | 225 * {@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. | 226 * 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 | 227 * 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 | 228 * 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 | 229 * 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 | 230 * 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. | 231 * certificate allowed by the device's trusted store of certificates. |
539 * </p> | 232 * </p> |
(...skipping 22 matching lines...) Expand all Loading... |
562 * subdomains of {@code hostName}. | 255 * subdomains of {@code hostName}. |
563 * @param expirationDate specifies the expiration date for the pins. | 256 * @param expirationDate specifies the expiration date for the pins. |
564 * @return the builder to facilitate chaining. | 257 * @return the builder to facilitate chaining. |
565 * @throws NullPointerException if any of the input parameters are {@cod
e null}. | 258 * @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} | 259 * @throws IllegalArgumentException if the given host name is invalid or
{@code pinsSha256} |
567 * contains a byte array that does not
represent a valid | 260 * contains a byte array that does not
represent a valid |
568 * SHA-256 hash. | 261 * SHA-256 hash. |
569 */ | 262 */ |
570 public Builder addPublicKeyPins(String hostName, Set<byte[]> pinsSha256, | 263 public Builder addPublicKeyPins(String hostName, Set<byte[]> pinsSha256, |
571 boolean includeSubdomains, Date expirationDate) { | 264 boolean includeSubdomains, Date expirationDate) { |
572 if (hostName == null) { | 265 mBuilderDelegate.addPublicKeyPins( |
573 throw new NullPointerException("The hostname cannot be null"); | 266 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; | 267 return this; |
594 } | 268 } |
595 | 269 |
596 /** | 270 /** |
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 | 271 * 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 | 272 * 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 | 273 * 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 | 274 * 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 | 275 * 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 | 276 * 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 | 277 * information see 'How does key pinning interact with local proxies and
filters?' at |
613 * https://www.chromium.org/Home/chromium-security/security-faq | 278 * https://www.chromium.org/Home/chromium-security/security-faq |
614 * | 279 * |
615 * @param value {@code true} to enable the bypass, {@code false} to disa
ble. | 280 * @param value {@code true} to enable the bypass, {@code false} to disa
ble. |
616 * @return the builder to facilitate chaining. | 281 * @return the builder to facilitate chaining. |
617 */ | 282 */ |
618 public Builder enablePublicKeyPinningBypassForLocalTrustAnchors(boolean
value) { | 283 public Builder enablePublicKeyPinningBypassForLocalTrustAnchors(boolean
value) { |
619 mPublicKeyPinningBypassForLocalTrustAnchorsEnabled = value; | 284 mBuilderDelegate.enablePublicKeyPinningBypassForLocalTrustAnchors(va
lue); |
620 return this; | 285 return this; |
621 } | 286 } |
622 | 287 |
623 /** | 288 /** |
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. | 289 * Sets experimental options to be used in Cronet. |
666 * | 290 * |
667 * @param options JSON formatted experimental options. | 291 * @param options JSON formatted experimental options. |
668 * @return the builder to facilitate chaining. | 292 * @return the builder to facilitate chaining. |
669 */ | 293 */ |
670 public Builder setExperimentalOptions(String options) { | 294 public Builder setExperimentalOptions(String options) { |
671 mExperimentalOptions = options; | 295 mBuilderDelegate.setExperimentalOptions(options); |
672 return this; | 296 return this; |
673 } | 297 } |
674 | 298 |
675 /** | 299 /** |
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. | 300 * Build a {@link CronetEngine} using this builder's configuration. |
762 * @return constructed {@link CronetEngine}. | 301 * @return constructed {@link CronetEngine}. |
763 */ | 302 */ |
764 public CronetEngine build() { | 303 public CronetEngine build() { |
765 if (getUserAgent() == null) { | 304 return mBuilderDelegate.build(); |
766 setUserAgent(getDefaultUserAgent()); | |
767 } | |
768 CronetEngine cronetEngine = null; | |
769 if (!legacyMode()) { | |
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 } | 305 } |
781 } | 306 } |
782 | 307 |
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 /** | 308 /** |
895 * @return a human-readable version string of the engine. | 309 * @return a human-readable version string of the engine. |
896 */ | 310 */ |
897 public abstract String getVersionString(); | 311 public abstract String getVersionString(); |
898 | 312 |
899 /** | 313 /** |
900 * Shuts down the {@link CronetEngine} if there are no active requests, | 314 * Shuts down the {@link CronetEngine} if there are no active requests, |
901 * otherwise throws an exception. | 315 * otherwise throws an exception. |
902 * | 316 * |
903 * Cannot be called on network thread - the thread Cronet calls into | 317 * Cannot be called on network thread - the thread Cronet calls into |
(...skipping 14 matching lines...) Expand all Loading... |
918 * @param logAll {@code true} to include basic events, user cookies, | 332 * @param logAll {@code true} to include basic events, user cookies, |
919 * credentials and all transferred bytes in the log. This option
presents | 333 * 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 | 334 * 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 | 335 * only be used with the user's consent and in situations where t
he log |
922 * won't be public. | 336 * won't be public. |
923 * {@code false} to just include basic events. | 337 * {@code false} to just include basic events. |
924 */ | 338 */ |
925 public abstract void startNetLogToFile(String fileName, boolean logAll); | 339 public abstract void startNetLogToFile(String fileName, boolean logAll); |
926 | 340 |
927 /** | 341 /** |
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 | 342 * Stops NetLog logging and flushes file to disk. If a logging session is |
947 * not in progress, this call is ignored. | 343 * not in progress, this call is ignored. |
948 */ | 344 */ |
949 public abstract void stopNetLog(); | 345 public abstract void stopNetLog(); |
950 | 346 |
951 /** | 347 /** |
952 * Returns serialized representation of certificate verifier's cache | |
953 * which contains the list of hosts/certificates and the certificate | |
954 * verification results. May block until data is received from the network | |
955 * thread (will timeout after the specified timeout). In case of timeout, it | |
956 * returns the previous saved value. | |
957 * | |
958 * @param timeout in milliseconds. If timeout is 0, it will use default valu
e. | |
959 * @return serialized representation of certificate verification results | |
960 * data. | |
961 */ | |
962 public abstract String getCertVerifierData(long timeout); | |
963 | |
964 /** | |
965 * Returns differences in metrics collected by Cronet since the last call to | 348 * Returns differences in metrics collected by Cronet since the last call to |
966 * {@link #getGlobalMetricsDeltas}. | 349 * this method. |
967 * <p> | 350 * <p> |
968 * Cronet collects these metrics globally. This means deltas returned by | 351 * Cronet collects these metrics globally. This means deltas returned by |
969 * {@code getGlobalMetricsDeltas()} will include measurements of requests | 352 * {@code getGlobalMetricsDeltas()} will include measurements of requests |
970 * processed by other {@link CronetEngine} instances. Since this function | 353 * processed by other {@link CronetEngine} instances. Since this function |
971 * returns differences in metrics collected since the last call, and these | 354 * returns differences in metrics collected since the last call, and these |
972 * metrics are collected globally, a call to any {@code CronetEngine} | 355 * metrics are collected globally, a call to any {@code CronetEngine} |
973 * instance's {@code getGlobalMetricsDeltas()} method will affect the deltas | 356 * instance's {@code getGlobalMetricsDeltas()} method will affect the deltas |
974 * returned by any other {@code CronetEngine} instance's | 357 * returned by any other {@code CronetEngine} instance's |
975 * {@code getGlobalMetricsDeltas()}. | 358 * {@code getGlobalMetricsDeltas()}. |
976 * <p> | 359 * <p> |
977 * Cronet starts collecting these metrics after the first call to | 360 * Cronet starts collecting these metrics after the first call to |
978 * {@code getGlobalMetricsDeltras()}, so the first call returns no | 361 * {@code getGlobalMetricsDeltras()}, so the first call returns no |
979 * useful data as no metrics have yet been collected. | 362 * useful data as no metrics have yet been collected. |
980 * | 363 * |
981 * @return differences in metrics collected by Cronet, since the last call | 364 * @return differences in metrics collected by Cronet, since the last call |
982 * to {@code getGlobalMetricsDeltas()}, serialized as a | 365 * to {@code getGlobalMetricsDeltas()}, serialized as a |
983 * <a href=https://developers.google.com/protocol-buffers>protobuf | 366 * <a href=https://developers.google.com/protocol-buffers>protobuf |
984 * </a>. | 367 * </a>. |
985 */ | 368 */ |
986 public abstract byte[] getGlobalMetricsDeltas(); | 369 public abstract byte[] getGlobalMetricsDeltas(); |
987 | 370 |
988 /** | 371 /** |
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 * Returns the HTTP RTT estimate (in milliseconds) computed by the network | |
997 * quality estimator. Set to | |
998 * {@link RttThroughputValues.INVALID_RTT_THROUGHPUT} if a valid value | |
999 * is unavailable. This must be called after | |
1000 * {@link #enableNetworkQualityEstimator}, and will throw an | |
1001 * exception otherwise. | |
1002 * @hide as it's a prototype. | |
1003 * @return Estimate of the HTTP RTT in milliseconds. | |
1004 */ | |
1005 public abstract int getHttpRttMs(); | |
1006 | |
1007 /** | |
1008 * Returns the transport RTT estimate (in milliseconds) computed by the | |
1009 * network quality estimator. Set to | |
1010 * {@link RttThroughputValues.INVALID_RTT_THROUGHPUT} if a valid value is | |
1011 * unavailable. This must be called after | |
1012 * {@link #enableNetworkQualityEstimator}, and will throw an | |
1013 * exception otherwise. | |
1014 * @hide as it's a prototype. | |
1015 * @return Estimate of the transport RTT in milliseconds. | |
1016 */ | |
1017 public abstract int getTransportRttMs(); | |
1018 | |
1019 /** | |
1020 * Returns the downstream throughput estimate (in kilobits per second) | |
1021 * computed by the network quality estimator. Set to | |
1022 * {@link RttThroughputValues.INVALID_RTT_THROUGHPUT} if a valid value is | |
1023 * unavailable. This must be called after | |
1024 * {@link #enableNetworkQualityEstimator}, and will | |
1025 * throw an exception otherwise. | |
1026 * @hide as it's a prototype. | |
1027 * @return Estimate of the downstream throughput in kilobits per second. | |
1028 */ | |
1029 public abstract int getDownstreamThroughputKbps(); | |
1030 | |
1031 /** | |
1032 * Configures the network quality estimator for testing. This must be called | |
1033 * before round trip time and throughput listeners are added, and after the | |
1034 * network quality estimator has been enabled. | |
1035 * @param useLocalHostRequests include requests to localhost in estimates. | |
1036 * @param useSmallerResponses include small responses in throughput | |
1037 * estimates. | |
1038 * @hide as it's a prototype. | |
1039 */ | |
1040 public abstract void configureNetworkQualityEstimatorForTesting( | |
1041 boolean useLocalHostRequests, boolean useSmallerResponses); | |
1042 | |
1043 /** | |
1044 * Registers a listener that gets called whenever the network quality | |
1045 * estimator witnesses a sample round trip time. This must be called | |
1046 * after {@link #enableNetworkQualityEstimator}, and with throw an | |
1047 * exception otherwise. Round trip times may be recorded at various layers | |
1048 * of the network stack, including TCP, QUIC, and at the URL request layer. | |
1049 * The listener is called on the {@link java.util.concurrent.Executor} that | |
1050 * is passed to {@link #enableNetworkQualityEstimator}. | |
1051 * @param listener the listener of round trip times. | |
1052 * @hide as it's a prototype. | |
1053 */ | |
1054 public abstract void addRttListener(NetworkQualityRttListener listener); | |
1055 | |
1056 /** | |
1057 * Removes a listener of round trip times if previously registered with | |
1058 * {@link #addRttListener}. This should be called after a | |
1059 * {@link NetworkQualityRttListener} is added in order to stop receiving | |
1060 * observations. | |
1061 * @param listener the listener of round trip times. | |
1062 * @hide as it's a prototype. | |
1063 */ | |
1064 public abstract void removeRttListener(NetworkQualityRttListener listener); | |
1065 | |
1066 /** | |
1067 * Registers a listener that gets called whenever the network quality | |
1068 * estimator witnesses a sample throughput measurement. This must be called | |
1069 * after {@link #enableNetworkQualityEstimator}. Throughput observations | |
1070 * are computed by measuring bytes read over the active network interface | |
1071 * at times when at least one URL response is being received. The listener | |
1072 * is called on the {@link java.util.concurrent.Executor} that is passed to | |
1073 * {@link #enableNetworkQualityEstimator}. | |
1074 * @param listener the listener of throughput. | |
1075 * @hide as it's a prototype. | |
1076 */ | |
1077 public abstract void addThroughputListener(NetworkQualityThroughputListener
listener); | |
1078 | |
1079 /** | |
1080 * Removes a listener of throughput. This should be called after a | |
1081 * {@link NetworkQualityThroughputListener} is added with | |
1082 * {@link #addThroughputListener} in order to stop receiving observations. | |
1083 * @param listener the listener of throughput. | |
1084 * @hide as it's a prototype. | |
1085 */ | |
1086 public abstract void removeThroughputListener(NetworkQualityThroughputListen
er listener); | |
1087 | |
1088 /** | |
1089 * Establishes a new connection to the resource specified by the {@link URL}
{@code url}. | 372 * Establishes a new connection to the resource specified by the {@link URL}
{@code url}. |
1090 * <p> | 373 * <p> |
1091 * <b>Note:</b> Cronet's {@link java.net.HttpURLConnection} implementation i
s subject to certain | 374 * <b>Note:</b> Cronet's {@link java.net.HttpURLConnection} implementation i
s subject to certain |
1092 * limitations, see {@link #createURLStreamHandlerFactory} for details. | 375 * limitations, see {@link #createURLStreamHandlerFactory} for details. |
1093 * | 376 * |
1094 * @param url URL of resource to connect to. | 377 * @param url URL of resource to connect to. |
1095 * @return an {@link java.net.HttpURLConnection} instance implemented by thi
s CronetEngine. | 378 * @return an {@link java.net.HttpURLConnection} instance implemented by thi
s CronetEngine. |
1096 * @throws IOException if an error occurs while opening the connection. | 379 * @throws IOException if an error occurs while opening the connection. |
1097 */ | 380 */ |
1098 public abstract URLConnection openConnection(URL url) throws IOException; | 381 public abstract URLConnection openConnection(URL url) throws IOException; |
1099 | 382 |
1100 /** | 383 /** |
1101 * Establishes a new connection to the resource specified by the {@link URL}
{@code url} | |
1102 * using the given proxy. | |
1103 * <p> | |
1104 * <b>Note:</b> Cronet's {@link java.net.HttpURLConnection} implementation i
s subject to certain | |
1105 * limitations, see {@link #createURLStreamHandlerFactory} for details. | |
1106 * | |
1107 * @param url URL of resource to connect to. | |
1108 * @param proxy proxy to use when establishing connection. | |
1109 * @return an {@link java.net.HttpURLConnection} instance implemented by thi
s CronetEngine. | |
1110 * @throws IOException if an error occurs while opening the connection. | |
1111 * @hide TODO(pauljensen): Expose once implemented, http://crbug.com/418111 | |
1112 */ | |
1113 public abstract URLConnection openConnection(URL url, Proxy proxy) throws IO
Exception; | |
1114 | |
1115 /** | |
1116 * Creates a {@link URLStreamHandlerFactory} to handle HTTP and HTTPS | 384 * Creates a {@link URLStreamHandlerFactory} to handle HTTP and HTTPS |
1117 * traffic. An instance of this class can be installed via | 385 * traffic. An instance of this class can be installed via |
1118 * {@link URL#setURLStreamHandlerFactory} thus using this CronetEngine by de
fault for | 386 * {@link URL#setURLStreamHandlerFactory} thus using this CronetEngine by de
fault for |
1119 * all requests created via {@link URL#openConnection}. | 387 * all requests created via {@link URL#openConnection}. |
1120 * <p> | 388 * <p> |
1121 * Cronet does not use certain HTTP features provided via the system: | 389 * Cronet does not use certain HTTP features provided via the system: |
1122 * <ul> | 390 * <ul> |
1123 * <li>the HTTP cache installed via | 391 * <li>the HTTP cache installed via |
1124 * {@link HttpResponseCache#install(java.io.File, long) HttpResponseCach
e.install()}</li> | 392 * {@link HttpResponseCache#install(java.io.File, long) HttpResponseCach
e.install()}</li> |
1125 * <li>the HTTP authentication method installed via | 393 * <li>the HTTP authentication method installed via |
(...skipping 12 matching lines...) Expand all Loading... |
1138 * <li>the HTTPS socket factory installed via {@link | 406 * <li>the HTTPS socket factory installed via {@link |
1139 * HttpsURLConnection#setDefaultSSLSocketFactory(javax.net.ssl.SSLSocketFa
ctory) | 407 * HttpsURLConnection#setDefaultSSLSocketFactory(javax.net.ssl.SSLSocketFa
ctory) |
1140 * HttpsURLConnection.setDefaultSSLSocketFactory()}</li> | 408 * HttpsURLConnection.setDefaultSSLSocketFactory()}</li> |
1141 * </ul> | 409 * </ul> |
1142 * | 410 * |
1143 * @return an {@link URLStreamHandlerFactory} instance implemented by this | 411 * @return an {@link URLStreamHandlerFactory} instance implemented by this |
1144 * CronetEngine. | 412 * CronetEngine. |
1145 */ | 413 */ |
1146 public abstract URLStreamHandlerFactory createURLStreamHandlerFactory(); | 414 public abstract URLStreamHandlerFactory createURLStreamHandlerFactory(); |
1147 | 415 |
1148 private static CronetEngine createCronetEngine(Builder builder) { | |
1149 CronetEngine cronetEngine = null; | |
1150 try { | |
1151 Class<? extends CronetEngine> engineClass = | |
1152 builder.getContext() | |
1153 .getClassLoader() | |
1154 .loadClass(CRONET_URL_REQUEST_CONTEXT) | |
1155 .asSubclass(CronetEngine.class); | |
1156 Constructor<? extends CronetEngine> constructor = | |
1157 engineClass.getConstructor(Builder.class); | |
1158 CronetEngine possibleEngine = constructor.newInstance(builder); | |
1159 if (possibleEngine.isEnabled()) { | |
1160 cronetEngine = possibleEngine; | |
1161 } | |
1162 } catch (ClassNotFoundException e) { | |
1163 // Leave as null. | |
1164 } catch (Exception e) { | |
1165 throw new IllegalStateException("Cannot instantiate: " + CRONET_URL_
REQUEST_CONTEXT, e); | |
1166 } | |
1167 return cronetEngine; | |
1168 } | |
1169 | |
1170 /** | 416 /** |
1171 * Registers a listener that gets called after the end of each request with
the request info. | 417 * Creates a builder for {@link UrlRequest}. All callbacks for |
1172 * | |
1173 * <p>The listener is called on an {@link java.util.concurrent.Executor} pro
vided by the | |
1174 * listener. | |
1175 * | |
1176 * @param listener the listener for finished requests. | |
1177 * | |
1178 * @hide as it's a prototype. | |
1179 */ | |
1180 public abstract void addRequestFinishedListener(RequestFinishedInfo.Listener
listener); | |
1181 | |
1182 /** | |
1183 * Removes a finished request listener. | |
1184 * | |
1185 * @param listener the listener to remove. | |
1186 * | |
1187 * @hide it's a prototype. | |
1188 */ | |
1189 public abstract void removeRequestFinishedListener(RequestFinishedInfo.Liste
ner listener); | |
1190 | |
1191 /** | |
1192 * Creates a builder for {@link UrlRequest}. All callbacks formatted | |
1193 * generated {@link UrlRequest} objects will be invoked on | 418 * generated {@link UrlRequest} objects will be invoked on |
1194 * {@code executor}'s threads. {@code executor} must not run tasks on the | 419 * {@code executor}'s threads. {@code executor} must not run tasks on the |
1195 * thread calling {@link Executor#execute} to prevent blocking networking | 420 * thread calling {@link Executor#execute} to prevent blocking networking |
1196 * operations and causing exceptions during shutdown. | 421 * operations and causing exceptions during shutdown. |
1197 * | 422 * |
1198 * @param url URL for the generated requests. | 423 * @param url URL for the generated requests. |
1199 * @param callback callback object that gets invoked on different events. | 424 * @param callback callback object that gets invoked on different events. |
1200 * @param executor {@link Executor} on which all callbacks will be invoked. | 425 * @param executor {@link Executor} on which all callbacks will be invoked. |
1201 */ | 426 */ |
1202 public UrlRequest.Builder newUrlRequestBuilder( | 427 public abstract UrlRequest.Builder newUrlRequestBuilder( |
1203 String url, UrlRequest.Callback callback, Executor executor) { | 428 String url, UrlRequest.Callback callback, Executor executor); |
1204 return new UrlRequest.Builder(url, callback, executor, this); | |
1205 } | |
1206 } | 429 } |
OLD | NEW |