Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(376)

Side by Side Diff: tools/android/forwarder2/host_forwarder_main.cc

Issue 11269036: Support HTTP test-server based net unit tests on Android. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Revert changes in net_unittests_disabled Created 8 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include <errno.h> 5 #include <errno.h>
6 #include <signal.h> 6 #include <signal.h>
7 #include <stdio.h> 7 #include <stdio.h>
8 #include <stdlib.h> 8 #include <stdlib.h>
9 #include <unistd.h>
9 10
10 #include <vector> 11 #include <vector>
11 #include <string> 12 #include <string>
12 13
13 #include "base/command_line.h" 14 #include "base/command_line.h"
15 #include "base/eintr_wrapper.h"
16 #include "base/file_path.h"
17 #include "base/file_util.h"
14 #include "base/logging.h" 18 #include "base/logging.h"
15 #include "base/memory/scoped_vector.h" 19 #include "base/memory/scoped_vector.h"
20 #include "base/safe_strerror_posix.h"
16 #include "base/string_number_conversions.h" 21 #include "base/string_number_conversions.h"
17 #include "base/string_piece.h" 22 #include "base/string_piece.h"
18 #include "base/string_split.h" 23 #include "base/string_split.h"
24 #include "base/string_util.h"
19 #include "base/stringprintf.h" 25 #include "base/stringprintf.h"
20 #include "tools/android/common/daemon.h" 26 #include "tools/android/forwarder2/daemon.h"
21 #include "tools/android/forwarder2/host_controller.h" 27 #include "tools/android/forwarder2/host_controller.h"
22 #include "tools/android/forwarder2/pipe_notifier.h" 28 #include "tools/android/forwarder2/pipe_notifier.h"
29 #include "tools/android/forwarder2/socket.h"
23 30
24 using base::StringToInt; 31 using base::StringToInt;
25 using forwarder2::HostController; 32 using forwarder2::HostController;
33 using forwarder2::Socket;
26 34
27 namespace { 35 namespace {
28 36
29 const int kDefaultAdbPort = 3000; 37 const char kPIDFilePath[] = "/tmp/host_forwarder_pid";
38 const char kCommandSocketPath[] = "host_forwarder_command_socket";
39 const char kWelcomeMessage[] = "forwarder2";
30 40
31 // Need to be global to be able to accessed from the signal handler. 41 // Need to be global to be able to accessed from the signal handler.
32 forwarder2::PipeNotifier* g_notifier; 42 forwarder2::PipeNotifier* g_notifier;
33 43
34 void KillHandler(int /* unused */) { 44 void PError(const char* msg) {
45 LOG(ERROR) << msg << ": " << safe_strerror(errno);
46 }
47
48 void CloseFD(int fd) {
49 if (HANDLE_EINTR(close(fd)) < 0)
50 PError("close");
51 }
52
53 void KillHandler(int signal_number) {
54 if (signal_number != SIGTERM && signal_number != SIGINT) {
55 LOG(ERROR) << "Ignoring unexpected signal " << signal_number;
56 return;
57 }
35 static int s_kill_handler_count = 0; 58 static int s_kill_handler_count = 0;
36 CHECK(g_notifier); 59 CHECK(g_notifier);
37 // If for some reason the forwarder get stuck in any socket waiting forever, 60 // If for some reason the forwarder get stuck in any socket waiting forever,
38 // we can send a SIGKILL or SIGINT three times to force it die 61 // we can send a SIGKILL or SIGINT three times to force it die
39 // (non-nicely). This is useful when debugging. 62 // (non-nicely). This is useful when debugging.
40 ++s_kill_handler_count; 63 ++s_kill_handler_count;
41 if (!g_notifier->Notify() || s_kill_handler_count > 2) 64 if (!g_notifier->Notify() || s_kill_handler_count > 2)
42 exit(1); 65 exit(1);
43 } 66 }
44 67
45 // Format of arg: <Device port>[:<Forward to port>:<Forward to address>] 68 enum {
46 bool ParseForwardArg(const std::string& arg, 69 kConnectSingleTry = 1,
47 int* device_port, 70 kConnectNoIdleTime = 0,
48 std::string* forward_to_host, 71 };
49 int* forward_to_port) { 72
50 std::vector<std::string> arg_pieces; 73 scoped_ptr<Socket> ConnectToDaemon(int tries_count, int idle_time_msec) {
51 base::SplitString(arg, ':', &arg_pieces); 74 for (int i = 0; i < tries_count; ++i) {
52 if (arg_pieces.size() == 0 || !StringToInt(arg_pieces[0], device_port)) 75 scoped_ptr<Socket> socket(new Socket());
76 if (!socket->ConnectUnix(kCommandSocketPath, true)) {
77 if (idle_time_msec)
78 usleep(idle_time_msec * 1000);
79 continue;
80 }
81 char buf[128];
82 memset(buf, 0, sizeof(buf));
83 if (socket->Read(buf, sizeof(buf)) < 0) {
84 perror("read");
85 continue;
86 }
87 if (strcmp(buf, kWelcomeMessage)) {
88 LOG(ERROR) << "Unexpected message read from daemon: " << buf;
89 break;
90 }
91 return socket.Pass();
92 }
93 return scoped_ptr<Socket>(NULL);
94 }
95
96 // Format of |command|:
97 // <ADB port>:<Device port>[:<Forward to port>:<Forward to address>].
98 bool ParseForwardCommand(const std::string& command,
99 int* adb_port,
100 int* device_port,
101 std::string* forward_to_host,
102 int* forward_to_port) {
103 std::vector<std::string> command_pieces;
104 base::SplitString(command, ':', &command_pieces);
105
106 if (command_pieces.size() < 2 ||
107 !StringToInt(command_pieces[0], adb_port) ||
108 !StringToInt(command_pieces[1], device_port))
53 return false; 109 return false;
54 110
55 if (arg_pieces.size() > 1) { 111 if (command_pieces.size() > 2) {
56 if (!StringToInt(arg_pieces[1], forward_to_port)) 112 if (!StringToInt(command_pieces[2], forward_to_port))
57 return false; 113 return false;
58 if (arg_pieces.size() > 2) 114 if (command_pieces.size() > 3)
59 *forward_to_host = arg_pieces[2]; 115 *forward_to_host = command_pieces[3];
60 } else { 116 } else {
61 *forward_to_port = *device_port; 117 *forward_to_port = *device_port;
62 } 118 }
63 return true; 119 return true;
64 } 120 }
65 121
66 } // namespace 122 bool IsForwardCommandValid(const std::string& command) {
67 123 int adb_port, device_port, forward_to_port;
68 int main(int argc, char** argv) { 124 std::string forward_to_host;
69 printf("Host forwarder to handle incoming connections from Android.\n"); 125 std::vector<std::string> command_pieces;
70 printf("Like 'adb forward' but in the reverse direction\n"); 126 return ParseForwardCommand(
71 127 command, &adb_port, &device_port, &forward_to_host, &forward_to_port);
72 CommandLine command_line(argc, argv); 128 }
73 bool show_help = tools::HasHelpSwitch(command_line); 129
74 std::string adb_port_str = command_line.GetSwitchValueASCII("adb_port"); 130 bool DaemonHandler() {
75 int adb_port = kDefaultAdbPort; 131 LOG(INFO) << "Starting host process daemon (pid=" << getpid() << ")";
76 if (!adb_port_str.empty() && !StringToInt(adb_port_str, &adb_port)) { 132 DCHECK(!g_notifier);
77 printf("Could not parse adb port number: %s\n", adb_port_str.c_str());
78 show_help = true;
79 }
80 if (adb_port <= 0) {
81 printf("Invalid adb port number: %s. Adb port must be a "
82 "postivie integer.\n", adb_port_str.c_str());
83 show_help = true;
84 }
85 CommandLine::StringVector forward_args = command_line.GetArgs();
86 if (show_help || forward_args.empty()) {
87 tools::ShowHelp(
88 argv[0],
89 "[--adb_port=<adb port>] "
90 "<Device port>[:<Forward to port>:<Forward to address>] ...",
91 base::StringPrintf(
92 " <adb port> is the TCP port Adb is configured to forward to."
93 " Default is %d\n"
94 " <Forward to port> default is <Device port>\n"
95 " <Forward to address> default is 127.0.0.1.",
96 kDefaultAdbPort).c_str());
97 return 1;
98 }
99
100 g_notifier = new forwarder2::PipeNotifier(); 133 g_notifier = new forwarder2::PipeNotifier();
134
135 signal(SIGTERM, KillHandler);
136 signal(SIGINT, KillHandler);
137
138 const int notifier_fd = g_notifier->receiver_fd();
139 Socket command_socket;
140 if (!command_socket.BindUnix(kCommandSocketPath, true)) {
141 LOG(ERROR) << "Could not bind Unix Domain Socket";
142 return false;
143 }
144 command_socket.set_exit_notifier_fd(notifier_fd);
145
101 ScopedVector<HostController> controllers; 146 ScopedVector<HostController> controllers;
102 int failed_count = 0; 147 int failed_count = 0;
103 for (size_t i = 0; i < forward_args.size(); ++i) { 148
149 for (;;) {
150 Socket client_socket;
151 if (!command_socket.Accept(&client_socket)) {
152 if (command_socket.exited())
153 return true;
154 PError("Accept()");
155 return false;
156 }
157 if (!client_socket.Write(kWelcomeMessage, sizeof(kWelcomeMessage))) {
158 PError("Write()");
159 continue;
160 }
161 std::string command(128, '\0');
162 const int bytes_read = client_socket.Read(&command[0], command.length());
163 if (bytes_read <= 0) {
164 if (client_socket.exited())
165 break;
166 PError("Read()");
167 ++failed_count;
168 }
169 command.resize(bytes_read);
170 int adb_port = 0;
104 int device_port = 0; 171 int device_port = 0;
105 std::string forward_to_host; 172 std::string forward_to_host;
106 int forward_to_port = 0; 173 int forward_to_port = 0;
107 if (ParseForwardArg(forward_args[i], 174 // Note that the command is checked on the CLI side. In the worst case,
108 &device_port, 175 // Connect() will fail below.
109 &forward_to_host, 176 ParseForwardCommand(
110 &forward_to_port)) { 177 command, &adb_port, &device_port, &forward_to_host, &forward_to_port);
111 scoped_ptr<HostController> host_controller( 178 scoped_ptr<HostController> host_controller(
112 new HostController(device_port, 179 new HostController(device_port,
113 forward_to_host, 180 forward_to_host,
114 forward_to_port, 181 forward_to_port,
115 adb_port, 182 adb_port,
116 g_notifier->receiver_fd())); 183 g_notifier->receiver_fd()));
117 if (!host_controller->Connect()) 184 if (!host_controller->Connect()) {
118 continue;
119 host_controller->Start();
120 // Get the current allocated port.
121 device_port = host_controller->device_port();
122 printf("Forwarding device port %d to host %d:%s\n",
123 device_port, forward_to_port, forward_to_host.c_str());
124
125 controllers.push_back(host_controller.release());
126 } else {
127 printf("Couldn't start forwarder server for port spec: %s\n",
128 forward_args[i].c_str());
129 ++failed_count; 185 ++failed_count;
130 } 186 client_socket.WriteString("ERROR: Connection to device failed.");
131 } 187 continue;
132 188 }
133 // Signal handler must be installed after the for loop above where we start 189 host_controller->Start();
134 // the host_controllers and push_back into the vector. Otherwise a race 190 // Get the current allocated port.
135 // condition may occur. 191 device_port = host_controller->device_port();
136 signal(SIGTERM, KillHandler); 192 LOG(INFO) << "Forwarding device port " << device_port << " to host "
137 signal(SIGINT, KillHandler); 193 << forward_to_host << ":" << forward_to_port;
138 194 if (!client_socket.WriteString(
139 if (controllers.size() == 0) { 195 base::StringPrintf("%d:%d", device_port, forward_to_port))) {
140 printf("No forwarder servers could be started. Exiting.\n"); 196 ++failed_count;
141 return failed_count; 197 continue;
142 } 198 }
143 199 controllers.push_back(host_controller.release());
144 // TODO(felipeg): We should check if the controllers are really alive before 200 }
145 // printing Ready.
146 printf("Host Forwarder Ready.\n");
147 for (int i = 0; i < controllers.size(); ++i) 201 for (int i = 0; i < controllers.size(); ++i)
148 controllers[i]->Join(); 202 controllers[i]->Join();
149 203
204 if (controllers.size() == 0) {
205 LOG(ERROR) << "No forwarder servers could be started. Exiting.";
206 return false;
207 }
208 return true;
209 }
210
211 void PrintUsage(const char* program_name) {
212 LOG(ERROR) << program_name << " adb_port:from_port:to_port:to_host\n"
213 "<adb port> is the TCP port Adb is configured to forward to.";
214 }
215
216 } // namespace
217
218 int main(int argc, char** argv) {
219 if (!CommandLine::Init(argc, argv)) {
220 LOG(ERROR) << "Could not initialize command line";
221 return 1;
222 }
223 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
224 std::string command;
225 int adb_port = 0;
226 if (argc != 2) {
227 PrintUsage(argv[0]);
228 return 1;
229 }
230 if (!strcmp(argv[1], "kill-server")) {
231 command = "kill-server";
232 } else {
233 command = "forward";
234 if (!IsForwardCommandValid(argv[1])) {
235 PrintUsage(argv[0]);
236 return 1;
237 }
238 }
239
240 forwarder2::Daemon daemon(kPIDFilePath);
241
242 if (command == "kill-server")
243 return !daemon.Kill();
244
245 bool is_daemon = false;
246 scoped_ptr<Socket> daemon_socket = ConnectToDaemon(
247 kConnectSingleTry, kConnectNoIdleTime);
248 if (!daemon_socket) {
249 if (!daemon.Spawn(&is_daemon))
250 return 1;
251 }
252
253 if (is_daemon)
254 return !DaemonHandler();
255
256 if (!daemon_socket) {
257 daemon_socket = ConnectToDaemon(5 /* tries */, 100 /* idle msec */);
258 if (!daemon_socket) {
259 LOG(ERROR) << "Could not connect to daemon.";
260 return 1;
261 }
262 }
263
264 // Send the forward command to the daemon.
265 CHECK(daemon_socket->Write(argv[1], strlen(argv[1])));
266 char buf[256];
267 const int bytes_read = daemon_socket->Read(
268 buf, sizeof(buf) - 1 /* leave space for null terminator */);
269 CHECK_GT(bytes_read, 0);
270 DCHECK(bytes_read < sizeof(buf));
271 buf[bytes_read] = 0;
272 base::StringPiece msg(buf, bytes_read);
273 if (msg.starts_with("ERROR")) {
274 LOG(ERROR) << msg;
275 return 1;
276 }
277 printf("%s\n", buf);
150 return 0; 278 return 0;
151 } 279 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698