diff options
| author | root <root@dangofactory.local> | 2026-11-23 10:20:49 +0900 |
|---|---|---|
| committer | root <root@dangofactory.local> | 2026-11-23 10:20:49 +0900 |
| commit | a67bdcc65a165d1da57ae6d6fead84a1d2e5b248 (patch) | |
| tree | d0075dacac62d509a09974c1cd2f18ca72cf0e39 /src | |
| download | tethering-app-main.tar.gz tethering-app-main.zip | |
Diffstat (limited to 'src')
| -rw-r--r-- | src/jp/example/tethering/BootReceiver.java | 42 | ||||
| -rw-r--r-- | src/jp/example/tethering/ControlReceiver.java | 55 | ||||
| -rw-r--r-- | src/jp/example/tethering/MainActivity.java | 253 | ||||
| -rw-r--r-- | src/jp/example/tethering/Ps1Exporter.java | 67 | ||||
| -rw-r--r-- | src/jp/example/tethering/RootRelay.java | 80 | ||||
| -rw-r--r-- | src/jp/example/tethering/TetherCli.java | 54 | ||||
| -rw-r--r-- | src/jp/example/tethering/UsbReceiver.java | 48 |
7 files changed, 599 insertions, 0 deletions
diff --git a/src/jp/example/tethering/BootReceiver.java b/src/jp/example/tethering/BootReceiver.java new file mode 100644 index 0000000..169892b --- /dev/null +++ b/src/jp/example/tethering/BootReceiver.java @@ -0,0 +1,42 @@ +package jp.example.tethering; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +/** + * Enables USB tethering after boot when the user has not turned auto mode off. + * The root relay (/kcroot.sh) may still be starting, so wait a little. + */ +public class BootReceiver extends BroadcastReceiver { + @Override + public void onReceive(final Context context, Intent intent) { + SharedPreferences prefs = context.getSharedPreferences("tethering", Context.MODE_PRIVATE); + if (!prefs.getBoolean("auto_usb", true)) { + return; + } + if (prefs.getBoolean("manual_off", false)) { + return; + } + + final PendingResult pending = goAsync(); + new Thread(new Runnable() { + @Override + public void run() { + try { + Thread.sleep(20000); + String apk = context.getPackageCodePath(); + RootRelay.run(RootRelay.acceptMobileData() + + "pm disable-user --user 0 jp.softbank.mb.tetherAuthNfp >/dev/null 2>&1\n" + + "am force-stop jp.softbank.mb.tetherAuthNfp\n" + + "CLASSPATH=" + apk + " /system/bin/app_process /system/bin " + + "jp.example.tethering.TetherCli usb true\n"); + } catch (InterruptedException ignored) { + } finally { + pending.finish(); + } + } + }).start(); + } +} diff --git a/src/jp/example/tethering/ControlReceiver.java b/src/jp/example/tethering/ControlReceiver.java new file mode 100644 index 0000000..b82f6bf --- /dev/null +++ b/src/jp/example/tethering/ControlReceiver.java @@ -0,0 +1,55 @@ +package jp.example.tethering; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +/** + * Remote control from adb / the PC: + * + * adb shell am broadcast -a jp.example.tethering.USB_ON + * adb shell am broadcast -a jp.example.tethering.USB_OFF + * + * The broadcast sets manual_off so the USB receiver does not immediately + * turn tethering back on after a manual OFF. + */ +public class ControlReceiver extends BroadcastReceiver { + public static final String ACTION_ON = "jp.example.tethering.USB_ON"; + public static final String ACTION_OFF = "jp.example.tethering.USB_OFF"; + public static final String ACTION_EXPORT = "jp.example.tethering.EXPORT_PS1"; + public static final String ACTION_EXPORT_SCRIPTS = "jp.example.tethering.EXPORT_SCRIPTS"; + + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + if (ACTION_EXPORT.equals(action) || ACTION_EXPORT_SCRIPTS.equals(action)) { + try { + Ps1Exporter.exportAll(context); + } catch (Exception e) { + android.util.Log.e("TetheringApp", "export failed", e); + } + return; + } + + boolean enable = ACTION_ON.equals(action); + if (!enable && !ACTION_OFF.equals(action)) { + return; + } + + SharedPreferences prefs = context.getSharedPreferences("tethering", Context.MODE_PRIVATE); + prefs.edit().putBoolean("manual_off", !enable).apply(); + + StringBuilder cmd = new StringBuilder(); + if (enable) { + cmd.append(RootRelay.acceptMobileData()); + cmd.append("pm disable-user --user 0 jp.softbank.mb.tetherAuthNfp >/dev/null 2>&1\n"); + cmd.append("am force-stop jp.softbank.mb.tetherAuthNfp\n"); + } + cmd.append("CLASSPATH=").append(context.getPackageCodePath()) + .append(" /system/bin/app_process /system/bin ") + .append("jp.example.tethering.TetherCli usb ") + .append(enable).append("\n"); + RootRelay.run(cmd.toString()); + } +} diff --git a/src/jp/example/tethering/MainActivity.java b/src/jp/example/tethering/MainActivity.java new file mode 100644 index 0000000..4bf9a18 --- /dev/null +++ b/src/jp/example/tethering/MainActivity.java @@ -0,0 +1,253 @@ +package jp.example.tethering; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.SharedPreferences; +import android.graphics.Color; +import java.net.NetworkInterface; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; +import android.widget.Toast; + +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InterfaceAddress; + +public class MainActivity extends Activity { + private static final String PREFS = "tethering"; + private static final String KEY_AUTO = "auto_usb"; + private static final String KEY_MANUAL_OFF = "manual_off"; + + private TextView status; + private Button toggle; + private CheckBox auto; + private SharedPreferences prefs; + private final Handler handler = new Handler(Looper.getMainLooper()); + private boolean lastOn = false; + private boolean busy = false; + + private final Runnable refresh = new Runnable() { + @Override + public void run() { + refreshStatus(); + handler.postDelayed(this, 3000); + } + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + prefs = getSharedPreferences(PREFS, MODE_PRIVATE); + + ScrollView scroll = new ScrollView(this); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + int p = dp(20); + root.setPadding(p, p, p, p); + scroll.addView(root); + + TextView title = new TextView(this); + title.setText("テザリング"); + title.setTextSize(28); + title.setGravity(Gravity.CENTER_HORIZONTAL); + root.addView(title); + + status = new TextView(this); + status.setTextSize(18); + status.setPadding(0, dp(16), 0, dp(16)); + status.setGravity(Gravity.CENTER_HORIZONTAL); + root.addView(status); + + toggle = new Button(this); + toggle.setTextSize(22); + toggle.setFocusable(true); + toggle.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + setUsb(!lastOn); + } + }); + root.addView(toggle, new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, dp(72))); + + auto = new CheckBox(this); + auto.setText("USB接続時に自動でON"); + auto.setTextSize(16); + auto.setFocusable(true); + auto.setChecked(prefs.getBoolean(KEY_AUTO, true)); + auto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + prefs.edit().putBoolean(KEY_AUTO, isChecked).apply(); + if (isChecked) { + prefs.edit().putBoolean(KEY_MANUAL_OFF, false).apply(); + } + } + }); + root.addView(auto); + + Button export = new Button(this); + export.setText("PC用スクリプトを書き出す"); + export.setTextSize(16); + export.setFocusable(true); + export.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + exportScripts(); + } + }); + root.addView(export); + + TextView info = new TextView(this); + info.setTextSize(14); + info.setPadding(0, dp(20), 0, 0); + info.setText("PC側は初回だけ同梱スクリプトを管理者で実行してください。\n" + + "以後はUSBを挿してアプリがONになれば、PCはDHCPで自動接続します。\n" + + "PowerShell / Linux / FreeBSD 用は\n" + + "「PC用スクリプトを書き出す」で /data/local/tmp に取り出せます。\n\n" + + "rootサービス: " + (RootRelay.available() ? "OK" : "見つかりません")); + root.addView(info); + + setContentView(scroll); + toggle.requestFocus(); + RootRelay.run(RootRelay.acceptMobileData()); + refreshStatus(); + + if (prefs.getBoolean(KEY_AUTO, true) && !prefs.getBoolean(KEY_MANUAL_OFF, false)) { + handler.postDelayed(new Runnable() { + @Override + public void run() { + setUsb(true); + } + }, 1200); + } + } + + private int dp(int v) { + return (int) (v * getResources().getDisplayMetrics().density + 0.5f); + } + + private void exportScripts() { + try { + String dir = Ps1Exporter.exportAll(this); + new AlertDialog.Builder(this) + .setTitle("PC用スクリプトを書き出しました") + .setMessage("スマホ内: " + dir + "\n" + + "pc-autoconnect.ps1\n" + + "pc-autoconnect.sh\n" + + "pc-autoconnect-linux.sh\n" + + "pc-autoconnect-freebsd.sh\n\n" + + "PC側で:\n" + + "adb pull " + dir + "pc-autoconnect.ps1 R:\\Projects\\Tethering-pc\\\n" + + "adb pull " + dir + "pc-autoconnect.sh R:\\Projects\\Tethering-pc\\\n" + + "adb pull " + dir + "pc-autoconnect-linux.sh R:\\Projects\\Tethering-pc\\\n" + + "adb pull " + dir + "pc-autoconnect-freebsd.sh R:\\Projects\\Tethering-pc\\") + .setPositiveButton("OK", null) + .show(); + } catch (Exception e) { + Toast.makeText(this, "書き出し失敗: " + e.getMessage(), Toast.LENGTH_LONG).show(); + } + } + + private void setUsb(boolean enable) { + if (busy) { + return; + } + busy = true; + prefs.edit().putBoolean(KEY_MANUAL_OFF, !enable).apply(); + status.setText(enable ? "ON にしています..." : "OFF にしています..."); + + StringBuilder cmd = new StringBuilder(); + if (enable) { + cmd.append(RootRelay.acceptMobileData()); + // SoftBank's tetherAuthAPLNfp stops tethering again unless disabled. + cmd.append("pm disable-user --user 0 jp.softbank.mb.tetherAuthNfp >/dev/null 2>&1\n"); + cmd.append("am force-stop jp.softbank.mb.tetherAuthNfp\n"); + } + cmd.append("CLASSPATH=").append(getPackageCodePath()) + .append(" /system/bin/app_process /system/bin ") + .append("jp.example.tethering.TetherCli usb ") + .append(enable).append("\n"); + + if (!RootRelay.run(cmd.toString())) { + status.setText("rootサービスに書き込めません"); + busy = false; + return; + } + + handler.postDelayed(new Runnable() { + @Override + public void run() { + busy = false; + refreshStatus(); + } + }, 2500); + } + + private void refreshStatus() { + boolean on = isUsbTethered(); + lastOn = on; + String ip = usbIp(); + android.util.Log.d("TetheringApp", "refreshStatus on=" + on + " ip=" + ip); + toggle.setText(on ? "USBテザリングをOFF" : "USBテザリングをON"); + status.setText(on + ? "USBテザリング: ON" + (ip != null ? "\n" + ip : "") + : "USBテザリング: OFF"); + status.setTextColor(on ? Color.rgb(0, 128, 0) : Color.rgb(180, 0, 0)); + } + + private boolean isUsbTethered() { + try { + NetworkInterface ni = NetworkInterface.getByName("usb0"); + if (ni == null || !ni.isUp()) { + return false; + } + for (InterfaceAddress ia : ni.getInterfaceAddresses()) { + if (ia.getAddress() instanceof Inet4Address) { + return true; + } + } + } catch (Exception ignored) { + } + return false; + } + + private String usbIp() { + try { + NetworkInterface ni = NetworkInterface.getByName("usb0"); + if (ni == null) { + return null; + } + for (InterfaceAddress ia : ni.getInterfaceAddresses()) { + InetAddress a = ia.getAddress(); + if (a instanceof Inet4Address) { + return a.getHostAddress() + "/" + ia.getNetworkPrefixLength(); + } + } + } catch (Exception ignored) { + } + return null; + } + + @Override + protected void onResume() { + super.onResume(); + handler.post(refresh); + } + + @Override + protected void onPause() { + handler.removeCallbacks(refresh); + super.onPause(); + } +} diff --git a/src/jp/example/tethering/Ps1Exporter.java b/src/jp/example/tethering/Ps1Exporter.java new file mode 100644 index 0000000..6eb5693 --- /dev/null +++ b/src/jp/example/tethering/Ps1Exporter.java @@ -0,0 +1,67 @@ +package jp.example.tethering; + +import android.content.Context; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; + +/** + * Writes the bundled host-side scripts to /data/local/tmp via the root relay. + * + * pc-autoconnect.ps1 Windows / PowerShell + * pc-autoconnect.sh OS dispatcher + * pc-autoconnect-linux.sh Linux + * pc-autoconnect-freebsd.sh FreeBSD + * + * The PC can then fetch them with adb pull. + */ +public final class Ps1Exporter { + public static final String REMOTE_DIR = "/data/local/tmp/"; + + private Ps1Exporter() { + } + + public static String exportAll(Context context) throws Exception { + StringBuilder cmd = new StringBuilder(); + appendAsset(cmd, context, "pc-autoconnect.ps1", + REMOTE_DIR + "pc-autoconnect.ps1", "TETHER_PS1_EOF"); + appendAsset(cmd, context, "pc-autoconnect.sh", + REMOTE_DIR + "pc-autoconnect.sh", "TETHER_SH_EOF"); + appendAsset(cmd, context, "pc-autoconnect-linux.sh", + REMOTE_DIR + "pc-autoconnect-linux.sh", "TETHER_LINUX_EOF"); + appendAsset(cmd, context, "pc-autoconnect-freebsd.sh", + REMOTE_DIR + "pc-autoconnect-freebsd.sh", "TETHER_FREEBSD_EOF"); + + cmd.append("chmod 644 ").append(REMOTE_DIR).append("pc-autoconnect.ps1\n"); + cmd.append("chmod 755 ") + .append(REMOTE_DIR).append("pc-autoconnect.sh ") + .append(REMOTE_DIR).append("pc-autoconnect-linux.sh ") + .append(REMOTE_DIR).append("pc-autoconnect-freebsd.sh\n"); + cmd.append("ls -l ").append(REMOTE_DIR).append("pc-autoconnect*\n"); + + if (!RootRelay.run(cmd.toString())) { + throw new Exception("root service (/data/local/tmp/rin) is not writable"); + } + return REMOTE_DIR; + } + + private static void appendAsset(StringBuilder cmd, Context context, String asset, + String remote, String marker) throws Exception { + InputStream in = context.getAssets().open(asset); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int n; + while ((n = in.read(buf)) > 0) { + bos.write(buf, 0, n); + } + in.close(); + + String text = new String(bos.toByteArray(), "UTF-8"); + cmd.append("cat > ").append(remote).append(" <<'").append(marker).append("'\n"); + cmd.append(text); + if (!text.endsWith("\n")) { + cmd.append('\n'); + } + cmd.append(marker).append('\n'); + } +} diff --git a/src/jp/example/tethering/RootRelay.java b/src/jp/example/tethering/RootRelay.java new file mode 100644 index 0000000..4219a6b --- /dev/null +++ b/src/jp/example/tethering/RootRelay.java @@ -0,0 +1,80 @@ +package jp.example.tethering; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.RandomAccessFile; + +/** + * The phone already runs /kcroot.sh as root. It watches /data/local/tmp/rin, + * executes its contents as root and appends stdout/stderr to /data/local/tmp/rout. + * Both files are world-writable/readable, so this app can use that service + * without needing root itself. + */ +public final class RootRelay { + public static final String RIN = "/data/local/tmp/rin"; + public static final String ROUT = "/data/local/tmp/rout"; + + private RootRelay() { + } + + public static boolean available() { + File f = new File(RIN); + return f.exists() && f.canWrite(); + } + + /** + * Kyocera's KcAlertMobiledataActivity shows a mobile-data confirmation for + * app UIDs that are not accepted. Mark our own UID as accepted so the + * dialog does not cover the app after a reinstall / UID change. + */ + public static String acceptMobileData() { + int uid = android.os.Process.myUid(); + return "content query --uri content://settings/accept_mobile_data | grep -q \"uid=" + uid + ",\" || " + + "content insert --uri content://settings/accept_mobile_data --bind uid:i:" + uid + + " --bind status:i:1 >/dev/null 2>&1\n" + + "content update --uri content://settings/accept_mobile_data --bind status:i:1 --where \"uid=" + + uid + "\" >/dev/null 2>&1\n" + + "pm disable --user 0 android/com.android.internal.app.KcAlertMobiledataActivity >/dev/null 2>&1\n"; + } + + public static boolean run(String command) { + FileOutputStream out = null; + try { + out = new FileOutputStream(RIN, false); + out.write((command + "\n").getBytes("UTF-8")); + out.flush(); + return true; + } catch (Exception e) { + return false; + } finally { + if (out != null) { + try { + out.close(); + } catch (Exception ignored) { + } + } + } + } + + public static String tail() { + RandomAccessFile f = null; + try { + f = new RandomAccessFile(ROUT, "r"); + long len = f.length(); + int n = (int) Math.min(len, 16384); + f.seek(len - n); + byte[] buf = new byte[n]; + f.readFully(buf); + return new String(buf, "UTF-8"); + } catch (Exception e) { + return ""; + } finally { + if (f != null) { + try { + f.close(); + } catch (Exception ignored) { + } + } + } + } +} diff --git a/src/jp/example/tethering/TetherCli.java b/src/jp/example/tethering/TetherCli.java new file mode 100644 index 0000000..4cf3336 --- /dev/null +++ b/src/jp/example/tethering/TetherCli.java @@ -0,0 +1,54 @@ +package jp.example.tethering; + +import android.content.Context; +import android.os.Looper; + +import java.lang.reflect.Method; + +/** + * Runs as a separate root process via: + * + * CLASSPATH=<this apk> /system/bin/app_process /system/bin \ + * jp.example.tethering.TetherCli usb true + * + * A normal app cannot call setUsbTethering() (it needs TETHER_PRIVILEGED), + * but uid 0 can. + */ +public class TetherCli { + public static void main(String[] args) { + String mode = args.length > 0 ? args[0] : "usb"; + boolean enable = args.length < 2 || "true".equalsIgnoreCase(args[1]); + try { + Looper.prepareMainLooper(); + Class<?> at = Class.forName("android.app.ActivityThread"); + Object thread = at.getMethod("systemMain").invoke(null); + Context ctx = (Context) at.getMethod("getSystemContext").invoke(thread); + + if ("usb".equals(mode)) { + Object cm = ctx.getSystemService(Context.CONNECTIVITY_SERVICE); + Method m = cm.getClass().getMethod("setUsbTethering", boolean.class); + m.invoke(cm, enable); + System.out.println("OK usb " + enable); + } else if ("wifi".equals(mode)) { + Object wm = ctx.getSystemService(Context.WIFI_SERVICE); + Method m = wm.getClass().getMethod("setWifiApEnabled", + android.net.wifi.WifiConfiguration.class, boolean.class); + m.invoke(wm, null, enable); + System.out.println("OK wifi " + enable); + } else if ("bt".equals(mode)) { + Object cm = ctx.getSystemService(Context.CONNECTIVITY_SERVICE); + Method m = cm.getClass().getMethod("setBluetoothTethering", boolean.class); + m.invoke(cm, enable); + System.out.println("OK bt " + enable); + } else { + System.out.println("unknown mode " + mode); + } + } catch (Throwable t) { + t.printStackTrace(); + } + try { + Thread.sleep(1200); + } catch (InterruptedException ignored) { + } + } +} diff --git a/src/jp/example/tethering/UsbReceiver.java b/src/jp/example/tethering/UsbReceiver.java new file mode 100644 index 0000000..38a2cd3 --- /dev/null +++ b/src/jp/example/tethering/UsbReceiver.java @@ -0,0 +1,48 @@ +package jp.example.tethering; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +/** + * Android sends android.hardware.usb.action.USB_STATE with EXTRA_CONNECTED + * when the USB cable is plugged/unplugged. Start tethering automatically. + */ +public class UsbReceiver extends BroadcastReceiver { + @Override + public void onReceive(final Context context, Intent intent) { + boolean connected = intent.getBooleanExtra("connected", false); + if (!connected) { + return; + } + + SharedPreferences prefs = context.getSharedPreferences("tethering", Context.MODE_PRIVATE); + if (!prefs.getBoolean("auto_usb", true)) { + return; + } + if (prefs.getBoolean("manual_off", false)) { + return; + } + + final PendingResult pending = goAsync(); + new Thread(new Runnable() { + @Override + public void run() { + try { + // Give the RNDIS gadget a moment to appear. + Thread.sleep(2500); + String apk = context.getPackageCodePath(); + RootRelay.run(RootRelay.acceptMobileData() + + "pm disable-user --user 0 jp.softbank.mb.tetherAuthNfp >/dev/null 2>&1\n" + + "am force-stop jp.softbank.mb.tetherAuthNfp\n" + + "CLASSPATH=" + apk + " /system/bin/app_process /system/bin " + + "jp.example.tethering.TetherCli usb true\n"); + } catch (InterruptedException ignored) { + } finally { + pending.finish(); + } + } + }).start(); + } +} |
