1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <jni.h>
6 #include <memory>
7 #include <string>
8 #include <utility>
9
10 #include "base/android/base_jni_onload.h"
11 #include "base/android/build_info.h"
12 #include "base/android/jni_android.h"
13 #include "base/android/jni_array.h"
14 #include "base/android/jni_registrar.h"
15 #include "base/android/jni_string.h"
16 #include "base/android/jni_utils.h"
17 #include "base/android/library_loader/library_loader_hooks.h"
18 #include "base/check_op.h"
19 #include "base/command_line.h"
20 #include "base/feature_list.h"
21 #include "base/message_loop/message_pump_type.h"
22 #include "base/metrics/field_trial_params.h"
23 #include "base/synchronization/waitable_event.h"
24 #include "base/task/current_thread.h"
25 #include "base/task/sequenced_task_runner.h"
26 #include "base/task/single_thread_task_executor.h"
27 #include "base/task/thread_pool/thread_pool_instance.h"
28 #include "build/build_config.h"
29 #include "components/cronet/android/cronet_base_feature.h"
30 #include "components/cronet/android/cronet_jni_headers/CronetLibraryLoader_jni.h"
31 #include "components/cronet/android/cronet_jni_registration_generated.h"
32 #include "components/cronet/android/cronet_library_loader.h"
33 #include "components/cronet/android/proto/base_feature_overrides.pb.h"
34 #include "components/cronet/cronet_global_state.h"
35 #include "components/cronet/version.h"
36 #include "net/android/network_change_notifier_factory_android.h"
37 #include "net/base/network_change_notifier.h"
38 #include "net/proxy_resolution/configured_proxy_resolution_service.h"
39 #include "net/proxy_resolution/proxy_config_service_android.h"
40 #include "third_party/zlib/zlib.h"
41 #include "url/buildflags.h"
42
43 #if !BUILDFLAG(USE_PLATFORM_ICU_ALTERNATIVES)
44 #include "base/i18n/icu_util.h" // nogncheck
45 #endif
46
47 using base::android::JavaParamRef;
48 using base::android::ScopedJavaLocalRef;
49
50 namespace cronet {
51 namespace {
52
53 // This feature flag can be used to make Cronet log a message from native code
54 // on library initialization. This is useful for testing that the Cronet
55 // base::Feature integration works.
56 BASE_FEATURE(kLogMe, "CronetLogMe", base::FEATURE_DISABLED_BY_DEFAULT);
57 constexpr base::FeatureParam<std::string> kLogMeMessage{&kLogMe, "message", ""};
58
59 // SingleThreadTaskExecutor on the init thread, which is where objects that
60 // receive Java notifications generally live.
61 base::SingleThreadTaskExecutor* g_init_task_executor = nullptr;
62
63 std::unique_ptr<net::NetworkChangeNotifier> g_network_change_notifier;
64 base::WaitableEvent g_init_thread_init_done(
65 base::WaitableEvent::ResetPolicy::MANUAL,
66 base::WaitableEvent::InitialState::NOT_SIGNALED);
67
GetBaseFeatureOverrides(JNIEnv * env)68 ::org::chromium::net::httpflags::BaseFeatureOverrides GetBaseFeatureOverrides(
69 JNIEnv* env) {
70 const auto serializedProto =
71 cronet::Java_CronetLibraryLoader_getBaseFeatureOverrides(env);
72 CHECK(serializedProto);
73
74 const auto serializedProtoSize =
75 base::android::SafeGetArrayLength(env, serializedProto);
76 ::org::chromium::net::httpflags::BaseFeatureOverrides overrides;
77 void* const serializedProtoArray =
78 env->GetPrimitiveArrayCritical(serializedProto.obj(), /*isCopy=*/nullptr);
79 CHECK(serializedProtoArray != nullptr);
80 CHECK(overrides.ParseFromArray(serializedProtoArray, serializedProtoSize));
81 env->ReleasePrimitiveArrayCritical(serializedProto.obj(),
82 serializedProtoArray, JNI_ABORT);
83 return overrides;
84 }
85
NativeInit(JNIEnv * env)86 void NativeInit(JNIEnv* env) {
87 // Cronet doesn't currently provide any way of using a custom command line
88 // (see https://crbug.com/1488393). For now, initialize an empty command line
89 // so that code attempting to use the command line doesn't crash.
90 static const char* const argv[] = {"cronet", nullptr};
91 base::CommandLine::Init(sizeof(argv) / sizeof(*argv) - 1, argv);
92
93 logging::InitLogging(logging::LoggingSettings());
94
95 #if !BUILDFLAG(USE_PLATFORM_ICU_ALTERNATIVES)
96 base::i18n::InitializeICU();
97 #endif
98
99 ApplyBaseFeatureOverrides(GetBaseFeatureOverrides(env));
100
101 if (base::FeatureList::IsEnabled(kLogMe)) {
102 LOG(/* Bypass log spam warning regex */ INFO)
103 << "CronetLogMe feature flag set, logging as instructed. Message: "
104 << kLogMeMessage.Get();
105 }
106
107 if (!base::ThreadPoolInstance::Get())
108 base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Cronet");
109 }
110
111 } // namespace
112
OnInitThread()113 bool OnInitThread() {
114 DCHECK(g_init_task_executor);
115 return g_init_task_executor->task_runner()->RunsTasksInCurrentSequence();
116 }
117
118 // Checks the available version of JNI. Also, caches Java reflection artifacts.
CronetOnLoad(JavaVM * vm,void * reserved)119 jint CronetOnLoad(JavaVM* vm, void* reserved) {
120 base::android::InitVM(vm);
121 JNIEnv* env = base::android::AttachCurrentThread();
122 if (!RegisterNatives(env)) {
123 return -1;
124 }
125 if (!base::android::OnJNIOnLoadInit())
126 return -1;
127 NativeInit(env);
128 return JNI_VERSION_1_6;
129 }
130
CronetOnUnLoad(JavaVM * jvm,void * reserved)131 void CronetOnUnLoad(JavaVM* jvm, void* reserved) {
132 if (base::ThreadPoolInstance::Get())
133 base::ThreadPoolInstance::Get()->Shutdown();
134
135 base::android::LibraryLoaderExitHook();
136 }
137
JNI_CronetLibraryLoader_CronetInitOnInitThread(JNIEnv * env)138 void JNI_CronetLibraryLoader_CronetInitOnInitThread(JNIEnv* env) {
139 // Initialize SingleThreadTaskExecutor for init thread.
140 DCHECK(!base::CurrentThread::IsSet());
141 DCHECK(!g_init_task_executor);
142 g_init_task_executor =
143 new base::SingleThreadTaskExecutor(base::MessagePumpType::JAVA);
144
145 DCHECK(!g_network_change_notifier);
146 if (!net::NetworkChangeNotifier::GetFactory()) {
147 net::NetworkChangeNotifier::SetFactory(
148 new net::NetworkChangeNotifierFactoryAndroid());
149 }
150 g_network_change_notifier = net::NetworkChangeNotifier::CreateIfNeeded();
151 DCHECK(g_network_change_notifier);
152
153 g_init_thread_init_done.Signal();
154 }
155
JNI_CronetLibraryLoader_GetCronetVersion(JNIEnv * env)156 ScopedJavaLocalRef<jstring> JNI_CronetLibraryLoader_GetCronetVersion(
157 JNIEnv* env) {
158 #if defined(ARCH_CPU_ARM64)
159 // Attempt to avoid crashes on some ARM64 Marshmallow devices by
160 // prompting zlib ARM feature detection early on. https://crbug.com/853725
161 if (base::android::BuildInfo::GetInstance()->sdk_int() ==
162 base::android::SDK_VERSION_MARSHMALLOW) {
163 crc32(0, Z_NULL, 0);
164 }
165 #endif
166 return base::android::ConvertUTF8ToJavaString(env, CRONET_VERSION);
167 }
168
JNI_CronetLibraryLoader_SetMinLogLevel(JNIEnv * env,jint jlog_level)169 void JNI_CronetLibraryLoader_SetMinLogLevel(JNIEnv* env, jint jlog_level) {
170 logging::SetMinLogLevel(jlog_level);
171 }
172
PostTaskToInitThread(const base::Location & posted_from,base::OnceClosure task)173 void PostTaskToInitThread(const base::Location& posted_from,
174 base::OnceClosure task) {
175 g_init_thread_init_done.Wait();
176 g_init_task_executor->task_runner()->PostTask(posted_from, std::move(task));
177 }
178
EnsureInitialized()179 void EnsureInitialized() {
180 if (g_init_task_executor) {
181 // Ensure that init is done on the init thread.
182 g_init_thread_init_done.Wait();
183 return;
184 }
185
186 // The initialization can only be done once, so static |s_run_once| variable
187 // is used to do it in the constructor.
188 static class RunOnce {
189 public:
190 RunOnce() {
191 JNIEnv* env = base::android::AttachCurrentThread();
192 // Ensure initialized from Java side to properly create Init thread.
193 cronet::Java_CronetLibraryLoader_ensureInitializedFromNative(env);
194 NativeInit(env);
195 }
196 } s_run_once;
197 }
198
CreateProxyConfigService(const scoped_refptr<base::SequencedTaskRunner> & io_task_runner)199 std::unique_ptr<net::ProxyConfigService> CreateProxyConfigService(
200 const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) {
201 // Note: CreateSystemProxyConfigService internally assumes that
202 // base::SingleThreadTaskRunner::GetCurrentDefault() == JNI communication
203 // thread.
204 std::unique_ptr<net::ProxyConfigService> service =
205 net::ProxyConfigService::CreateSystemProxyConfigService(io_task_runner);
206 // If a PAC URL is present, ignore it and use the address and port of
207 // Android system's local HTTP proxy server. See: crbug.com/432539.
208 // TODO(csharrison) Architect the wrapper better so we don't need to cast for
209 // android ProxyConfigServices.
210 net::ProxyConfigServiceAndroid* android_proxy_config_service =
211 static_cast<net::ProxyConfigServiceAndroid*>(service.get());
212 android_proxy_config_service->set_exclude_pac_url(true);
213 return service;
214 }
215
216 // Creates a proxy resolution service appropriate for this platform.
CreateProxyResolutionService(std::unique_ptr<net::ProxyConfigService> proxy_config_service,net::NetLog * net_log)217 std::unique_ptr<net::ProxyResolutionService> CreateProxyResolutionService(
218 std::unique_ptr<net::ProxyConfigService> proxy_config_service,
219 net::NetLog* net_log) {
220 // Android provides a local HTTP proxy server that handles proxying when a PAC
221 // URL is present. Create a proxy service without a resolver and rely on this
222 // local HTTP proxy. See: crbug.com/432539.
223 return net::ConfiguredProxyResolutionService::CreateWithoutProxyResolver(
224 std::move(proxy_config_service), net_log);
225 }
226
227 // Creates default User-Agent request value, combining optional
228 // |partial_user_agent| with system-dependent values.
CreateDefaultUserAgent(const std::string & partial_user_agent)229 std::string CreateDefaultUserAgent(const std::string& partial_user_agent) {
230 // Cronet global state must be initialized to include application info
231 // into default user agent
232 cronet::EnsureInitialized();
233
234 JNIEnv* env = base::android::AttachCurrentThread();
235 std::string user_agent = base::android::ConvertJavaStringToUTF8(
236 cronet::Java_CronetLibraryLoader_getDefaultUserAgent(env));
237 if (!partial_user_agent.empty())
238 user_agent.insert(user_agent.size() - 1, "; " + partial_user_agent);
239 return user_agent;
240 }
241
SetNetworkThreadPriorityOnNetworkThread(double priority)242 void SetNetworkThreadPriorityOnNetworkThread(double priority) {
243 int priority_int = priority;
244 DCHECK_LE(priority_int, 19);
245 DCHECK_GE(priority_int, -20);
246 if (priority_int >= -20 && priority_int <= 19) {
247 JNIEnv* env = base::android::AttachCurrentThread();
248 cronet::Java_CronetLibraryLoader_setNetworkThreadPriorityOnNetworkThread(
249 env, priority_int);
250 }
251 }
252
253 } // namespace cronet
254