Skip to content

Commit

Permalink
Merge pull request #210 from jessedusty:add_port_option
Browse files Browse the repository at this point in the history
Add port option to allow multiple instances of the gnirehtet relay to
run
  • Loading branch information
rom1v committed Nov 13, 2019
2 parents 53c38c5 + a84a4d9 commit e87f7e6
Show file tree
Hide file tree
Showing 6 changed files with 157 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,18 @@
/**
* Simple specific command-line arguments parser.
*/
@SuppressWarnings("checkstyle:MagicNumber")
public class CommandLineArguments {

public static final int PARAM_NONE = 0;
public static final int PARAM_SERIAL = 1;
public static final int PARAM_DNS_SERVER = 1 << 1;
public static final int PARAM_ROUTES = 1 << 2;
public static final int PARAM_PORT = 1 << 3;

public static final int DEFAULT_PORT = 31416;

private int port;
private String serial;
private String dnsServers;
private String routes;
Expand All @@ -52,12 +57,27 @@ public static CommandLineArguments parse(int acceptedParameters, String... args)
}
arguments.routes = args[i + 1];
++i; // consume the -r parameter
} else if ((acceptedParameters & PARAM_PORT) != 0 && "-p".equals(arg)) {
if (arguments.port != 0) {
throw new IllegalArgumentException("Port already set");
}
if (i == args.length - 1) {
throw new IllegalArgumentException("Missing -p parameter");
}
arguments.port = Integer.parseInt(args[i + 1]);
if (arguments.port <= 0 || arguments.port >= 65536) {
throw new IllegalArgumentException("Invalid port: " + arguments.port);
}
++i;
} else if ((acceptedParameters & PARAM_SERIAL) != 0 && arguments.serial == null) {
arguments.serial = arg;
} else {
throw new IllegalArgumentException("Unexpected argument: \"" + arg + "\"");
}
}
if (arguments.port == 0) {
arguments.port = DEFAULT_PORT;
}
return arguments;
}

Expand All @@ -72,4 +92,8 @@ public String getDnsServers() {
public String getRoutes() {
return routes;
}

public int getPort() {
return port;
}
}
74 changes: 41 additions & 33 deletions relay-java/src/main/java/com/genymobile/gnirehtet/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ void execute(CommandLineArguments args) throws Exception {
cmdReinstall(args.getSerial());
}
},
RUN("run", CommandLineArguments.PARAM_SERIAL | CommandLineArguments.PARAM_DNS_SERVER | CommandLineArguments.PARAM_ROUTES) {
RUN("run", CommandLineArguments.PARAM_SERIAL | CommandLineArguments.PARAM_DNS_SERVER | CommandLineArguments.PARAM_ROUTES
| CommandLineArguments.PARAM_PORT) {
@Override
String getDescription() {
return "Enable reverse tethering for exactly one device:\n"
Expand All @@ -88,10 +89,10 @@ String getDescription() {

@Override
void execute(CommandLineArguments args) throws Exception {
cmdRun(args.getSerial(), args.getDnsServers(), args.getRoutes());
cmdRun(args.getSerial(), args.getDnsServers(), args.getRoutes(), args.getPort());
}
},
AUTORUN("autorun", CommandLineArguments.PARAM_DNS_SERVER | CommandLineArguments.PARAM_ROUTES) {
AUTORUN("autorun", CommandLineArguments.PARAM_DNS_SERVER | CommandLineArguments.PARAM_ROUTES | CommandLineArguments.PARAM_PORT) {
@Override
String getDescription() {
return "Enable reverse tethering for all devices:\n"
Expand All @@ -101,10 +102,11 @@ String getDescription() {

@Override
void execute(CommandLineArguments args) throws Exception {
cmdAutorun(args.getDnsServers(), args.getRoutes());
cmdAutorun(args.getDnsServers(), args.getRoutes(), args.getPort());
}
},
START("start", CommandLineArguments.PARAM_SERIAL | CommandLineArguments.PARAM_DNS_SERVER | CommandLineArguments.PARAM_ROUTES) {
START("start", CommandLineArguments.PARAM_SERIAL | CommandLineArguments.PARAM_DNS_SERVER | CommandLineArguments.PARAM_ROUTES
| CommandLineArguments.PARAM_PORT) {
@Override
String getDescription() {
return "Start a client on the Android device and exit.\n"
Expand All @@ -113,6 +115,8 @@ String getDescription() {
+ "If -d is given, then make the Android device use the specified\n"
+ "DNS server(s). Otherwise, use 8.8.8.8 (Google public DNS).\n"
+ "If -r is given, then only reverse tether the specified routes.\n"
+ "If -p is given, then make the relay server listen on the specified\n"
+ "port. Otherwise, use port 31416.\n"
+ "Otherwise, use 0.0.0.0/0 (redirect the whole traffic).\n"
+ "If the client is already started, then do nothing, and ignore\n"
+ "the other parameters.\n"
Expand All @@ -121,10 +125,10 @@ String getDescription() {

@Override
void execute(CommandLineArguments args) throws Exception {
cmdStart(args.getSerial(), args.getDnsServers(), args.getRoutes());
cmdStart(args.getSerial(), args.getDnsServers(), args.getRoutes(), args.getPort());
}
},
AUTOSTART("autostart", CommandLineArguments.PARAM_DNS_SERVER | CommandLineArguments.PARAM_ROUTES) {
AUTOSTART("autostart", CommandLineArguments.PARAM_DNS_SERVER | CommandLineArguments.PARAM_ROUTES | CommandLineArguments.PARAM_PORT) {
@Override
String getDescription() {
return "Listen for device connexions and start a client on every detected\n"
Expand All @@ -135,7 +139,7 @@ String getDescription() {

@Override
void execute(CommandLineArguments args) throws Exception {
cmdAutostart(args.getDnsServers(), args.getRoutes());
cmdAutostart(args.getDnsServers(), args.getRoutes(), args.getPort());
}
},
STOP("stop", CommandLineArguments.PARAM_SERIAL) {
Expand All @@ -151,18 +155,19 @@ void execute(CommandLineArguments args) throws Exception {
cmdStop(args.getSerial());
}
},
RESTART("restart", CommandLineArguments.PARAM_SERIAL | CommandLineArguments.PARAM_DNS_SERVER | CommandLineArguments.PARAM_ROUTES) {
RESTART("restart", CommandLineArguments.PARAM_SERIAL | CommandLineArguments.PARAM_DNS_SERVER | CommandLineArguments.PARAM_ROUTES
| CommandLineArguments.PARAM_PORT) {
@Override
String getDescription() {
return "Stop then start.";
}

@Override
void execute(CommandLineArguments args) throws Exception {
cmdRestart(args.getSerial(), args.getDnsServers(), args.getRoutes());
cmdRestart(args.getSerial(), args.getDnsServers(), args.getRoutes(), args.getPort());
}
},
TUNNEL("tunnel", CommandLineArguments.PARAM_SERIAL) {
TUNNEL("tunnel", CommandLineArguments.PARAM_SERIAL | CommandLineArguments.PARAM_PORT) {
@Override
String getDescription() {
return "Set up the 'adb reverse' tunnel.\n"
Expand All @@ -173,18 +178,18 @@ String getDescription() {

@Override
void execute(CommandLineArguments args) throws Exception {
cmdTunnel(args.getSerial());
cmdTunnel(args.getSerial(), args.getPort());
}
},
RELAY("relay", CommandLineArguments.PARAM_NONE) {
RELAY("relay", CommandLineArguments.PARAM_PORT) {
@Override
String getDescription() {
return "Start the relay server in the current terminal.";
}

@Override
void execute(CommandLineArguments args) throws Exception {
cmdRelay();
cmdRelay(args.getPort());
}
};

Expand Down Expand Up @@ -216,9 +221,9 @@ private static void cmdReinstall(String serial) throws InterruptedException, IOE
cmdInstall(serial);
}

private static void cmdRun(String serial, String dnsServers, String routes) throws InterruptedException, IOException, CommandExecutionException {
private static void cmdRun(String serial, String dnsServers, String routes, int port) throws IOException {
// start in parallel so that the relay server is ready when the client connects
asyncStart(serial, dnsServers, routes);
asyncStart(serial, dnsServers, routes, port);

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
// executed on Ctrl+C
Expand All @@ -229,23 +234,23 @@ private static void cmdRun(String serial, String dnsServers, String routes) thro
}
}));

cmdRelay();
cmdRelay(port);
}

private static void cmdAutorun(final String dnsServers, final String routes) throws InterruptedException, IOException, CommandExecutionException {
private static void cmdAutorun(final String dnsServers, final String routes, int port) throws IOException {
new Thread(() -> {
try {
cmdAutostart(dnsServers, routes);
cmdAutostart(dnsServers, routes, port);
} catch (Exception e) {
Log.e(TAG, "Cannot auto start clients", e);
}
}).start();

cmdRelay();
cmdRelay(port);
}

@SuppressWarnings("checkstyle:MagicNumber")
private static void cmdStart(String serial, String dnsServers, String routes) throws InterruptedException, IOException,
private static void cmdStart(String serial, String dnsServers, String routes, int port) throws InterruptedException, IOException,
CommandExecutionException {
if (mustInstallClient(serial)) {
cmdInstall(serial);
Expand All @@ -254,7 +259,7 @@ private static void cmdStart(String serial, String dnsServers, String routes) th
}

Log.i(TAG, "Starting client...");
cmdTunnel(serial);
cmdTunnel(serial, port);

List<String> cmd = new ArrayList<>();
Collections.addAll(cmd, "shell", "am", "start", "-a", "com.genymobile.gnirehtet.START", "-n",
Expand All @@ -268,9 +273,9 @@ private static void cmdStart(String serial, String dnsServers, String routes) th
execAdb(serial, cmd);
}

private static void cmdAutostart(final String dnsServers, final String routes) {
private static void cmdAutostart(final String dnsServers, final String routes, int port) {
AdbMonitor adbMonitor = new AdbMonitor((serial) -> {
asyncStart(serial, dnsServers, routes);
asyncStart(serial, dnsServers, routes, port);
});
adbMonitor.monitor();
}
Expand All @@ -281,25 +286,25 @@ private static void cmdStop(String serial) throws InterruptedException, IOExcept
"com.genymobile.gnirehtet/.GnirehtetActivity");
}

private static void cmdRestart(String serial, String dnsServers, String routes) throws InterruptedException, IOException,
private static void cmdRestart(String serial, String dnsServers, String routes, int port) throws InterruptedException, IOException,
CommandExecutionException {
cmdStop(serial);
cmdStart(serial, dnsServers, routes);
cmdStart(serial, dnsServers, routes, port);
}

private static void cmdTunnel(String serial) throws InterruptedException, IOException, CommandExecutionException {
execAdb(serial, "reverse", "localabstract:gnirehtet", "tcp:31416");
private static void cmdTunnel(String serial, int port) throws InterruptedException, IOException, CommandExecutionException {
execAdb(serial, "reverse", "localabstract:gnirehtet", "tcp:" + port);
}

private static void cmdRelay() throws IOException {
Log.i(TAG, "Starting relay server...");
new Relay().run();
private static void cmdRelay(int port) throws IOException {
Log.i(TAG, "Starting relay server on port " + port + "...");
new Relay(port).run();
}

private static void asyncStart(String serial, String dnsServers, String routes) {
private static void asyncStart(String serial, String dnsServers, String routes, int port) {
new Thread(() -> {
try {
cmdStart(serial, dnsServers, routes);
cmdStart(serial, dnsServers, routes, port);
} catch (Exception e) {
Log.e(TAG, "Cannot start client", e);
}
Expand Down Expand Up @@ -387,6 +392,9 @@ private static void appendCommandUsage(StringBuilder builder, Command command) {
if ((command.acceptedParameters & CommandLineArguments.PARAM_DNS_SERVER) != 0) {
builder.append(" [-d DNS[,DNS2,...]]");
}
if ((command.acceptedParameters & CommandLineArguments.PARAM_PORT) != 0) {
builder.append(" [-p PORT]");
}
if ((command.acceptedParameters & CommandLineArguments.PARAM_ROUTES) != 0) {
builder.append(" [-r ROUTE[,ROUTE2,...]]");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,10 @@ public class Relay {

private static final String TAG = Relay.class.getSimpleName();

private static final int DEFAULT_PORT = 31416;
private static final int CLEANING_INTERVAL = 60 * 1000;

private final int port;

public Relay() {
this(DEFAULT_PORT);
}

public Relay(int port) {
this.port = port;
}
Expand Down
25 changes: 25 additions & 0 deletions relay-rust/src/cli_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,15 @@ pub const PARAM_NONE: u8 = 0;
pub const PARAM_SERIAL: u8 = 1;
pub const PARAM_DNS_SERVERS: u8 = 1 << 1;
pub const PARAM_ROUTES: u8 = 1 << 2;
pub const PARAM_PORT: u8 = 1 << 3;

pub const DEFAULT_PORT: u16 = 31416;

pub struct CommandLineArguments {
serial: Option<String>,
dns_servers: Option<String>,
routes: Option<String>,
port: u16,
}

impl CommandLineArguments {
Expand All @@ -31,6 +35,7 @@ impl CommandLineArguments {
let mut serial = None;
let mut dns_servers = None;
let mut routes = None;
let mut port = 0;

let mut iter = args.into_iter();
while let Some(arg) = iter.next() {
Expand All @@ -53,16 +58,32 @@ impl CommandLineArguments {
} else {
return Err(String::from("Missing -r parameter"));
}
} else if (accepted_parameters & PARAM_PORT) != 0 && "-p" == arg {
if port != 0 {
return Err(String::from("Port already set"));
}
if let Some(value) = iter.next() {
port = value.into().parse().unwrap();
if port == 0 {
return Err(String::from("Invalid port: 0"));
}
} else {
return Err(String::from("Missing -p parameter"));
}
} else if (accepted_parameters & PARAM_SERIAL) != 0 && serial.is_none() {
serial = Some(arg);
} else {
return Err(format!("Unexpected argument: \"{}\"", arg));
}
}
if port == 0 {
port = DEFAULT_PORT;
}
Ok(Self {
serial,
dns_servers,
routes,
port,
})
}

Expand All @@ -77,6 +98,10 @@ impl CommandLineArguments {
pub fn routes(&self) -> Option<&str> {
self.routes.as_ref().map(String::as_str)
}

pub fn port(&self) -> u16 {
self.port
}
}

#[cfg(test)]
Expand Down
5 changes: 2 additions & 3 deletions relay-rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ pub use crate::relay::byte_buffer;
use crate::relay::Relay;
use std::io;

pub fn relay() -> io::Result<()> {
const PORT: u16 = 31416;
Relay::new(PORT).run()
pub fn relay(port: u16) -> io::Result<()> {
Relay::new(port).run()
}
Loading

0 comments on commit e87f7e6

Please sign in to comment.