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_utils.cpp b/adb/adb_utils.cpp
index 3333fc6..5d4755f 100644
--- a/adb/adb_utils.cpp
+++ b/adb/adb_utils.cpp
@@ -27,6 +27,7 @@
#include <algorithm>
#include <android-base/logging.h>
+#include <android-base/parseint.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
@@ -230,3 +231,26 @@
return true;
}
#endif
+
+bool forward_targets_are_valid(const std::string& source, const std::string& dest,
+ std::string* error) {
+ if (android::base::StartsWith(source, "tcp:")) {
+ // The source port may be 0 to allow the system to select an open port.
+ int port;
+ if (!android::base::ParseInt(&source[4], &port) || port < 0) {
+ *error = android::base::StringPrintf("Invalid source port: '%s'", &source[4]);
+ return false;
+ }
+ }
+
+ if (android::base::StartsWith(dest, "tcp:")) {
+ // The destination port must be > 0.
+ int port;
+ if (!android::base::ParseInt(&dest[4], &port) || port <= 0) {
+ *error = android::base::StringPrintf("Invalid destination port: '%s'", &dest[4]);
+ return false;
+ }
+ }
+
+ return true;
+}