1 /*
2  * Copyright (C) 2015 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 "adb_listeners.h"
18 
19 #include <stdio.h>
20 #include <stdlib.h>
21 
22 #include <algorithm>
23 #include <list>
24 #include <memory>
25 
26 #include <android-base/stringprintf.h>
27 #include <android-base/strings.h>
28 #include <android-base/thread_annotations.h>
29 #include <cutils/sockets.h>
30 
31 #include "socket_spec.h"
32 #include "sysdeps.h"
33 #include "transport.h"
34 
35 // A listener is an entity which binds to a local port and, upon receiving a connection on that
36 // port, creates an asocket to connect the new local connection to a specific remote service. They
37 // are mostly used to implement forward and reverse-forward.
38 //
39 // Some listeners, called "smartsockets" read from the new connection to determine what exact
40 // service to connect to on the far side. This is implemented with a different fdevent handler.
41 class alistener {
42   public:
43     alistener(const std::string& _local_name, const std::string& _connect_to);
44     ~alistener();
45 
isSmartSocket()46     bool isSmartSocket() { return connect_to == kSmartSocketConnectTo; }
47 
48     fdevent* fde = nullptr;
49     int fd = -1;
50 
51     std::string local_name;
52     std::string connect_to;
53     atransport* transport = nullptr;
54     adisconnect disconnect;
55 
56   private:
57     DISALLOW_COPY_AND_ASSIGN(alistener);
58 };
59 
alistener(const std::string & _local_name,const std::string & _connect_to)60 alistener::alistener(const std::string& _local_name, const std::string& _connect_to)
61     : local_name(_local_name), connect_to(_connect_to) {
62 }
63 
~alistener()64 alistener::~alistener() {
65     // Closes the corresponding fd.
66     fdevent_destroy(fde);
67 
68     if (transport) {
69         transport->RemoveDisconnect(&disconnect);
70     }
71 }
72 
73 // listener_list retains ownership of all created alistener objects. Removing an alistener from
74 // this list will cause it to be deleted.
75 static auto& listener_list_mutex = *new std::mutex();
76 typedef std::list<std::unique_ptr<alistener>> ListenerList;
77 static ListenerList& listener_list GUARDED_BY(listener_list_mutex) = *new ListenerList();
78 
79 #if ADB_HOST
ss_listener_event_func(int _fd,unsigned ev,void * _l)80 static void ss_listener_event_func(int _fd, unsigned ev, void *_l) {
81     if (ev & FDE_READ) {
82         unique_fd fd(adb_socket_accept(_fd, nullptr, nullptr));
83         if (fd < 0) return;
84 
85         int rcv_buf_size = CHUNK_SIZE;
86         adb_setsockopt(fd.get(), SOL_SOCKET, SO_RCVBUF, &rcv_buf_size, sizeof(rcv_buf_size));
87 
88         asocket* s = create_local_socket(std::move(fd));
89         if (s) {
90             connect_to_smartsocket(s);
91             return;
92         }
93     }
94 }
95 #endif
96 
listener_event_func(int _fd,unsigned ev,void * _l)97 static void listener_event_func(int _fd, unsigned ev, void* _l)
98 {
99     alistener* listener = reinterpret_cast<alistener*>(_l);
100 
101     if (ev & FDE_READ) {
102         unique_fd fd(adb_socket_accept(_fd, nullptr, nullptr));
103         if (fd < 0) {
104             return;
105         }
106 
107         asocket* s = create_local_socket(std::move(fd));
108         if (s) {
109             s->transport = listener->transport;
110             connect_to_remote(s, listener->connect_to);
111             return;
112         }
113     }
114 }
115 
116 // Called as a transport disconnect function. |arg| is the raw alistener*.
listener_disconnect(void * arg,atransport *)117 static void listener_disconnect(void* arg, atransport*) EXCLUDES(listener_list_mutex) {
118     std::lock_guard<std::mutex> lock(listener_list_mutex);
119     for (auto iter = listener_list.begin(); iter != listener_list.end(); ++iter) {
120         if (iter->get() == arg) {
121             (*iter)->transport = nullptr;
122             listener_list.erase(iter);
123             return;
124         }
125     }
126 }
127 
128 // Write the list of current listeners (network redirections) into a string.
format_listeners()129 std::string format_listeners() EXCLUDES(listener_list_mutex) {
130     std::lock_guard<std::mutex> lock(listener_list_mutex);
131     std::string result;
132     for (auto& l : listener_list) {
133         if (l->isSmartSocket()) {
134             continue;
135         }
136         //  <device-serial> " " <local-name> " " <remote-name> "\n"
137         // Entries from "adb reverse" have no serial.
138         android::base::StringAppendF(
139                 &result, "%s %s %s\n",
140                 !l->transport->serial.empty() ? l->transport->serial.c_str() : "(reverse)",
141                 l->local_name.c_str(), l->connect_to.c_str());
142     }
143     return result;
144 }
145 
remove_listener(const char * local_name,atransport * transport)146 InstallStatus remove_listener(const char* local_name, atransport* transport)
147     EXCLUDES(listener_list_mutex) {
148     std::lock_guard<std::mutex> lock(listener_list_mutex);
149     for (auto iter = listener_list.begin(); iter != listener_list.end(); ++iter) {
150         if (local_name == (*iter)->local_name) {
151             listener_list.erase(iter);
152             return INSTALL_STATUS_OK;
153         }
154     }
155     return INSTALL_STATUS_LISTENER_NOT_FOUND;
156 }
157 
remove_all_listeners()158 void remove_all_listeners() EXCLUDES(listener_list_mutex) {
159     std::lock_guard<std::mutex> lock(listener_list_mutex);
160     auto iter = listener_list.begin();
161     while (iter != listener_list.end()) {
162         // Never remove smart sockets.
163         if ((*iter)->connect_to[0] == '*') {
164             ++iter;
165         } else {
166             iter = listener_list.erase(iter);
167         }
168     }
169 }
170 
171 #if ADB_HOST
enable_server_sockets()172 void enable_server_sockets() EXCLUDES(listener_list_mutex) {
173     std::lock_guard<std::mutex> lock(listener_list_mutex);
174     for (auto& l : listener_list) {
175         if (l->isSmartSocket()) {
176             fdevent_set(l->fde, FDE_READ);
177         }
178     }
179 }
180 
close_smartsockets()181 void close_smartsockets() EXCLUDES(listener_list_mutex) {
182     std::lock_guard<std::mutex> lock(listener_list_mutex);
183     auto pred = [](const std::unique_ptr<alistener>& listener) {
184         return listener->isSmartSocket();
185     };
186     listener_list.remove_if(pred);
187 }
188 #endif
189 
install_listener(const std::string & local_name,const char * connect_to,atransport * transport,int flags,int * resolved_tcp_port,std::string * error)190 InstallStatus install_listener(const std::string& local_name, const char* connect_to,
191                                atransport* transport, int flags, int* resolved_tcp_port,
192                                std::string* error) EXCLUDES(listener_list_mutex) {
193     std::lock_guard<std::mutex> lock(listener_list_mutex);
194     for (auto& l : listener_list) {
195         if (local_name == l->local_name) {
196             // Can't repurpose a smartsocket.
197             if (l->isSmartSocket()) {
198                 *error = "cannot repurpose smartsocket";
199                 return INSTALL_STATUS_INTERNAL_ERROR;
200             }
201 
202             // Can't repurpose a listener if INSTALL_LISTENER_NO_REBIND is set
203             if (flags & INSTALL_LISTENER_NO_REBIND) {
204                 *error = "cannot rebind";
205                 return INSTALL_STATUS_CANNOT_REBIND;
206             }
207 
208             l->connect_to = connect_to;
209             if (l->transport != transport) {
210                 l->transport->RemoveDisconnect(&l->disconnect);
211                 l->transport = transport;
212                 l->transport->AddDisconnect(&l->disconnect);
213             }
214             return INSTALL_STATUS_OK;
215         }
216     }
217 
218     auto listener = std::make_unique<alistener>(local_name, connect_to);
219 
220     int resolved = 0;
221     listener->fd = socket_spec_listen(listener->local_name, error, &resolved);
222     if (listener->fd < 0) {
223         return INSTALL_STATUS_CANNOT_BIND;
224     }
225 
226     // If the caller requested port 0, update the listener name with the resolved port.
227     if (resolved != 0) {
228         listener->local_name = android::base::StringPrintf("tcp:%d", resolved);
229         if (resolved_tcp_port) {
230             *resolved_tcp_port = resolved;
231         }
232     }
233 
234     close_on_exec(listener->fd);
235     if (listener->isSmartSocket()) {
236 #if ADB_HOST
237         listener->fde = fdevent_create(listener->fd, ss_listener_event_func, listener.get());
238 #else
239         LOG(FATAL) << "attempted to connect to *smartsocket* in daemon";
240 #endif
241     } else {
242         listener->fde = fdevent_create(listener->fd, listener_event_func, listener.get());
243     }
244     if ((flags & INSTALL_LISTENER_DISABLED) == 0) {
245         fdevent_set(listener->fde, FDE_READ);
246     }
247 
248     listener->transport = transport;
249 
250     if (transport) {
251         listener->disconnect.opaque = listener.get();
252         listener->disconnect.func = listener_disconnect;
253         transport->AddDisconnect(&listener->disconnect);
254     }
255 
256     listener_list.push_back(std::move(listener));
257     return INSTALL_STATUS_OK;
258 }
259