adb: implement "adb reverse <local> <remote>"

This implements the logical opposite of 'adb forward', i.e.
the ability to reverse network connections from the device
to the host.

This feature is very useful for testing various programs
running on an Android device without root or poking at the
host's routing table.

Options and parameters are exactly the same as those for
'adb forward', except that the direction is reversed.

Examples:

  adb reverse tcp:5000 tcp:6000
    connections to localhost:5000 on the device will be
    forwarded to localhost:6000 on the host.

  adb reverse --no-rebind tcp:5000 tcp:6000
    same as above, but fails if the socket is already
    bound through a previous 'adb reverse tcp:5000 ...'
    command.

  adb reverse --list
    list all active reversed connections for the target
    device. Note: there is no command to list all
    reversed connections for all devices at once.

  adb reverse --remove tcp:5000
    remove any reversed connection on the device from
    localhost:5000

  adb reverse --remove-all
    remove all reversed connections form the current
    device.

Reversed connections are tied to a transport, in other
words, they disappear as soon as a device is disconnected.

Simple testing protocol:

  adb forward tcp:5000 tcp:6000
  adb reverse tcp:6000 tcp:7000
  nc -l localhost 7000

in another terminal:
  echo "Hello" | nc localhost 5000

Will print "Hello" on the first terminal.

Change-Id: I761af790cdb06829b68430afa4145a919fa0e6d5
diff --git a/services.c b/services.c
index 2d3423b..ebe84bb 100644
--- a/services.c
+++ b/services.c
@@ -154,6 +154,17 @@
     adb_close(fd);
 }
 
+void reverse_service(int fd, void* arg)
+{
+    const char* command = arg;
+
+    if (handle_forward_request(command, kTransportAny, NULL, fd) < 0) {
+        sendfailmsg(fd, "not a reverse forwarding command");
+    }
+    free(arg);
+    adb_close(fd);
+}
+
 #endif
 
 static int create_service_thread(void (*func)(int, void *), void *cookie)
@@ -398,6 +409,16 @@
         ret = create_service_thread(restart_tcp_service, (void *) (uintptr_t) port);
     } else if(!strncmp(name, "usb:", 4)) {
         ret = create_service_thread(restart_usb_service, NULL);
+    } else if (!strncmp(name, "reverse:", 8)) {
+        char* cookie = strdup(name + 8);
+        if (cookie == NULL) {
+            ret = -1;
+        } else {
+            ret = create_service_thread(reverse_service, cookie);
+            if (ret < 0) {
+                free(cookie);
+            }
+        }
 #endif
     }
     if (ret >= 0) {