blob: 5cd58d3bba97457a0e7eebb38e22ead2f6fcc542 [file] [log] [blame]
Yu Shan7a5283f2022-10-25 18:01:05 -07001/*
2 * Copyright (C) 2022 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#include "RemoteAccessService.h"
18
19#include <VehicleUtils.h>
20#include <aidl/android/hardware/automotive/vehicle/VehicleProperty.h>
21#include <android-base/stringprintf.h>
22#include <android/binder_status.h>
23#include <grpc++/grpc++.h>
24#include <private/android_filesystem_config.h>
25#include <utils/Log.h>
26#include <chrono>
27#include <thread>
28
29namespace android {
30namespace hardware {
31namespace automotive {
32namespace remoteaccess {
33
34namespace {
35
36using ::aidl::android::hardware::automotive::remoteaccess::ApState;
37using ::aidl::android::hardware::automotive::remoteaccess::IRemoteTaskCallback;
38using ::aidl::android::hardware::automotive::vehicle::VehicleProperty;
39using ::android::base::ScopedLockAssertion;
40using ::android::base::StringAppendF;
41using ::android::base::StringPrintf;
42using ::android::frameworks::automotive::vhal::IVhalClient;
43using ::android::hardware::automotive::vehicle::toInt;
44using ::grpc::ClientContext;
45using ::grpc::ClientReaderInterface;
46using ::grpc::Status;
47using ::grpc::StatusCode;
48using ::ndk::ScopedAStatus;
49
50const std::string WAKEUP_SERVICE_NAME = "com.google.vehicle.wakeup";
51constexpr char COMMAND_SET_AP_STATE[] = "--set-ap-state";
52constexpr char COMMAND_START_DEBUG_CALLBACK[] = "--start-debug-callback";
53constexpr char COMMAND_STOP_DEBUG_CALLBACK[] = "--stop-debug-callback";
54constexpr char COMMAND_SHOW_TASK[] = "--show-task";
55constexpr char COMMAND_GET_DEVICE_ID[] = "--get-device-id";
56
57std::vector<uint8_t> stringToBytes(const std::string& s) {
58 const char* data = s.data();
59 return std::vector<uint8_t>(data, data + s.size());
60}
61
62ScopedAStatus rpcStatusToScopedAStatus(const Status& status, const std::string& errorMsg) {
63 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
64 status.error_code(), (errorMsg + ", error: " + status.error_message()).c_str());
65}
66
67std::string printBytes(const std::vector<uint8_t>& bytes) {
68 std::string s;
69 for (size_t i = 0; i < bytes.size(); i++) {
70 StringAppendF(&s, "%02x", bytes[i]);
71 }
72 return s;
73}
74
75bool checkBoolFlag(const char* flag) {
76 return !strcmp(flag, "1") || !strcmp(flag, "0");
77}
78
79void dprintErrorStatus(int fd, const char* detail, const ScopedAStatus& status) {
80 dprintf(fd, "%s, code: %d, error: %s\n", detail, status.getStatus(), status.getMessage());
81}
82
83} // namespace
84
85RemoteAccessService::RemoteAccessService(WakeupClient::StubInterface* grpcStub)
86 : mGrpcStub(grpcStub){};
87
88RemoteAccessService::~RemoteAccessService() {
89 maybeStopTaskLoop();
90}
91
92void RemoteAccessService::maybeStartTaskLoop() {
93 std::lock_guard<std::mutex> lockGuard(mStartStopTaskLoopLock);
94 if (mTaskLoopRunning) {
95 return;
96 }
97
98 mThread = std::thread([this]() { runTaskLoop(); });
99
100 mTaskLoopRunning = true;
101}
102
103void RemoteAccessService::maybeStopTaskLoop() {
104 std::lock_guard<std::mutex> lockGuard(mStartStopTaskLoopLock);
105 if (!mTaskLoopRunning) {
106 return;
107 }
108
109 {
110 std::lock_guard<std::mutex> lockGuard(mLock);
111 // Try to stop the reading stream.
112 if (mGetRemoteTasksContext) {
113 mGetRemoteTasksContext->TryCancel();
114 mGetRemoteTasksContext.reset();
115 }
116 mTaskWaitStopped = true;
117 mCv.notify_all();
118 }
119 if (mThread.joinable()) {
120 mThread.join();
121 }
122
123 mTaskLoopRunning = false;
124}
125
126void RemoteAccessService::runTaskLoop() {
127 GetRemoteTasksRequest request = {};
128 std::unique_ptr<ClientReaderInterface<GetRemoteTasksResponse>> reader;
129 while (true) {
130 {
131 std::lock_guard<std::mutex> lockGuard(mLock);
132 mGetRemoteTasksContext.reset(new ClientContext());
133 reader = mGrpcStub->GetRemoteTasks(mGetRemoteTasksContext.get(), request);
134 }
135 GetRemoteTasksResponse response;
136 while (reader->Read(&response)) {
137 ALOGI("Receiving one task from remote task client");
138
139 std::shared_ptr<IRemoteTaskCallback> callback;
140 {
141 std::lock_guard<std::mutex> lockGuard(mLock);
142 callback = mRemoteTaskCallback;
143 }
144 if (callback == nullptr) {
145 ALOGD("No callback registered, task ignored");
146 continue;
147 }
148 ALOGD("Calling onRemoteTaskRequested callback for client ID: %s",
149 response.clientid().c_str());
150 ScopedAStatus callbackStatus = callback->onRemoteTaskRequested(
151 response.clientid(), stringToBytes(response.data()));
152 if (!callbackStatus.isOk()) {
153 ALOGE("Failed to call onRemoteTaskRequested callback, status: %d, message: %s",
154 callbackStatus.getStatus(), callbackStatus.getMessage());
155 }
156 }
157 Status status = reader->Finish();
158
159 ALOGE("GetRemoteTasks stream breaks, code: %d, message: %s, sleeping for 10s and retry",
160 status.error_code(), status.error_message().c_str());
161 // The long lasting connection should not return. But if the server returns, retry after
162 // 10s.
163 {
164 std::unique_lock lk(mLock);
165 if (mCv.wait_for(lk, std::chrono::milliseconds(mRetryWaitInMs), [this] {
166 ScopedLockAssertion lockAssertion(mLock);
167 return mTaskWaitStopped;
168 })) {
169 // If the stopped flag is set, we are quitting, exit the loop.
170 break;
171 }
172 }
173 }
174}
175
176ScopedAStatus RemoteAccessService::getDeviceId(std::string* deviceId) {
177#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
178 auto vhalClient = IVhalClient::tryCreate();
179 if (vhalClient == nullptr) {
180 ALOGE("Failed to connect to VHAL");
181 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
182 /*errorCode=*/0, "Failed to connect to VHAL to get device ID");
183 }
184 return getDeviceIdWithClient(*vhalClient.get(), deviceId);
185#else
186 // Don't use VHAL client in fuzzing since IPC is not allowed.
187 return ScopedAStatus::ok();
188#endif
189}
190
191ScopedAStatus RemoteAccessService::getDeviceIdWithClient(IVhalClient& vhalClient,
192 std::string* deviceId) {
193 auto result = vhalClient.getValueSync(
194 *vhalClient.createHalPropValue(toInt(VehicleProperty::INFO_VIN)));
195 if (!result.ok()) {
196 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
197 /*errorCode=*/0,
198 ("failed to get INFO_VIN from VHAL: " + result.error().message()).c_str());
199 }
200 *deviceId = (*result)->getStringValue();
201 return ScopedAStatus::ok();
202}
203
204ScopedAStatus RemoteAccessService::getWakeupServiceName(std::string* wakeupServiceName) {
205 *wakeupServiceName = WAKEUP_SERVICE_NAME;
206 return ScopedAStatus::ok();
207}
208
209ScopedAStatus RemoteAccessService::setRemoteTaskCallback(
210 const std::shared_ptr<IRemoteTaskCallback>& callback) {
211 std::lock_guard<std::mutex> lockGuard(mLock);
212 mRemoteTaskCallback = callback;
213 return ScopedAStatus::ok();
214}
215
216ScopedAStatus RemoteAccessService::clearRemoteTaskCallback() {
217 std::lock_guard<std::mutex> lockGuard(mLock);
218 mRemoteTaskCallback.reset();
219 return ScopedAStatus::ok();
220}
221
222ScopedAStatus RemoteAccessService::notifyApStateChange(const ApState& newState) {
223 ClientContext context;
224 NotifyWakeupRequiredRequest request = {};
225 request.set_iswakeuprequired(newState.isWakeupRequired);
226 NotifyWakeupRequiredResponse response = {};
227 Status status = mGrpcStub->NotifyWakeupRequired(&context, request, &response);
228 if (!status.ok()) {
229 return rpcStatusToScopedAStatus(status, "Failed to notify isWakeupRequired");
230 }
231
232 if (newState.isReadyForRemoteTask) {
233 maybeStartTaskLoop();
234 } else {
235 maybeStopTaskLoop();
236 }
237 return ScopedAStatus::ok();
238}
239
240bool RemoteAccessService::checkDumpPermission() {
241 uid_t uid = AIBinder_getCallingUid();
242 return uid == AID_ROOT || uid == AID_SHELL || uid == AID_SYSTEM;
243}
244
245void RemoteAccessService::dumpHelp(int fd) {
246 dprintf(fd, "%s",
247 (std::string("RemoteAccess HAL debug interface, Usage: \n") + COMMAND_SET_AP_STATE +
248 " [0/1](isReadyForRemoteTask) [0/1](isWakeupRequired) Set the new AP state\n" +
249 COMMAND_START_DEBUG_CALLBACK +
250 " Start a debug callback that will record the received tasks\n" +
251 COMMAND_STOP_DEBUG_CALLBACK + " Stop the debug callback\n" + COMMAND_SHOW_TASK +
252 " Show tasks received by debug callback\n" + COMMAND_GET_DEVICE_ID +
253 " Get device id\n")
254 .c_str());
255}
256
257binder_status_t RemoteAccessService::dump(int fd, const char** args, uint32_t numArgs) {
258 if (!checkDumpPermission()) {
259 dprintf(fd, "Caller must be root, system or shell\n");
260 return STATUS_PERMISSION_DENIED;
261 }
262
263 if (numArgs == 0) {
264 dumpHelp(fd);
265 return STATUS_OK;
266 }
267
268 if (!strcmp(args[0], COMMAND_SET_AP_STATE)) {
269 if (numArgs < 3) {
270 dumpHelp(fd);
271 return STATUS_OK;
272 }
273 ApState apState = {};
274 const char* remoteTaskFlag = args[1];
275 if (!strcmp(remoteTaskFlag, "1") && !strcmp(remoteTaskFlag, "0")) {
276 dumpHelp(fd);
277 return STATUS_OK;
278 }
279 if (!checkBoolFlag(args[1])) {
280 dumpHelp(fd);
281 return STATUS_OK;
282 }
283 if (!strcmp(args[1], "1")) {
284 apState.isReadyForRemoteTask = true;
285 }
286 if (!checkBoolFlag(args[2])) {
287 dumpHelp(fd);
288 return STATUS_OK;
289 }
290 if (!strcmp(args[2], "1")) {
291 apState.isWakeupRequired = true;
292 }
293 auto status = notifyApStateChange(apState);
294 if (!status.isOk()) {
295 dprintErrorStatus(fd, "Failed to set AP state", status);
296 } else {
297 dprintf(fd, "successfully set the new AP state\n");
298 }
299 } else if (!strcmp(args[0], COMMAND_START_DEBUG_CALLBACK)) {
300 mDebugCallback = ndk::SharedRefBase::make<DebugRemoteTaskCallback>();
301 setRemoteTaskCallback(mDebugCallback);
302 dprintf(fd, "Debug callback registered\n");
303 } else if (!strcmp(args[0], COMMAND_STOP_DEBUG_CALLBACK)) {
304 if (mDebugCallback) {
305 mDebugCallback.reset();
306 }
307 clearRemoteTaskCallback();
308 dprintf(fd, "Debug callback unregistered\n");
309 } else if (!strcmp(args[0], COMMAND_SHOW_TASK)) {
310 if (mDebugCallback) {
311 dprintf(fd, "%s", mDebugCallback->printTasks().c_str());
312 } else {
313 dprintf(fd, "Debug callback is not currently used, use \"%s\" first.\n",
314 COMMAND_START_DEBUG_CALLBACK);
315 }
316 } else if (!strcmp(args[0], COMMAND_GET_DEVICE_ID)) {
317 std::string deviceId;
318 auto status = getDeviceId(&deviceId);
319 if (!status.isOk()) {
320 dprintErrorStatus(fd, "Failed to get device ID", status);
321 } else {
322 dprintf(fd, "Device Id: %s\n", deviceId.c_str());
323 }
324 } else {
325 dumpHelp(fd);
326 }
327
328 return STATUS_OK;
329}
330
331ScopedAStatus DebugRemoteTaskCallback::onRemoteTaskRequested(const std::string& clientId,
332 const std::vector<uint8_t>& data) {
333 std::lock_guard<std::mutex> lockGuard(mLock);
334 mTasks.push_back({
335 .clientId = clientId,
336 .data = data,
337 });
338 return ScopedAStatus::ok();
339}
340
341std::string DebugRemoteTaskCallback::printTasks() {
342 std::lock_guard<std::mutex> lockGuard(mLock);
343 std::string s = StringPrintf("Received %zu tasks in %f seconds", mTasks.size(),
344 (android::uptimeMillis() - mStartTimeMillis) / 1000.);
345 for (size_t i = 0; i < mTasks.size(); i++) {
346 StringAppendF(&s, "Client Id: %s, Data: %s\n", mTasks[i].clientId.c_str(),
347 printBytes(mTasks[i].data).c_str());
348 }
349 return s;
350}
351
352} // namespace remoteaccess
353} // namespace automotive
354} // namespace hardware
355} // namespace android