1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "AdbDebuggingManager-JNI"
18 
19 #define LOG_NDEBUG 0
20 
21 #include <algorithm>
22 #include <condition_variable>
23 #include <mutex>
24 #include <optional>
25 #include <random>
26 #include <string>
27 #include <vector>
28 
29 #include <adb/pairing/pairing_server.h>
30 #include <android-base/properties.h>
31 #include <utils/Log.h>
32 
33 #include <nativehelper/JNIHelp.h>
34 #include "jni.h"
35 
36 namespace android {
37 
38 // ----------------------------------------------------------------------------
39 namespace {
40 
41 template <class T, class N>
42 class JSmartWrapper {
43 public:
JSmartWrapper(JNIEnv * env,T * jData)44     JSmartWrapper(JNIEnv* env, T* jData) : mEnv(env), mJData(jData) {}
45 
46     virtual ~JSmartWrapper() = default;
47 
data() const48     const N* data() const { return mRawData; }
49 
size() const50     jsize size() const { return mSize; }
51 
52 protected:
53     N* mRawData = nullptr;
54     JNIEnv* mEnv = nullptr;
55     T* mJData = nullptr;
56     jsize mSize = 0;
57 }; // JSmartWrapper
58 
59 class JStringUTFWrapper : public JSmartWrapper<jstring, const char> {
60 public:
JStringUTFWrapper(JNIEnv * env,jstring * str)61     explicit JStringUTFWrapper(JNIEnv* env, jstring* str) : JSmartWrapper(env, str) {
62         mRawData = env->GetStringUTFChars(*str, NULL);
63         mSize = env->GetStringUTFLength(*str);
64     }
65 
~JStringUTFWrapper()66     virtual ~JStringUTFWrapper() {
67         if (data()) {
68             mEnv->ReleaseStringUTFChars(*mJData, mRawData);
69         }
70     }
71 }; // JStringUTFWrapper
72 
73 struct ServerDeleter {
operator ()android::__anon6847251b0110::ServerDeleter74     void operator()(PairingServerCtx* p) { pairing_server_destroy(p); }
75 };
76 using PairingServerPtr = std::unique_ptr<PairingServerCtx, ServerDeleter>;
77 struct PairingResultWaiter {
78     std::mutex mutex_;
79     std::condition_variable cv_;
80     std::optional<bool> is_valid_;
81     PeerInfo peer_info_;
82 
ResultCallbackandroid::__anon6847251b0110::PairingResultWaiter83     static void ResultCallback(const PeerInfo* peer_info, void* opaque) {
84         auto* p = reinterpret_cast<PairingResultWaiter*>(opaque);
85         {
86             std::unique_lock<std::mutex> lock(p->mutex_);
87             if (peer_info) {
88                 memcpy(&(p->peer_info_), peer_info, sizeof(PeerInfo));
89             }
90             p->is_valid_ = (peer_info != nullptr);
91         }
92         p->cv_.notify_one();
93     }
94 };
95 
96 PairingServerPtr sServer;
97 std::unique_ptr<PairingResultWaiter> sWaiter;
98 } // namespace
99 
native_pairing_start(JNIEnv * env,jobject thiz,jstring guid,jstring password)100 static jint native_pairing_start(JNIEnv* env, jobject thiz, jstring guid, jstring password) {
101     // Server-side only sends its GUID on success.
102     PeerInfo system_info = {};
103     system_info.type = ADB_DEVICE_GUID;
104     JStringUTFWrapper guidWrapper(env, &guid);
105     memcpy(system_info.data, guidWrapper.data(), guidWrapper.size());
106 
107     JStringUTFWrapper passwordWrapper(env, &password);
108 
109     // Create the pairing server
110     sServer = PairingServerPtr(
111             pairing_server_new_no_cert(reinterpret_cast<const uint8_t*>(passwordWrapper.data()),
112                                        passwordWrapper.size(), &system_info, 0));
113 
114     sWaiter.reset(new PairingResultWaiter);
115     uint16_t port = pairing_server_start(sServer.get(), sWaiter->ResultCallback, sWaiter.get());
116     if (port == 0) {
117         ALOGE("Failed to start pairing server");
118         return -1;
119     }
120 
121     return port;
122 }
123 
native_pairing_cancel(JNIEnv *,jclass)124 static void native_pairing_cancel(JNIEnv* /* env */, jclass /* clazz */) {
125     if (sServer != nullptr) {
126         sServer.reset();
127     }
128 }
129 
native_pairing_wait(JNIEnv * env,jobject thiz)130 static jboolean native_pairing_wait(JNIEnv* env, jobject thiz) {
131     ALOGI("Waiting for pairing server to complete");
132     std::unique_lock<std::mutex> lock(sWaiter->mutex_);
133     if (!sWaiter->is_valid_.has_value()) {
134         sWaiter->cv_.wait(lock, [&]() { return sWaiter->is_valid_.has_value(); });
135     }
136     if (!*(sWaiter->is_valid_)) {
137         return JNI_FALSE;
138     }
139 
140     std::string peer_public_key = reinterpret_cast<char*>(sWaiter->peer_info_.data);
141     // Write to PairingThread's member variables
142     jclass clazz = env->GetObjectClass(thiz);
143     jfieldID mPublicKey = env->GetFieldID(clazz, "mPublicKey", "Ljava/lang/String;");
144     jstring jpublickey = env->NewStringUTF(peer_public_key.c_str());
145     env->SetObjectField(thiz, mPublicKey, jpublickey);
146     return JNI_TRUE;
147 }
148 
149 // ----------------------------------------------------------------------------
150 
151 static const JNINativeMethod gPairingThreadMethods[] = {
152         /* name, signature, funcPtr */
153         {"native_pairing_start", "(Ljava/lang/String;Ljava/lang/String;)I",
154          (void*)native_pairing_start},
155         {"native_pairing_cancel", "()V", (void*)native_pairing_cancel},
156         {"native_pairing_wait", "()Z", (void*)native_pairing_wait},
157 };
158 
register_android_server_AdbDebuggingManager(JNIEnv * env)159 int register_android_server_AdbDebuggingManager(JNIEnv* env) {
160     int res = jniRegisterNativeMethods(env,
161                                        "com/android/server/adb/AdbDebuggingManager$PairingThread",
162                                        gPairingThreadMethods, NELEM(gPairingThreadMethods));
163     (void)res; // Faked use when LOG_NDEBUG.
164     LOG_FATAL_IF(res < 0, "Unable to register native methods.");
165     return 0;
166 }
167 
168 } /* namespace android */
169