[sql] Remove _HAS_EXCEPTIONS=0 from build info.
[chromium-blink-merge.git] / tools / android / forwarder2 / host_forwarder_main.cc
blobddb56c09b535b1ca76734ff001ebd5a7b6286798
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <errno.h>
6 #include <signal.h>
7 #include <sys/types.h>
8 #include <sys/wait.h>
9 #include <unistd.h>
11 #include <cstdio>
12 #include <iostream>
13 #include <limits>
14 #include <string>
15 #include <utility>
16 #include <vector>
18 #include "base/at_exit.h"
19 #include "base/basictypes.h"
20 #include "base/bind.h"
21 #include "base/command_line.h"
22 #include "base/compiler_specific.h"
23 #include "base/containers/hash_tables.h"
24 #include "base/files/file_path.h"
25 #include "base/files/file_util.h"
26 #include "base/logging.h"
27 #include "base/memory/linked_ptr.h"
28 #include "base/memory/scoped_vector.h"
29 #include "base/memory/weak_ptr.h"
30 #include "base/pickle.h"
31 #include "base/strings/string_number_conversions.h"
32 #include "base/strings/string_piece.h"
33 #include "base/strings/string_split.h"
34 #include "base/strings/string_util.h"
35 #include "base/strings/stringprintf.h"
36 #include "base/task_runner.h"
37 #include "base/threading/thread.h"
38 #include "tools/android/forwarder2/common.h"
39 #include "tools/android/forwarder2/daemon.h"
40 #include "tools/android/forwarder2/host_controller.h"
41 #include "tools/android/forwarder2/pipe_notifier.h"
42 #include "tools/android/forwarder2/socket.h"
43 #include "tools/android/forwarder2/util.h"
45 namespace forwarder2 {
46 namespace {
48 const char kLogFilePath[] = "/tmp/host_forwarder_log";
49 const char kDaemonIdentifier[] = "chrome_host_forwarder_daemon";
51 const int kBufSize = 256;
53 // Needs to be global to be able to be accessed from the signal handler.
54 PipeNotifier* g_notifier = NULL;
56 // Lets the daemon fetch the exit notifier file descriptor.
57 int GetExitNotifierFD() {
58 DCHECK(g_notifier);
59 return g_notifier->receiver_fd();
62 void KillHandler(int signal_number) {
63 char buf[kBufSize];
64 if (signal_number != SIGTERM && signal_number != SIGINT) {
65 snprintf(buf, sizeof(buf), "Ignoring unexpected signal %d.", signal_number);
66 SIGNAL_SAFE_LOG(WARNING, buf);
67 return;
69 snprintf(buf, sizeof(buf), "Received signal %d.", signal_number);
70 SIGNAL_SAFE_LOG(WARNING, buf);
71 static int s_kill_handler_count = 0;
72 CHECK(g_notifier);
73 // If for some reason the forwarder get stuck in any socket waiting forever,
74 // we can send a SIGKILL or SIGINT three times to force it die
75 // (non-nicely). This is useful when debugging.
76 ++s_kill_handler_count;
77 if (!g_notifier->Notify() || s_kill_handler_count > 2)
78 exit(1);
81 // Manages HostController instances. There is one HostController instance for
82 // each connection being forwarded. Note that forwarding can happen with many
83 // devices (identified with a serial id).
84 class HostControllersManager {
85 public:
86 HostControllersManager()
87 : controllers_(new HostControllerMap()),
88 has_failed_(false),
89 weak_ptr_factory_(this) {
92 ~HostControllersManager() {
93 if (!thread_.get())
94 return;
95 // Delete the controllers on the thread they were created on.
96 thread_->task_runner()->DeleteSoon(
97 FROM_HERE, controllers_.release());
100 void HandleRequest(const std::string& adb_path,
101 const std::string& device_serial,
102 int device_port,
103 int host_port,
104 scoped_ptr<Socket> client_socket) {
105 // Lazy initialize so that the CLI process doesn't get this thread created.
106 InitOnce();
107 thread_->task_runner()->PostTask(
108 FROM_HERE,
109 base::Bind(&HostControllersManager::HandleRequestOnInternalThread,
110 base::Unretained(this), adb_path, device_serial, device_port,
111 host_port, base::Passed(&client_socket)));
114 bool has_failed() const { return has_failed_; }
116 private:
117 typedef base::hash_map<
118 std::string, linked_ptr<HostController> > HostControllerMap;
120 static std::string MakeHostControllerMapKey(int adb_port, int device_port) {
121 return base::StringPrintf("%d:%d", adb_port, device_port);
124 void InitOnce() {
125 if (thread_.get())
126 return;
127 at_exit_manager_.reset(new base::AtExitManager());
128 thread_.reset(new base::Thread("HostControllersManagerThread"));
129 thread_->Start();
132 // Invoked when a HostController instance reports an error (e.g. due to a
133 // device connectivity issue). Note that this could be called after the
134 // controller manager was destroyed which is why a weak pointer is used.
135 static void DeleteHostController(
136 const base::WeakPtr<HostControllersManager>& manager_ptr,
137 scoped_ptr<HostController> host_controller) {
138 HostController* const controller = host_controller.release();
139 HostControllersManager* const manager = manager_ptr.get();
140 if (!manager) {
141 // Note that |controller| is not leaked in this case since the host
142 // controllers manager owns the controllers. If the manager was deleted
143 // then all the controllers (including |controller|) were also deleted.
144 return;
146 DCHECK(manager->thread_->task_runner()->RunsTasksOnCurrentThread());
147 // Note that this will delete |controller| which is owned by the map.
148 DeleteRefCountedValueInMap(
149 MakeHostControllerMapKey(
150 controller->adb_port(), controller->device_port()),
151 manager->controllers_.get());
154 void HandleRequestOnInternalThread(const std::string& adb_path,
155 const std::string& device_serial,
156 int device_port,
157 int host_port,
158 scoped_ptr<Socket> client_socket) {
159 const int adb_port = GetAdbPortForDevice(adb_path, device_serial);
160 if (adb_port < 0) {
161 SendMessage(
162 "ERROR: could not get adb port for device. You might need to add "
163 "'adb' to your PATH or provide the device serial id.",
164 client_socket.get());
165 return;
167 if (device_port < 0) {
168 // Remove the previously created host controller.
169 const std::string controller_key = MakeHostControllerMapKey(
170 adb_port, -device_port);
171 const bool controller_did_exist = DeleteRefCountedValueInMap(
172 controller_key, controllers_.get());
173 SendMessage(
174 !controller_did_exist ? "ERROR: could not unmap port" : "OK",
175 client_socket.get());
177 RemoveAdbPortForDeviceIfNeeded(adb_path, device_serial);
178 return;
180 if (host_port < 0) {
181 SendMessage("ERROR: missing host port", client_socket.get());
182 return;
184 const bool use_dynamic_port_allocation = device_port == 0;
185 if (!use_dynamic_port_allocation) {
186 const std::string controller_key = MakeHostControllerMapKey(
187 adb_port, device_port);
188 if (controllers_->find(controller_key) != controllers_->end()) {
189 LOG(INFO) << "Already forwarding device port " << device_port
190 << " to host port " << host_port;
191 SendMessage(base::StringPrintf("%d:%d", device_port, host_port),
192 client_socket.get());
193 return;
196 // Create a new host controller.
197 scoped_ptr<HostController> host_controller(
198 HostController::Create(
199 device_port, host_port, adb_port, GetExitNotifierFD(),
200 base::Bind(&HostControllersManager::DeleteHostController,
201 weak_ptr_factory_.GetWeakPtr())));
202 if (!host_controller.get()) {
203 has_failed_ = true;
204 SendMessage("ERROR: Connection to device failed.", client_socket.get());
205 return;
207 // Get the current allocated port.
208 device_port = host_controller->device_port();
209 LOG(INFO) << "Forwarding device port " << device_port << " to host port "
210 << host_port;
211 const std::string msg = base::StringPrintf("%d:%d", device_port, host_port);
212 if (!SendMessage(msg, client_socket.get()))
213 return;
214 host_controller->Start();
215 controllers_->insert(
216 std::make_pair(MakeHostControllerMapKey(adb_port, device_port),
217 linked_ptr<HostController>(host_controller.release())));
220 void RemoveAdbPortForDeviceIfNeeded(const std::string& adb_path,
221 const std::string& device_serial) {
222 base::hash_map<std::string, int>::const_iterator it =
223 device_serial_to_adb_port_map_.find(device_serial);
224 if (it == device_serial_to_adb_port_map_.end())
225 return;
227 int port = it->second;
228 const std::string prefix = base::StringPrintf("%d:", port);
229 for (HostControllerMap::const_iterator others = controllers_->begin();
230 others != controllers_->end(); ++others) {
231 if (others->first.find(prefix) == 0U)
232 return;
234 // No other port is being forwarded to this device:
235 // - Remove it from our internal serial -> adb port map.
236 // - Remove from "adb forward" command.
237 LOG(INFO) << "Device " << device_serial << " has no more ports.";
238 device_serial_to_adb_port_map_.erase(device_serial);
239 const std::string serial_part = device_serial.empty() ?
240 std::string() : std::string("-s ") + device_serial;
241 const std::string command = base::StringPrintf(
242 "%s %s forward --remove tcp:%d",
243 adb_path.c_str(),
244 serial_part.c_str(),
245 port);
246 const int ret = system(command.c_str());
247 LOG(INFO) << command << " ret: " << ret;
248 // Wait for the socket to be fully unmapped.
249 const std::string port_mapped_cmd = base::StringPrintf(
250 "lsof -nPi:%d",
251 port);
252 const int poll_interval_us = 500 * 1000;
253 int retries = 3;
254 while (retries) {
255 const int port_unmapped = system(port_mapped_cmd.c_str());
256 LOG(INFO) << "Device " << device_serial << " port " << port << " unmap "
257 << port_unmapped;
258 if (port_unmapped)
259 break;
260 --retries;
261 usleep(poll_interval_us);
265 int GetAdbPortForDevice(const std::string adb_path,
266 const std::string& device_serial) {
267 base::hash_map<std::string, int>::const_iterator it =
268 device_serial_to_adb_port_map_.find(device_serial);
269 if (it != device_serial_to_adb_port_map_.end())
270 return it->second;
271 Socket bind_socket;
272 CHECK(bind_socket.BindTcp("127.0.0.1", 0));
273 const int port = bind_socket.GetPort();
274 bind_socket.Close();
275 const std::string serial_part = device_serial.empty() ?
276 std::string() : std::string("-s ") + device_serial;
277 const std::string command = base::StringPrintf(
278 "%s %s forward tcp:%d localabstract:chrome_device_forwarder",
279 adb_path.c_str(),
280 serial_part.c_str(),
281 port);
282 LOG(INFO) << command;
283 const int ret = system(command.c_str());
284 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
285 return -1;
286 device_serial_to_adb_port_map_[device_serial] = port;
287 return port;
290 bool SendMessage(const std::string& msg, Socket* client_socket) {
291 bool result = client_socket->WriteString(msg);
292 DCHECK(result);
293 if (!result)
294 has_failed_ = true;
295 return result;
298 base::hash_map<std::string, int> device_serial_to_adb_port_map_;
299 scoped_ptr<HostControllerMap> controllers_;
300 bool has_failed_;
301 scoped_ptr<base::AtExitManager> at_exit_manager_; // Needed by base::Thread.
302 scoped_ptr<base::Thread> thread_;
303 base::WeakPtrFactory<HostControllersManager> weak_ptr_factory_;
306 class ServerDelegate : public Daemon::ServerDelegate {
307 public:
308 ServerDelegate(const std::string& adb_path)
309 : adb_path_(adb_path), has_failed_(false) {}
311 bool has_failed() const {
312 return has_failed_ || controllers_manager_.has_failed();
315 // Daemon::ServerDelegate:
316 void Init() override {
317 LOG(INFO) << "Starting host process daemon (pid=" << getpid() << ")";
318 DCHECK(!g_notifier);
319 g_notifier = new PipeNotifier();
320 signal(SIGTERM, KillHandler);
321 signal(SIGINT, KillHandler);
324 void OnClientConnected(scoped_ptr<Socket> client_socket) override {
325 char buf[kBufSize];
326 const int bytes_read = client_socket->Read(buf, sizeof(buf));
327 if (bytes_read <= 0) {
328 if (client_socket->DidReceiveEvent())
329 return;
330 PError("Read()");
331 has_failed_ = true;
332 return;
334 const base::Pickle command_pickle(buf, bytes_read);
335 base::PickleIterator pickle_it(command_pickle);
336 std::string device_serial;
337 CHECK(pickle_it.ReadString(&device_serial));
338 int device_port;
339 if (!pickle_it.ReadInt(&device_port)) {
340 client_socket->WriteString("ERROR: missing device port");
341 return;
343 int host_port;
344 if (!pickle_it.ReadInt(&host_port))
345 host_port = -1;
346 controllers_manager_.HandleRequest(adb_path_, device_serial, device_port,
347 host_port, client_socket.Pass());
350 private:
351 std::string adb_path_;
352 bool has_failed_;
353 HostControllersManager controllers_manager_;
355 DISALLOW_COPY_AND_ASSIGN(ServerDelegate);
358 class ClientDelegate : public Daemon::ClientDelegate {
359 public:
360 ClientDelegate(const base::Pickle& command_pickle)
361 : command_pickle_(command_pickle), has_failed_(false) {}
363 bool has_failed() const { return has_failed_; }
365 // Daemon::ClientDelegate:
366 void OnDaemonReady(Socket* daemon_socket) override {
367 // Send the forward command to the daemon.
368 CHECK_EQ(static_cast<long>(command_pickle_.size()),
369 daemon_socket->WriteNumBytes(command_pickle_.data(),
370 command_pickle_.size()));
371 char buf[kBufSize];
372 const int bytes_read = daemon_socket->Read(
373 buf, sizeof(buf) - 1 /* leave space for null terminator */);
374 CHECK_GT(bytes_read, 0);
375 DCHECK(static_cast<size_t>(bytes_read) < sizeof(buf));
376 buf[bytes_read] = 0;
377 base::StringPiece msg(buf, bytes_read);
378 if (msg.starts_with("ERROR")) {
379 LOG(ERROR) << msg;
380 has_failed_ = true;
381 return;
383 printf("%s\n", buf);
386 private:
387 const base::Pickle command_pickle_;
388 bool has_failed_;
391 void ExitWithUsage() {
392 std::cerr << "Usage: host_forwarder [options]\n\n"
393 "Options:\n"
394 " --serial-id=[0-9A-Z]{16}]\n"
395 " --map DEVICE_PORT HOST_PORT\n"
396 " --unmap DEVICE_PORT\n"
397 " --adb PATH_TO_ADB\n"
398 " --kill-server\n";
399 exit(1);
402 int PortToInt(const std::string& s) {
403 int value;
404 // Note that 0 is a valid port (used for dynamic port allocation).
405 if (!base::StringToInt(s, &value) || value < 0 ||
406 value > std::numeric_limits<uint16>::max()) {
407 LOG(ERROR) << "Could not convert string " << s << " to port";
408 ExitWithUsage();
410 return value;
413 int RunHostForwarder(int argc, char** argv) {
414 base::CommandLine::Init(argc, argv);
415 const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
416 std::string adb_path = "adb";
417 bool kill_server = false;
419 base::Pickle pickle;
420 pickle.WriteString(
421 cmd_line.HasSwitch("serial-id") ?
422 cmd_line.GetSwitchValueASCII("serial-id") : std::string());
424 const std::vector<std::string> args = cmd_line.GetArgs();
425 if (cmd_line.HasSwitch("kill-server")) {
426 kill_server = true;
427 } else if (cmd_line.HasSwitch("unmap")) {
428 if (args.size() != 1)
429 ExitWithUsage();
430 // Note the minus sign below.
431 pickle.WriteInt(-PortToInt(args[0]));
432 } else if (cmd_line.HasSwitch("map")) {
433 if (args.size() != 2)
434 ExitWithUsage();
435 pickle.WriteInt(PortToInt(args[0]));
436 pickle.WriteInt(PortToInt(args[1]));
437 } else {
438 ExitWithUsage();
441 if (cmd_line.HasSwitch("adb")) {
442 adb_path = cmd_line.GetSwitchValueASCII("adb");
445 if (kill_server && args.size() > 0)
446 ExitWithUsage();
448 ClientDelegate client_delegate(pickle);
449 ServerDelegate daemon_delegate(adb_path);
450 Daemon daemon(
451 kLogFilePath, kDaemonIdentifier, &client_delegate, &daemon_delegate,
452 &GetExitNotifierFD);
454 if (kill_server)
455 return !daemon.Kill();
456 if (!daemon.SpawnIfNeeded())
457 return 1;
459 return client_delegate.has_failed() || daemon_delegate.has_failed();
462 } // namespace
463 } // namespace forwarder2
465 int main(int argc, char** argv) {
466 return forwarder2::RunHostForwarder(argc, argv);