Update {virtual,override,final} to follow C++11 style in tools.
[chromium-blink-merge.git] / tools / android / forwarder2 / host_forwarder_main.cc
blobf5d8e2f85d89c6d4849b6539aff94aa9c41919d9
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/safe_strerror_posix.h"
32 #include "base/strings/string_number_conversions.h"
33 #include "base/strings/string_piece.h"
34 #include "base/strings/string_split.h"
35 #include "base/strings/string_util.h"
36 #include "base/strings/stringprintf.h"
37 #include "base/task_runner.h"
38 #include "base/threading/thread.h"
39 #include "tools/android/forwarder2/common.h"
40 #include "tools/android/forwarder2/daemon.h"
41 #include "tools/android/forwarder2/host_controller.h"
42 #include "tools/android/forwarder2/pipe_notifier.h"
43 #include "tools/android/forwarder2/socket.h"
44 #include "tools/android/forwarder2/util.h"
46 namespace forwarder2 {
47 namespace {
49 const char kLogFilePath[] = "/tmp/host_forwarder_log";
50 const char kDaemonIdentifier[] = "chrome_host_forwarder_daemon";
52 const int kBufSize = 256;
54 // Needs to be global to be able to be accessed from the signal handler.
55 PipeNotifier* g_notifier = NULL;
57 // Lets the daemon fetch the exit notifier file descriptor.
58 int GetExitNotifierFD() {
59 DCHECK(g_notifier);
60 return g_notifier->receiver_fd();
63 void KillHandler(int signal_number) {
64 char buf[kBufSize];
65 if (signal_number != SIGTERM && signal_number != SIGINT) {
66 snprintf(buf, sizeof(buf), "Ignoring unexpected signal %d.", signal_number);
67 SIGNAL_SAFE_LOG(WARNING, buf);
68 return;
70 snprintf(buf, sizeof(buf), "Received signal %d.", signal_number);
71 SIGNAL_SAFE_LOG(WARNING, buf);
72 static int s_kill_handler_count = 0;
73 CHECK(g_notifier);
74 // If for some reason the forwarder get stuck in any socket waiting forever,
75 // we can send a SIGKILL or SIGINT three times to force it die
76 // (non-nicely). This is useful when debugging.
77 ++s_kill_handler_count;
78 if (!g_notifier->Notify() || s_kill_handler_count > 2)
79 exit(1);
82 // Manages HostController instances. There is one HostController instance for
83 // each connection being forwarded. Note that forwarding can happen with many
84 // devices (identified with a serial id).
85 class HostControllersManager {
86 public:
87 HostControllersManager()
88 : controllers_(new HostControllerMap()),
89 has_failed_(false),
90 weak_ptr_factory_(this) {
93 ~HostControllersManager() {
94 if (!thread_.get())
95 return;
96 // Delete the controllers on the thread they were created on.
97 thread_->message_loop_proxy()->DeleteSoon(
98 FROM_HERE, controllers_.release());
101 void HandleRequest(const std::string& adb_path,
102 const std::string& device_serial,
103 int device_port,
104 int host_port,
105 scoped_ptr<Socket> client_socket) {
106 // Lazy initialize so that the CLI process doesn't get this thread created.
107 InitOnce();
108 thread_->message_loop_proxy()->PostTask(
109 FROM_HERE,
110 base::Bind(&HostControllersManager::HandleRequestOnInternalThread,
111 base::Unretained(this), adb_path, device_serial, device_port,
112 host_port, base::Passed(&client_socket)));
115 bool has_failed() const { return has_failed_; }
117 private:
118 typedef base::hash_map<
119 std::string, linked_ptr<HostController> > HostControllerMap;
121 static std::string MakeHostControllerMapKey(int adb_port, int device_port) {
122 return base::StringPrintf("%d:%d", adb_port, device_port);
125 void InitOnce() {
126 if (thread_.get())
127 return;
128 at_exit_manager_.reset(new base::AtExitManager());
129 thread_.reset(new base::Thread("HostControllersManagerThread"));
130 thread_->Start();
133 // Invoked when a HostController instance reports an error (e.g. due to a
134 // device connectivity issue). Note that this could be called after the
135 // controller manager was destroyed which is why a weak pointer is used.
136 static void DeleteHostController(
137 const base::WeakPtr<HostControllersManager>& manager_ptr,
138 scoped_ptr<HostController> host_controller) {
139 HostController* const controller = host_controller.release();
140 HostControllersManager* const manager = manager_ptr.get();
141 if (!manager) {
142 // Note that |controller| is not leaked in this case since the host
143 // controllers manager owns the controllers. If the manager was deleted
144 // then all the controllers (including |controller|) were also deleted.
145 return;
147 DCHECK(manager->thread_->message_loop_proxy()->RunsTasksOnCurrentThread());
148 // Note that this will delete |controller| which is owned by the map.
149 DeleteRefCountedValueInMap(
150 MakeHostControllerMapKey(
151 controller->adb_port(), controller->device_port()),
152 manager->controllers_.get());
155 void HandleRequestOnInternalThread(const std::string& adb_path,
156 const std::string& device_serial,
157 int device_port,
158 int host_port,
159 scoped_ptr<Socket> client_socket) {
160 const int adb_port = GetAdbPortForDevice(adb_path, device_serial);
161 if (adb_port < 0) {
162 SendMessage(
163 "ERROR: could not get adb port for device. You might need to add "
164 "'adb' to your PATH or provide the device serial id.",
165 client_socket.get());
166 return;
168 if (device_port < 0) {
169 // Remove the previously created host controller.
170 const std::string controller_key = MakeHostControllerMapKey(
171 adb_port, -device_port);
172 const bool controller_did_exist = DeleteRefCountedValueInMap(
173 controller_key, controllers_.get());
174 SendMessage(
175 !controller_did_exist ? "ERROR: could not unmap port" : "OK",
176 client_socket.get());
178 RemoveAdbPortForDeviceIfNeeded(adb_path, device_serial);
179 return;
181 if (host_port < 0) {
182 SendMessage("ERROR: missing host port", client_socket.get());
183 return;
185 const bool use_dynamic_port_allocation = device_port == 0;
186 if (!use_dynamic_port_allocation) {
187 const std::string controller_key = MakeHostControllerMapKey(
188 adb_port, device_port);
189 if (controllers_->find(controller_key) != controllers_->end()) {
190 LOG(INFO) << "Already forwarding device port " << device_port
191 << " to host port " << host_port;
192 SendMessage(base::StringPrintf("%d:%d", device_port, host_port),
193 client_socket.get());
194 return;
197 // Create a new host controller.
198 scoped_ptr<HostController> host_controller(
199 HostController::Create(
200 device_port, host_port, adb_port, GetExitNotifierFD(),
201 base::Bind(&HostControllersManager::DeleteHostController,
202 weak_ptr_factory_.GetWeakPtr())));
203 if (!host_controller.get()) {
204 has_failed_ = true;
205 SendMessage("ERROR: Connection to device failed.", client_socket.get());
206 return;
208 // Get the current allocated port.
209 device_port = host_controller->device_port();
210 LOG(INFO) << "Forwarding device port " << device_port << " to host port "
211 << host_port;
212 const std::string msg = base::StringPrintf("%d:%d", device_port, host_port);
213 if (!SendMessage(msg, client_socket.get()))
214 return;
215 host_controller->Start();
216 controllers_->insert(
217 std::make_pair(MakeHostControllerMapKey(adb_port, device_port),
218 linked_ptr<HostController>(host_controller.release())));
221 void RemoveAdbPortForDeviceIfNeeded(const std::string& adb_path,
222 const std::string& device_serial) {
223 base::hash_map<std::string, int>::const_iterator it =
224 device_serial_to_adb_port_map_.find(device_serial);
225 if (it == device_serial_to_adb_port_map_.end())
226 return;
228 int port = it->second;
229 const std::string prefix = base::StringPrintf("%d:", port);
230 for (HostControllerMap::const_iterator others = controllers_->begin();
231 others != controllers_->end(); ++others) {
232 if (others->first.find(prefix) == 0U)
233 return;
235 // No other port is being forwarded to this device:
236 // - Remove it from our internal serial -> adb port map.
237 // - Remove from "adb forward" command.
238 LOG(INFO) << "Device " << device_serial << " has no more ports.";
239 device_serial_to_adb_port_map_.erase(device_serial);
240 const std::string serial_part = device_serial.empty() ?
241 std::string() : std::string("-s ") + device_serial;
242 const std::string command = base::StringPrintf(
243 "%s %s forward --remove tcp:%d",
244 adb_path.c_str(),
245 serial_part.c_str(),
246 port);
247 const int ret = system(command.c_str());
248 LOG(INFO) << command << " ret: " << ret;
249 // Wait for the socket to be fully unmapped.
250 const std::string port_mapped_cmd = base::StringPrintf(
251 "lsof -nPi:%d",
252 port);
253 const int poll_interval_us = 500 * 1000;
254 int retries = 3;
255 while (retries) {
256 const int port_unmapped = system(port_mapped_cmd.c_str());
257 LOG(INFO) << "Device " << device_serial << " port " << port << " unmap "
258 << port_unmapped;
259 if (port_unmapped)
260 break;
261 --retries;
262 usleep(poll_interval_us);
266 int GetAdbPortForDevice(const std::string adb_path,
267 const std::string& device_serial) {
268 base::hash_map<std::string, int>::const_iterator it =
269 device_serial_to_adb_port_map_.find(device_serial);
270 if (it != device_serial_to_adb_port_map_.end())
271 return it->second;
272 Socket bind_socket;
273 CHECK(bind_socket.BindTcp("127.0.0.1", 0));
274 const int port = bind_socket.GetPort();
275 bind_socket.Close();
276 const std::string serial_part = device_serial.empty() ?
277 std::string() : std::string("-s ") + device_serial;
278 const std::string command = base::StringPrintf(
279 "%s %s forward tcp:%d localabstract:chrome_device_forwarder",
280 adb_path.c_str(),
281 serial_part.c_str(),
282 port);
283 LOG(INFO) << command;
284 const int ret = system(command.c_str());
285 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
286 return -1;
287 device_serial_to_adb_port_map_[device_serial] = port;
288 return port;
291 bool SendMessage(const std::string& msg, Socket* client_socket) {
292 bool result = client_socket->WriteString(msg);
293 DCHECK(result);
294 if (!result)
295 has_failed_ = true;
296 return result;
299 base::hash_map<std::string, int> device_serial_to_adb_port_map_;
300 scoped_ptr<HostControllerMap> controllers_;
301 bool has_failed_;
302 scoped_ptr<base::AtExitManager> at_exit_manager_; // Needed by base::Thread.
303 scoped_ptr<base::Thread> thread_;
304 base::WeakPtrFactory<HostControllersManager> weak_ptr_factory_;
307 class ServerDelegate : public Daemon::ServerDelegate {
308 public:
309 ServerDelegate(const std::string& adb_path)
310 : adb_path_(adb_path), has_failed_(false) {}
312 bool has_failed() const {
313 return has_failed_ || controllers_manager_.has_failed();
316 // Daemon::ServerDelegate:
317 void Init() override {
318 LOG(INFO) << "Starting host process daemon (pid=" << getpid() << ")";
319 DCHECK(!g_notifier);
320 g_notifier = new PipeNotifier();
321 signal(SIGTERM, KillHandler);
322 signal(SIGINT, KillHandler);
325 void OnClientConnected(scoped_ptr<Socket> client_socket) override {
326 char buf[kBufSize];
327 const int bytes_read = client_socket->Read(buf, sizeof(buf));
328 if (bytes_read <= 0) {
329 if (client_socket->DidReceiveEvent())
330 return;
331 PError("Read()");
332 has_failed_ = true;
333 return;
335 const Pickle command_pickle(buf, bytes_read);
336 PickleIterator pickle_it(command_pickle);
337 std::string device_serial;
338 CHECK(pickle_it.ReadString(&device_serial));
339 int device_port;
340 if (!pickle_it.ReadInt(&device_port)) {
341 client_socket->WriteString("ERROR: missing device port");
342 return;
344 int host_port;
345 if (!pickle_it.ReadInt(&host_port))
346 host_port = -1;
347 controllers_manager_.HandleRequest(adb_path_, device_serial, device_port,
348 host_port, client_socket.Pass());
351 private:
352 std::string adb_path_;
353 bool has_failed_;
354 HostControllersManager controllers_manager_;
356 DISALLOW_COPY_AND_ASSIGN(ServerDelegate);
359 class ClientDelegate : public Daemon::ClientDelegate {
360 public:
361 ClientDelegate(const Pickle& command_pickle)
362 : command_pickle_(command_pickle),
363 has_failed_(false) {
366 bool has_failed() const { return has_failed_; }
368 // Daemon::ClientDelegate:
369 void OnDaemonReady(Socket* daemon_socket) override {
370 // Send the forward command to the daemon.
371 CHECK_EQ(static_cast<long>(command_pickle_.size()),
372 daemon_socket->WriteNumBytes(command_pickle_.data(),
373 command_pickle_.size()));
374 char buf[kBufSize];
375 const int bytes_read = daemon_socket->Read(
376 buf, sizeof(buf) - 1 /* leave space for null terminator */);
377 CHECK_GT(bytes_read, 0);
378 DCHECK(static_cast<size_t>(bytes_read) < sizeof(buf));
379 buf[bytes_read] = 0;
380 base::StringPiece msg(buf, bytes_read);
381 if (msg.starts_with("ERROR")) {
382 LOG(ERROR) << msg;
383 has_failed_ = true;
384 return;
386 printf("%s\n", buf);
389 private:
390 const Pickle command_pickle_;
391 bool has_failed_;
394 void ExitWithUsage() {
395 std::cerr << "Usage: host_forwarder [options]\n\n"
396 "Options:\n"
397 " --serial-id=[0-9A-Z]{16}]\n"
398 " --map DEVICE_PORT HOST_PORT\n"
399 " --unmap DEVICE_PORT\n"
400 " --adb PATH_TO_ADB\n"
401 " --kill-server\n";
402 exit(1);
405 int PortToInt(const std::string& s) {
406 int value;
407 // Note that 0 is a valid port (used for dynamic port allocation).
408 if (!base::StringToInt(s, &value) || value < 0 ||
409 value > std::numeric_limits<uint16>::max()) {
410 LOG(ERROR) << "Could not convert string " << s << " to port";
411 ExitWithUsage();
413 return value;
416 int RunHostForwarder(int argc, char** argv) {
417 base::CommandLine::Init(argc, argv);
418 const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
419 std::string adb_path = "adb";
420 bool kill_server = false;
422 Pickle pickle;
423 pickle.WriteString(
424 cmd_line.HasSwitch("serial-id") ?
425 cmd_line.GetSwitchValueASCII("serial-id") : std::string());
427 const std::vector<std::string> args = cmd_line.GetArgs();
428 if (cmd_line.HasSwitch("kill-server")) {
429 kill_server = true;
430 } else if (cmd_line.HasSwitch("unmap")) {
431 if (args.size() != 1)
432 ExitWithUsage();
433 // Note the minus sign below.
434 pickle.WriteInt(-PortToInt(args[0]));
435 } else if (cmd_line.HasSwitch("map")) {
436 if (args.size() != 2)
437 ExitWithUsage();
438 pickle.WriteInt(PortToInt(args[0]));
439 pickle.WriteInt(PortToInt(args[1]));
440 } else {
441 ExitWithUsage();
444 if (cmd_line.HasSwitch("adb")) {
445 adb_path = cmd_line.GetSwitchValueASCII("adb");
448 if (kill_server && args.size() > 0)
449 ExitWithUsage();
451 ClientDelegate client_delegate(pickle);
452 ServerDelegate daemon_delegate(adb_path);
453 Daemon daemon(
454 kLogFilePath, kDaemonIdentifier, &client_delegate, &daemon_delegate,
455 &GetExitNotifierFD);
457 if (kill_server)
458 return !daemon.Kill();
459 if (!daemon.SpawnIfNeeded())
460 return 1;
462 return client_delegate.has_failed() || daemon_delegate.has_failed();
465 } // namespace
466 } // namespace forwarder2
468 int main(int argc, char** argv) {
469 return forwarder2::RunHostForwarder(argc, argv);