adb: support forwarding TCP port 0.
This CL adds support to forward or reverse TCP port 0 to allow the
system to automatically select an open port. The resolved port number
will be printed to stdout:
$ adb forward tcp:0 tcp:8000
12345
$ adb reverse tcp:0 tcp:9000
23456
This allows testing to be more robust by not hardcoding TCP ports which
may already be in use.
Forwarding port 0 is a host-only change and will work with any device,
but reversing port 0 requires the device to be updated with a new adbd
binary.
This CL also does a little bit of cleanup such as moving the alistener
class out of adb.h, and adds some error checking and additional tests.
Bug: 28051746
Test: python -m unittest discover
Test: adb_test
Test: `adb forward` and `adb reverse` with tcp:0
Change-Id: Icaa87346685b403ab5da7f0e6aa186aa091da572
diff --git a/adb/adb.cpp b/adb/adb.cpp
index 49d2936..11e9c68 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -955,18 +955,25 @@
std::string error;
InstallStatus r;
+ int resolved_tcp_port = 0;
if (kill_forward) {
r = remove_listener(pieces[0].c_str(), transport);
} else {
- r = install_listener(pieces[0], pieces[1].c_str(), transport,
- no_rebind, &error);
+ r = install_listener(pieces[0], pieces[1].c_str(), transport, no_rebind,
+ &resolved_tcp_port, &error);
}
if (r == INSTALL_STATUS_OK) {
#if ADB_HOST
- /* On the host: 1st OKAY is connect, 2nd OKAY is status */
+ // On the host: 1st OKAY is connect, 2nd OKAY is status.
SendOkay(reply_fd);
#endif
SendOkay(reply_fd);
+
+ // If a TCP port was resolved, send the actual port number back.
+ if (resolved_tcp_port != 0) {
+ SendProtocolString(reply_fd, android::base::StringPrintf("%d", resolved_tcp_port));
+ }
+
return 1;
}