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 TRACE_TAG SERVICES
18 
19 #include "sysdeps.h"
20 
21 #include <unistd.h>
22 
23 #include <android-base/logging.h>
24 #include <android-base/properties.h>
25 #include <android-base/stringprintf.h>
26 #include <log/log_properties.h>
27 
28 #include "adb_io.h"
29 #include "adb_unique_fd.h"
30 
restart_root_service(unique_fd fd)31 void restart_root_service(unique_fd fd) {
32     if (getuid() == 0) {
33         WriteFdExactly(fd.get(), "adbd is already running as root\n");
34         return;
35     }
36     if (!__android_log_is_debuggable()) {
37         WriteFdExactly(fd.get(), "adbd cannot run as root in production builds\n");
38         return;
39     }
40 
41     LOG(INFO) << "adbd restarting as root";
42     android::base::SetProperty("service.adb.root", "1");
43     WriteFdExactly(fd.get(), "restarting adbd as root\n");
44 }
45 
restart_unroot_service(unique_fd fd)46 void restart_unroot_service(unique_fd fd) {
47     if (getuid() != 0) {
48         WriteFdExactly(fd.get(), "adbd not running as root\n");
49         return;
50     }
51 
52     LOG(INFO) << "adbd restarting as nonroot";
53     android::base::SetProperty("service.adb.root", "0");
54     WriteFdExactly(fd.get(), "restarting adbd as non root\n");
55 }
56 
restart_tcp_service(unique_fd fd,int port)57 void restart_tcp_service(unique_fd fd, int port) {
58     if (port <= 0) {
59         WriteFdFmt(fd.get(), "invalid port %d\n", port);
60         return;
61     }
62 
63     LOG(INFO) << "adbd restarting in TCP mode (port = " << port << ")";
64     android::base::SetProperty("service.adb.tcp.port", android::base::StringPrintf("%d", port));
65     WriteFdFmt(fd.get(), "restarting in TCP mode port: %d\n", port);
66 }
67 
restart_usb_service(unique_fd fd)68 void restart_usb_service(unique_fd fd) {
69     LOG(INFO) << "adbd restarting in USB mode";
70     android::base::SetProperty("service.adb.tcp.port", "0");
71     WriteFdExactly(fd.get(), "restarting in USB mode\n");
72 }
73