1 /*
2  * Copyright 2020 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 "AdbPairingConnectionTest"
18 
19 #include <chrono>
20 #include <condition_variable>
21 #include <mutex>
22 #include <thread>
23 
24 #include <adb/pairing/pairing_server.h>
25 #include <android-base/logging.h>
26 #include <android-base/strings.h>
27 #include <gtest/gtest.h>
28 
29 #include "../internal/constants.h"
30 #include "pairing_client.h"
31 
32 using namespace std::chrono_literals;
33 
34 namespace adb {
35 namespace pairing {
36 
37 // Test X.509 certificates (RSA 2048)
38 static const std::string kTestRsa2048ServerCert =
39         "-----BEGIN CERTIFICATE-----\n"
40         "MIIDFzCCAf+gAwIBAgIBATANBgkqhkiG9w0BAQsFADAtMQswCQYDVQQGEwJVUzEQ\n"
41         "MA4GA1UECgwHQW5kcm9pZDEMMAoGA1UEAwwDQWRiMB4XDTIwMDEyMTIyMjU1NVoX\n"
42         "DTMwMDExODIyMjU1NVowLTELMAkGA1UEBhMCVVMxEDAOBgNVBAoMB0FuZHJvaWQx\n"
43         "DDAKBgNVBAMMA0FkYjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK8E\n"
44         "2Ck9TfuKlz7wqWdMfknjZ1luFDp2IHxAUZzh/F6jeI2dOFGAjpeloSnGOE86FIaT\n"
45         "d1EvpyTh7nBwbrLZAA6XFZTo7Bl6BdNOQdqb2d2+cLEN0inFxqUIycevRtohUE1Y\n"
46         "FHM9fg442X1jOTWXjDZWeiqFWo95paAPhzm6pWqfJK1+YKfT1LsWZpYqJGGQE5pi\n"
47         "C3qOBYYgFpoXMxTYJNoZo3uOYEdM6upc8/vh15nMgIxX/ymJxEY5BHPpZPPWjXLg\n"
48         "BfzVaV9fUfv0JT4HQ4t2WvxC3cD/UsjWp2a6p454uUp2ENrANa+jRdRJepepg9D2\n"
49         "DKsx9L8zjc5Obqexrt0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B\n"
50         "Af8EBAMCAYYwHQYDVR0OBBYEFDFW+8GTErwoZN5Uu9KyY4QdGYKpMA0GCSqGSIb3\n"
51         "DQEBCwUAA4IBAQBCDEn6SHXGlq5TU7J8cg1kRPd9bsJW+0hDuKSq0REXDkl0PcBf\n"
52         "fy282Agg9enKPPKmnpeQjM1dmnxdM8tT8LIUbMl779i3fn6v9HJVB+yG4gmRFThW\n"
53         "c+AGlBnrIT820cX/gU3h3R3FTahfsq+1rrSJkEgHyuC0HYeRyveSckBdaEOLvx0S\n"
54         "toun+32JJl5hWydpUUZhE9Mbb3KHBRM2YYZZU9JeJ08Apjl+3lRUeMAUwI5fkAAu\n"
55         "z/1SqnuGL96bd8P5ixdkA1+rF8FPhodGcq9mQOuUGP9g5HOXjaNoJYvwVRUdLeGh\n"
56         "cP/ReOTwQIzM1K5a83p8cX8AGGYmM7dQp7ec\n"
57         "-----END CERTIFICATE-----\n";
58 
59 static const std::string kTestRsa2048ServerPrivKey =
60         "-----BEGIN PRIVATE KEY-----\n"
61         "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCvBNgpPU37ipc+\n"
62         "8KlnTH5J42dZbhQ6diB8QFGc4fxeo3iNnThRgI6XpaEpxjhPOhSGk3dRL6ck4e5w\n"
63         "cG6y2QAOlxWU6OwZegXTTkHam9ndvnCxDdIpxcalCMnHr0baIVBNWBRzPX4OONl9\n"
64         "Yzk1l4w2VnoqhVqPeaWgD4c5uqVqnyStfmCn09S7FmaWKiRhkBOaYgt6jgWGIBaa\n"
65         "FzMU2CTaGaN7jmBHTOrqXPP74deZzICMV/8picRGOQRz6WTz1o1y4AX81WlfX1H7\n"
66         "9CU+B0OLdlr8Qt3A/1LI1qdmuqeOeLlKdhDawDWvo0XUSXqXqYPQ9gyrMfS/M43O\n"
67         "Tm6nsa7dAgMBAAECggEAFCS2bPdUKIgjbzLgtHW+hT+J2hD20rcHdyAp+dNH/2vI\n"
68         "yLfDJHJA4chGMRondKA704oDw2bSJxxlG9t83326lB35yxPhye7cM8fqgWrK8PVl\n"
69         "tU22FhO1ZgeJvb9OeXWNxKZyDW9oOOJ8eazNXVMuEo+dFj7B6l3MXQyHJPL2mJDm\n"
70         "u9ofFLdypX+gJncVO0oW0FNJnEUn2MMwHDNlo7gc4WdQuidPkuZItKRGcB8TTGF3\n"
71         "Ka1/2taYdTQ4Aq//Z84LlFvE0zD3T4c8LwYYzOzD4gGGTXvft7vSHzIun1S8YLRS\n"
72         "dEKXdVjtaFhgH3uUe4j+1b/vMvSHeoGBNX/G88GD+wKBgQDWUYVlMVqc9HD2IeYi\n"
73         "EfBcNwAJFJkh51yAl5QbUBgFYgFJVkkS/EDxEGFPvEmI3/pAeQFHFY13BI466EPs\n"
74         "o8Z8UUwWDp+Z1MFHHKQKnFakbsZbZlbqjJ9VJsqpezbpWhMHTOmcG0dmE7rf0lyM\n"
75         "eQv9slBB8qp2NEUs5Of7f2C2bwKBgQDRDq4nUuMQF1hbjM05tGKSIwkobmGsLspv\n"
76         "TMhkM7fq4RpbFHmbNgsFqMhcqYZ8gY6/scv5KCuAZ4yHUkbqwf5h+QCwrJ4uJeUJ\n"
77         "ZgJfHus2mmcNSo8FwSkNoojIQtzcbJav7bs2K9VTuertk/i7IJLApU4FOZZ5pghN\n"
78         "EXu0CZF1cwKBgDWFGhjRIF29tU/h20R60llU6s9Zs3wB+NmsALJpZ/ZAKS4VPB5f\n"
79         "nCAXBRYSYRKrTCU5kpYbzb4BBzuysPOxWmnFK4j+keCqfrGxd02nCQP7HdHJVr8v\n"
80         "6sIq88UrHeVcNxBFprjzHvtgxfQK5k22FMZ/9wbhAKyQFQ5HA5+MiaxFAoGAIcZZ\n"
81         "ZIkDninnYIMS9OursShv5lRO+15j3i9tgKLKZ+wOMgDQ1L6acUOfezj4PU1BHr8+\n"
82         "0PYocQpJreMhCfRlgLaV4fVBaPs+UZJld7CrF5tCYudUy/01ALrtlk0XGZWBktK5\n"
83         "mDrksC4tQkzRtonAq9cJD9cJ9IVaefkFH0UcdvkCgYBpZj50VLeGhnHHBnkJRlV1\n"
84         "fV+/P6PAq6RtqjA6O9Qdaoj5V3w2d63aQcQXQLJjH2BBmtCIy47r04rFvZpbCxP7\n"
85         "NH/OnK9NHpk2ucRTe8TAnVbvF/TZzPJoIxAO/D3OWaW6df4R8en8u6GYzWFglAyT\n"
86         "sydGT8yfWD1FYUWgfrVRbg==\n"
87         "-----END PRIVATE KEY-----\n";
88 
89 static const std::string kTestRsa2048ClientCert =
90         "-----BEGIN CERTIFICATE-----\n"
91         "MIIDFzCCAf+gAwIBAgIBATANBgkqhkiG9w0BAQsFADAtMQswCQYDVQQGEwJVUzEQ\n"
92         "MA4GA1UECgwHQW5kcm9pZDEMMAoGA1UEAwwDQWRiMB4XDTIwMDEyMTIyMjU1NloX\n"
93         "DTMwMDExODIyMjU1NlowLTELMAkGA1UEBhMCVVMxEDAOBgNVBAoMB0FuZHJvaWQx\n"
94         "DDAKBgNVBAMMA0FkYjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAI3a\n"
95         "EXh1S5FTbet7JVONswffRPaekdIK53cb8SnAbSO9X5OLA4zGwdkrBvDTsd96SKrp\n"
96         "JxmoNOE1DhbZh05KPlWAPkGKacjGWaz+S7biDOL0I6aaLbTlU/il1Ub9olPSBVUx\n"
97         "0nhdtEFgIOzddnP6/1KmyIIeRxS5lTKeg4avqUkZNXkz/wL1dHBFL7FNFf0SCcbo\n"
98         "tsub/deFbjZ27LTDN+SIBgFttTNqC5NTvoBAoMdyCOAgNYwaHO+fKiK3edfJieaw\n"
99         "7HD8qqmQxcpCtRlA8CUPj7GfR+WHiCJmlevhnkFXCo56R1BS0F4wuD4KPdSWt8gc\n"
100         "27ejH/9/z2cKo/6SLJMCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B\n"
101         "Af8EBAMCAYYwHQYDVR0OBBYEFO/Mr5ygqqpyU/EHM9v7RDvcqaOkMA0GCSqGSIb3\n"
102         "DQEBCwUAA4IBAQAH33KMouzF2DYbjg90KDrDQr4rq3WfNb6P743knxdUFuvb+40U\n"
103         "QjC2OJZHkSexH7wfG/y6ic7vfCfF4clNs3QvU1lEjOZC57St8Fk7mdNdsWLwxEMD\n"
104         "uePFz0dvclSxNUHyCVMqNxddzQYzxiDWQRmXWrUBliMduQqEQelcxW2yDtg8bj+s\n"
105         "aMpR1ra9scaD4jzIZIIxLoOS9zBMuNRbgP217sZrniyGMhzoI1pZ/izN4oXpyH7O\n"
106         "THuaCzzRT3ph2f8EgmHSodz3ttgSf2DHzi/Ez1xUkk7NOlgNtmsxEdrM47+cC5ae\n"
107         "fIf2V+1o1JW8J7D11RmRbNPh3vfisueB4f88\n"
108         "-----END CERTIFICATE-----\n";
109 
110 static const std::string kTestRsa2048ClientPrivKey =
111         "-----BEGIN PRIVATE KEY-----\n"
112         "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCN2hF4dUuRU23r\n"
113         "eyVTjbMH30T2npHSCud3G/EpwG0jvV+TiwOMxsHZKwbw07Hfekiq6ScZqDThNQ4W\n"
114         "2YdOSj5VgD5BimnIxlms/ku24gzi9COmmi205VP4pdVG/aJT0gVVMdJ4XbRBYCDs\n"
115         "3XZz+v9SpsiCHkcUuZUynoOGr6lJGTV5M/8C9XRwRS+xTRX9EgnG6LbLm/3XhW42\n"
116         "duy0wzfkiAYBbbUzaguTU76AQKDHcgjgIDWMGhzvnyoit3nXyYnmsOxw/KqpkMXK\n"
117         "QrUZQPAlD4+xn0flh4giZpXr4Z5BVwqOekdQUtBeMLg+Cj3UlrfIHNu3ox//f89n\n"
118         "CqP+kiyTAgMBAAECggEAAa64eP6ggCob1P3c73oayYPIbvRqiQdAFOrr7Vwu7zbr\n"
119         "z0rde+n6RU0mrpc+4NuzyPMtrOGQiatLbidJB5Cx3z8U00ovqbCl7PtcgorOhFKe\n"
120         "VEzihebCcYyQqbWQcKtpDMhOgBxRwFoXieJb6VGXfa96FAZalCWvXgOrTl7/BF2X\n"
121         "qMqIm9nJi+yS5tIO8VdOsOmrMWRH/b/ENUcef4WpLoxTXr0EEgyKWraeZ/hhXo1e\n"
122         "z29dZKqdr9wMsq11NPsRddwS94jnDkXTo+EQyWVTfB7gb6yyp07s8jysaDb21tVv\n"
123         "UXB9MRhDV1mOv0ncXfXZ4/+4A2UahmZaLDAVLaat4QKBgQDAVRredhGRGl2Nkic3\n"
124         "KvZCAfyxug788CgasBdEiouz19iCCwcgMIDwnq0s3/WM7h/laCamT2x38riYDnpq\n"
125         "rkYMfuVtU9CjEL9pTrdfwbIRhTwYNqADaPz2mXwQUhRXutE5TIdgxxC/a+ZTh0qN\n"
126         "S+vhTj/4hf0IZhMh5Nqj7IPExQKBgQC8zxEzhmSGjys0GuE6Wl6Doo2TpiR6vwvi\n"
127         "xPLU9lmIz5eca/Rd/eERioFQqeoIWDLzx52DXuz6rUoQhbJWz9hP3yqCwXD+pbNP\n"
128         "oDJqDDbCC4IMYEb0IK/PEPH+gIpnTjoFcW+ecKDFG7W5Lt05J8WsJsfOaJvMrOU+\n"
129         "dLXq3IgxdwKBgQC5RAFq0v6e8G+3hFaEHL0z3igkpt3zJf7rnj37hx2FMmDa+3Z0\n"
130         "umQp5B9af61PgL12xLmeMBmC/Wp1BlVDV/Yf6Uhk5Hyv5t0KuomHEtTNbbLyfAPs\n"
131         "5P/vJu/L5NS1oT4S3LX3MineyjgGs+bLbpub3z1dzutrYLADUSiPCK/xJQKBgBQt\n"
132         "nQ0Ao+Wtj1R2OvPdjJRM3wyUiPmFSWPm4HzaBx+T8AQLlYYmB9O0FbXlMtnJc0iS\n"
133         "YMcVcgYoVu4FG9YjSF7g3s4yljzgwJUV7c1fmMqMKE3iTDLy+1cJ3JLycdgwiArk\n"
134         "4KTyLHxkRbuQwpvFIF8RlfD9RQlOwQE3v+llwDhpAoGBAL6XG6Rp6mBoD2Ds5c9R\n"
135         "943yYgSUes3ji1SI9zFqeJtj8Ml/enuK1xu+8E/BxB0//+vgZsH6i3i8GFwygKey\n"
136         "CGJF8CbiHc3EJc3NQIIRXcni/CGacf0HwC6m+PGFDBIpA4H2iDpVvCSofxttQiq0\n"
137         "/Z7HXmXUvZHVyYi/QzX2Gahj\n"
138         "-----END PRIVATE KEY-----\n";
139 
140 struct ServerDeleter {
141     void operator()(PairingServerCtx* p) { pairing_server_destroy(p); }
142 };
143 using ServerPtr = std::unique_ptr<PairingServerCtx, ServerDeleter>;
144 
145 struct ResultWaiter {
146     std::mutex mutex_;
147     std::condition_variable cv_;
148     std::optional<bool> is_valid_;
149     PeerInfo peer_info_;
150 
151     static void ResultCallback(const PeerInfo* peer_info, void* opaque) {
152         auto* p = reinterpret_cast<ResultWaiter*>(opaque);
153         {
154             std::unique_lock<std::mutex> lock(p->mutex_);
155             if (peer_info) {
156                 memcpy(&(p->peer_info_), peer_info, sizeof(PeerInfo));
157             }
158             p->is_valid_ = (peer_info != nullptr);
159         }
160         p->cv_.notify_one();
161     }
162 };
163 
164 class AdbPairingConnectionTest : public testing::Test {
165   protected:
166     virtual void SetUp() override {}
167 
168     virtual void TearDown() override {}
169 
170     void InitPairing(const std::vector<uint8_t>& server_pswd,
171                      const std::vector<uint8_t>& client_pswd) {
172         server_ = CreateServer(server_pswd);
173         client_ = CreateClient(client_pswd);
174     }
175 
176     ServerPtr CreateServer(const std::vector<uint8_t>& pswd) {
177         return CreateServer(pswd, &server_info_, kTestRsa2048ServerCert, kTestRsa2048ServerPrivKey,
178                             0);
179     }
180 
181     std::unique_ptr<PairingClient> CreateClient(const std::vector<uint8_t> pswd) {
182         std::vector<uint8_t> cert;
183         std::vector<uint8_t> key;
184         // Include the null-byte as well.
185         cert.assign(reinterpret_cast<const uint8_t*>(kTestRsa2048ClientCert.data()),
186                     reinterpret_cast<const uint8_t*>(kTestRsa2048ClientCert.data()) +
187                             kTestRsa2048ClientCert.size() + 1);
188         key.assign(reinterpret_cast<const uint8_t*>(kTestRsa2048ClientPrivKey.data()),
189                    reinterpret_cast<const uint8_t*>(kTestRsa2048ClientPrivKey.data()) +
190                            kTestRsa2048ClientPrivKey.size() + 1);
191         return PairingClient::Create(pswd, client_info_, cert, key);
192     }
193 
194     static ServerPtr CreateServer(const std::vector<uint8_t>& pswd, const PeerInfo* peer_info,
195                                   const std::string_view cert, const std::string_view priv_key,
196                                   int port) {
197         return ServerPtr(pairing_server_new(
198                 pswd.data(), pswd.size(), peer_info, reinterpret_cast<const uint8_t*>(cert.data()),
199                 cert.size(), reinterpret_cast<const uint8_t*>(priv_key.data()), priv_key.size(),
200                 port));
201     }
202 
203     ServerPtr server_;
204     const PeerInfo server_info_ = {
205             .type = ADB_DEVICE_GUID,
206             .data = "my_server_info",
207     };
208     std::unique_ptr<PairingClient> client_;
209     const PeerInfo client_info_ = {
210             .type = ADB_RSA_PUB_KEY,
211             .data = "my_client_info",
212     };
213     std::string ip_addr_ = "127.0.0.1:";
214 };
215 
216 TEST_F(AdbPairingConnectionTest, ServerCreation) {
217     // All parameters bad
218     ASSERT_DEATH({ auto server = CreateServer({}, nullptr, "", "", 0); }, "");
219     // Bad password
220     ASSERT_DEATH(
221             {
222                 auto server = CreateServer({}, &server_info_, kTestRsa2048ServerCert,
223                                            kTestRsa2048ServerPrivKey, 0);
224             },
225             "");
226     // Bad peer_info
227     ASSERT_DEATH(
228             {
229                 auto server = CreateServer({0x01}, nullptr, kTestRsa2048ServerCert,
230                                            kTestRsa2048ServerPrivKey, 0);
231             },
232             "");
233     // Bad certificate
234     ASSERT_DEATH(
235             {
236                 auto server = CreateServer({0x01}, &server_info_, "", kTestRsa2048ServerPrivKey, 0);
237             },
238             "");
239     // Bad private key
240     ASSERT_DEATH(
241             { auto server = CreateServer({0x01}, &server_info_, kTestRsa2048ServerCert, "", 0); },
242             "");
243     // Valid params
244     auto server = CreateServer({0x01}, &server_info_, kTestRsa2048ServerCert,
245                                kTestRsa2048ServerPrivKey, 0);
246     EXPECT_NE(nullptr, server);
247 }
248 
249 TEST_F(AdbPairingConnectionTest, ClientCreation) {
250     std::vector<uint8_t> pswd{0x01, 0x03, 0x05, 0x07};
251     // Bad password
252     ASSERT_DEATH(
253             {
254                 pairing_connection_client_new(
255                         nullptr, pswd.size(), &client_info_,
256                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientCert.data()),
257                         kTestRsa2048ClientCert.size(),
258                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientPrivKey.data()),
259                         kTestRsa2048ClientPrivKey.size());
260             },
261             "");
262     ASSERT_DEATH(
263             {
264                 pairing_connection_client_new(
265                         pswd.data(), 0, &client_info_,
266                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientCert.data()),
267                         kTestRsa2048ClientCert.size(),
268                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientPrivKey.data()),
269                         kTestRsa2048ClientPrivKey.size());
270             },
271             "");
272 
273     // Bad peer_info
274     ASSERT_DEATH(
275             {
276                 pairing_connection_client_new(
277                         pswd.data(), pswd.size(), nullptr,
278                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientCert.data()),
279                         kTestRsa2048ClientCert.size(),
280                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientPrivKey.data()),
281                         kTestRsa2048ClientPrivKey.size());
282             },
283             "");
284 
285     // Bad certificate
286     ASSERT_DEATH(
287             {
288                 pairing_connection_client_new(
289                         pswd.data(), pswd.size(), &client_info_, nullptr,
290                         kTestRsa2048ClientCert.size(),
291                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientPrivKey.data()),
292                         kTestRsa2048ClientPrivKey.size());
293             },
294             "");
295     ASSERT_DEATH(
296             {
297                 pairing_connection_client_new(
298                         pswd.data(), pswd.size(), &client_info_,
299                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientCert.data()), 0,
300                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientPrivKey.data()),
301                         kTestRsa2048ClientPrivKey.size());
302             },
303             "");
304 
305     // Bad private key
306     ASSERT_DEATH(
307             {
308                 pairing_connection_client_new(
309                         pswd.data(), pswd.size(), &client_info_,
310                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientCert.data()),
311                         kTestRsa2048ClientCert.size(), nullptr, kTestRsa2048ClientPrivKey.size());
312             },
313             "");
314     ASSERT_DEATH(
315             {
316                 pairing_connection_client_new(
317                         pswd.data(), pswd.size(), &client_info_,
318                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientCert.data()),
319                         kTestRsa2048ClientCert.size(),
320                         reinterpret_cast<const uint8_t*>(kTestRsa2048ClientPrivKey.data()), 0);
321             },
322             "");
323 
324     // Valid params
325     auto client = pairing_connection_client_new(
326             pswd.data(), pswd.size(), &client_info_,
327             reinterpret_cast<const uint8_t*>(kTestRsa2048ClientCert.data()),
328             kTestRsa2048ClientCert.size(),
329             reinterpret_cast<const uint8_t*>(kTestRsa2048ClientPrivKey.data()),
330             kTestRsa2048ClientPrivKey.size());
331     EXPECT_NE(nullptr, client);
332 }
333 
334 TEST_F(AdbPairingConnectionTest, SmokeValidPairing) {
335     std::vector<uint8_t> pswd{0x01, 0x03, 0x05, 0x07};
336     InitPairing(pswd, pswd);
337 
338     // Start the server
339     ResultWaiter server_waiter;
340     std::unique_lock<std::mutex> server_lock(server_waiter.mutex_);
341     auto port = pairing_server_start(server_.get(), server_waiter.ResultCallback, &server_waiter);
342     ASSERT_GT(port, 0);
343     ip_addr_ += std::to_string(port);
344 
345     // Start the client
346     ResultWaiter client_waiter;
347     std::unique_lock<std::mutex> client_lock(client_waiter.mutex_);
348     ASSERT_TRUE(client_->Start(ip_addr_, client_waiter.ResultCallback, &client_waiter));
349     client_waiter.cv_.wait(client_lock, [&]() { return client_waiter.is_valid_.has_value(); });
350     ASSERT_TRUE(*(client_waiter.is_valid_));
351     ASSERT_EQ(strlen(reinterpret_cast<const char*>(client_waiter.peer_info_.data)),
352               strlen(reinterpret_cast<const char*>(server_info_.data)));
353     EXPECT_EQ(memcmp(client_waiter.peer_info_.data, server_info_.data, sizeof(server_info_.data)),
354               0);
355 
356     // Kill server if the pairing failed, since server only shuts down when
357     // it gets a valid pairing.
358     if (!client_waiter.is_valid_) {
359         server_lock.unlock();
360         server_.reset();
361     } else {
362         server_waiter.cv_.wait(server_lock, [&]() { return server_waiter.is_valid_.has_value(); });
363         ASSERT_TRUE(*(server_waiter.is_valid_));
364         ASSERT_EQ(strlen(reinterpret_cast<const char*>(server_waiter.peer_info_.data)),
365                   strlen(reinterpret_cast<const char*>(client_info_.data)));
366         EXPECT_EQ(
367                 memcmp(server_waiter.peer_info_.data, client_info_.data, sizeof(client_info_.data)),
368                 0);
369     }
370 }
371 
372 TEST_F(AdbPairingConnectionTest, CancelPairing) {
373     std::vector<uint8_t> pswd{0x01, 0x03, 0x05, 0x07};
374     std::vector<uint8_t> pswd2{0x01, 0x03, 0x05, 0x06};
375     InitPairing(pswd, pswd2);
376 
377     // Start the server
378     ResultWaiter server_waiter;
379     std::unique_lock<std::mutex> server_lock(server_waiter.mutex_);
380     auto port = pairing_server_start(server_.get(), server_waiter.ResultCallback, &server_waiter);
381     ASSERT_GT(port, 0);
382     ip_addr_ += std::to_string(port);
383 
384     // Start the client. Client should fail to pair
385     ResultWaiter client_waiter;
386     std::unique_lock<std::mutex> client_lock(client_waiter.mutex_);
387     ASSERT_TRUE(client_->Start(ip_addr_, client_waiter.ResultCallback, &client_waiter));
388     client_waiter.cv_.wait(client_lock, [&]() { return client_waiter.is_valid_.has_value(); });
389     ASSERT_FALSE(*(client_waiter.is_valid_));
390 
391     // Kill the server. We should still receive the callback with no valid
392     // pairing.
393     server_lock.unlock();
394     server_.reset();
395     server_lock.lock();
396     ASSERT_TRUE(server_waiter.is_valid_.has_value());
397     EXPECT_FALSE(*(server_waiter.is_valid_));
398 }
399 
400 TEST_F(AdbPairingConnectionTest, MultipleClientsAllFail) {
401     std::vector<uint8_t> pswd{0x01, 0x03, 0x05, 0x07};
402     std::vector<uint8_t> pswd2{0x01, 0x03, 0x05, 0x06};
403 
404     // Start the server
405     auto server = CreateServer(pswd);
406     ResultWaiter server_waiter;
407     std::unique_lock<std::mutex> server_lock(server_waiter.mutex_);
408     auto port = pairing_server_start(server.get(), server_waiter.ResultCallback, &server_waiter);
409     ASSERT_GT(port, 0);
410     ip_addr_ += std::to_string(port);
411 
412     // Start multiple clients, all with bad passwords
413     int test_num_clients = 5;
414     int num_clients_done = 0;
415     std::mutex global_clients_mutex;
416     std::unique_lock<std::mutex> global_clients_lock(global_clients_mutex);
417     std::condition_variable global_cv_;
418     for (int i = 0; i < test_num_clients; ++i) {
419         std::thread([&]() {
420             auto client = CreateClient(pswd2);
421             ResultWaiter client_waiter;
422             std::unique_lock<std::mutex> client_lock(client_waiter.mutex_);
423             ASSERT_TRUE(client->Start(ip_addr_, client_waiter.ResultCallback, &client_waiter));
424             client_waiter.cv_.wait(client_lock,
425                                    [&]() { return client_waiter.is_valid_.has_value(); });
426             ASSERT_FALSE(*(client_waiter.is_valid_));
427             {
428                 std::lock_guard<std::mutex> global_lock(global_clients_mutex);
429                 ++num_clients_done;
430             }
431             global_cv_.notify_one();
432         }).detach();
433     }
434 
435     global_cv_.wait(global_clients_lock, [&]() { return num_clients_done == test_num_clients; });
436     server_lock.unlock();
437     server.reset();
438     server_lock.lock();
439     ASSERT_TRUE(server_waiter.is_valid_.has_value());
440     EXPECT_FALSE(*(server_waiter.is_valid_));
441 }
442 
443 TEST_F(AdbPairingConnectionTest, DISABLED_MultipleClientsOnePass) {
444     // Send multiple clients with bad passwords, but send the last one with the
445     // correct password.
446     std::vector<uint8_t> pswd{0x01, 0x03, 0x05, 0x07};
447     std::vector<uint8_t> pswd2{0x01, 0x03, 0x05, 0x06};
448 
449     // Start the server
450     auto server = CreateServer(pswd);
451     ResultWaiter server_waiter;
452     std::unique_lock<std::mutex> server_lock(server_waiter.mutex_);
453     auto port = pairing_server_start(server.get(), server_waiter.ResultCallback, &server_waiter);
454     ASSERT_GT(port, 0);
455     ip_addr_ += std::to_string(port);
456 
457     // Start multiple clients, all with bad passwords
458     int test_num_clients = 5;
459     int num_clients_done = 0;
460     std::mutex global_clients_mutex;
461     std::unique_lock<std::mutex> global_clients_lock(global_clients_mutex);
462     std::condition_variable global_cv_;
463     for (int i = 0; i < test_num_clients; ++i) {
464         std::thread([&, i]() {
465             bool good_client = (i == (test_num_clients - 1));
466             auto client = CreateClient((good_client ? pswd : pswd2));
467             ResultWaiter client_waiter;
468             std::unique_lock<std::mutex> client_lock(client_waiter.mutex_);
469             ASSERT_TRUE(client->Start(ip_addr_, client_waiter.ResultCallback, &client_waiter));
470             client_waiter.cv_.wait(client_lock,
471                                    [&]() { return client_waiter.is_valid_.has_value(); });
472             if (good_client) {
473                 ASSERT_TRUE(*(client_waiter.is_valid_));
474                 ASSERT_EQ(strlen(reinterpret_cast<const char*>(client_waiter.peer_info_.data)),
475                           strlen(reinterpret_cast<const char*>(server_info_.data)));
476                 EXPECT_EQ(memcmp(client_waiter.peer_info_.data, server_info_.data,
477                                  sizeof(server_info_.data)),
478                           0);
479             } else {
480                 ASSERT_FALSE(*(client_waiter.is_valid_));
481             }
482             {
483                 std::lock_guard<std::mutex> global_lock(global_clients_mutex);
484                 ++num_clients_done;
485             }
486             global_cv_.notify_one();
487         }).detach();
488     }
489 
490     global_cv_.wait(global_clients_lock, [&]() { return num_clients_done == test_num_clients; });
491     server_waiter.cv_.wait(server_lock, [&]() { return server_waiter.is_valid_.has_value(); });
492     ASSERT_TRUE(*(server_waiter.is_valid_));
493     ASSERT_EQ(strlen(reinterpret_cast<const char*>(server_waiter.peer_info_.data)),
494               strlen(reinterpret_cast<const char*>(client_info_.data)));
495     EXPECT_EQ(memcmp(server_waiter.peer_info_.data, client_info_.data, sizeof(client_info_.data)),
496               0);
497 }
498 
499 }  // namespace pairing
500 }  // namespace adb
501