summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorroot <root@dangofactory.local>2026-11-23 10:20:49 +0900
committerroot <root@dangofactory.local>2026-11-23 10:20:49 +0900
commita67bdcc65a165d1da57ae6d6fead84a1d2e5b248 (patch)
treed0075dacac62d509a09974c1cd2f18ca72cf0e39
downloadtethering-app-main.tar.gz
tethering-app-main.zip
Import tethering-appHEADmain
-rw-r--r--.gitignore3
-rw-r--r--AndroidManifest.xml55
-rw-r--r--README.md159
-rw-r--r--assets/pc-autoconnect-freebsd.sh97
-rw-r--r--assets/pc-autoconnect-linux.sh114
-rw-r--r--assets/pc-autoconnect.ps1115
-rw-r--r--assets/pc-autoconnect.sh22
-rw-r--r--build.ps164
-rw-r--r--pc/pc-autoconnect-freebsd.sh97
-rw-r--r--pc/pc-autoconnect-linux.sh114
-rw-r--r--pc/pc-autoconnect.bat5
-rw-r--r--pc/pc-autoconnect.ps1115
-rw-r--r--pc/pc-autoconnect.sh22
-rw-r--r--res/values/strings.xml4
-rw-r--r--src/jp/example/tethering/BootReceiver.java42
-rw-r--r--src/jp/example/tethering/ControlReceiver.java55
-rw-r--r--src/jp/example/tethering/MainActivity.java253
-rw-r--r--src/jp/example/tethering/Ps1Exporter.java67
-rw-r--r--src/jp/example/tethering/RootRelay.java80
-rw-r--r--src/jp/example/tethering/TetherCli.java54
-rw-r--r--src/jp/example/tethering/UsbReceiver.java48
21 files changed, 1585 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d1f1fdb
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+build/
+*.keystore
+*.jks
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
new file mode 100644
index 0000000..a9b7249
--- /dev/null
+++ b/AndroidManifest.xml
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="jp.example.tethering"
+ android:versionCode="1"
+ android:versionName="1.0">
+
+ <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="22" />
+
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.INTERNET" />
+
+ <application
+ android:label="@string/app_name"
+ android:allowBackup="false"
+ android:theme="@android:style/Theme.Material.Light">
+
+ <activity
+ android:name=".MainActivity"
+ android:label="@string/app_name"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+
+ <receiver
+ android:name=".BootReceiver"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.intent.action.BOOT_COMPLETED" />
+ </intent-filter>
+ </receiver>
+
+ <receiver
+ android:name=".UsbReceiver"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.hardware.usb.action.USB_STATE" />
+ </intent-filter>
+ </receiver>
+
+ <receiver
+ android:name=".ControlReceiver"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="jp.example.tethering.USB_ON" />
+ <action android:name="jp.example.tethering.USB_OFF" />
+ <action android:name="jp.example.tethering.EXPORT_PS1" />
+ <action android:name="jp.example.tethering.EXPORT_SCRIPTS" />
+ </intent-filter>
+ </receiver>
+ </application>
+</manifest>
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..1c30698
--- /dev/null
+++ b/README.md
@@ -0,0 +1,159 @@
+# テザリング (701KC)
+
+KYOCERA 701KC (Android 5.1.1) 用の USB テザリング ON/OFF アプリです。
+アプリ名はそのまま **「テザリング」**、パッケージは `jp.example.tethering` です。
+
+## できること
+
+- USB テザリングの ON / OFF
+- アプリ起動時に自動で ON
+- USB を挿したときに自動で ON
+- 端末起動時に自動で ON(20 秒後)
+- `adb` からの遠隔操作
+ - `adb shell am broadcast -a jp.example.tethering.USB_ON`
+ - `adb shell am broadcast -a jp.example.tethering.USB_OFF`
+- PC 用スクリプトを同梱
+ - `pc-autoconnect.ps1` … Windows / PowerShell
+ - `pc-autoconnect.sh` … Linux / FreeBSD ディスパッチャ
+ - `pc-autoconnect-linux.sh` … Linux
+ - `pc-autoconnect-freebsd.sh` … FreeBSD
+ - 画面の「PC用スクリプトを書き出す」ボタン、または
+ `adb shell am broadcast -a jp.example.tethering.EXPORT_SCRIPTS`
+ - スマホ内 `/data/local/tmp/` に書き出し
+ - PC 側で `adb pull /data/local/tmp/pc-autoconnect* <dir>`
+- PC 側は初回設定後、DHCP で自動接続
+
+## 仕組み
+
+701KC では SoftBank の `jp.softbank.mb.tetherAuthNfp` がテザリング開始後に
+停止させてしまいます。このアプリは root サービス経由で
+
+1. `jp.softbank.mb.tetherAuthNfp` を無効化
+2. `ConnectivityManager.setUsbTethering(true)` を root (uid 0) で実行
+
+します。
+
+root サービスは `/kcroot.sh` が提供しているものをそのまま使います。
+`/data/local/tmp/rin` にコマンドを書き、`/data/local/tmp/rout` に結果が出ます。
+アプリ自身は root を要求しません(`rin` は world-writable のため)。
+
+## ビルド
+
+```powershell
+cd tethering-app
+powershell -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
+```
+
+出力:
+
+- `build/Tethering-debug.apk`
+- `C:\Users\forest\AppData\Local\Temp\opencode\Tethering-debug.apk`(インストール用の ASCII パス)
+
+## インストール
+
+```powershell
+adb install -r "C:\Users\forest\AppData\Local\Temp\opencode\Tethering-debug.apk"
+adb shell am start -n jp.example.tethering/.MainActivity
+```
+
+初回だけアプリを起動してください。以後は USB 接続・端末起動時に自動で ON になります。
+
+> 再ビルドで署名キーが変わらないよう、`tethering-app/debug.keystore` を残しています。
+> 消すと再インストール時に `INSTALL_FAILED_UPDATE_INCOMPATIBLE` になります。
+
+## PC 側の初回設定
+
+スクリプトはアプリの「PC用スクリプトを書き出す」で `/data/local/tmp/` に
+書き出せます。
+
+```powershell
+adb pull /data/local/tmp/pc-autoconnect.ps1 R:\Projects\Tethering-pc\
+adb pull /data/local/tmp/pc-autoconnect.sh R:\Projects\Tethering-pc\
+adb pull /data/local/tmp/pc-autoconnect-linux.sh R:\Projects\Tethering-pc\
+adb pull /data/local/tmp/pc-autoconnect-freebsd.sh R:\Projects\Tethering-pc\
+```
+
+Linux / FreeBSD では実行権限を付けてください。
+
+```sh
+chmod +x pc-autoconnect*.sh
+```
+
+### Windows (PowerShell)
+
+`pc-autoconnect.bat` を右クリック →「管理者として実行」してください。
+UAC が出ます。
+
+- 既定: RNDIS アダプタを DHCP に切り替え、インターフェースメトリックを 5 にします。
+ - スマホ側の dnsmasq から `192.168.42.x` とゲートウェイ `192.168.42.129` を自動取得します。
+- DHCP が使えない場合:
+ ```powershell
+ .\pc-autoconnect.ps1 -Static
+ ```
+ - PC を `192.168.42.1/24`、ゲートウェイを `192.168.42.129` に固定します。
+
+### Linux
+
+```sh
+sudo ./pc-autoconnect-linux.sh
+# DHCP が合わない場合
+sudo ./pc-autoconnect-linux.sh --static
+```
+
+- `rndis_host` / `cdc_ether` / `usbnet` のインターフェースを自動検出します。
+- 手動指定: `sudo IFACE=usb0 ./pc-autoconnect-linux.sh`
+- NetworkManager があれば `nmcli`、なければ `dhcpcd` / `dhclient` / `udhcpc` を使用します。
+- ルートメトリックを 5 にしてスマホを優先します。
+
+### FreeBSD
+
+```sh
+sudo ./pc-autoconnect-freebsd.sh
+# DHCP が合わない場合
+sudo ./pc-autoconnect-freebsd.sh --static
+```
+
+- `ue0` / `cdce0` / `ure0` を自動検出します。
+- 手動指定: `sudo IFACE=ue0 ./pc-autoconnect-freebsd.sh`
+- `dhclient` / `dhcpcd` を使用します。
+- デフォルトルートは `route add`、既にある場合は `route change` を試します。
+
+### 共通ディスパッチャ
+
+`pc-autoconnect.sh` は `uname -s` で Linux / FreeBSD を判定して呼び分けます。
+
+```sh
+sudo ./pc-autoconnect.sh
+```
+
+一度設定すれば、以後は USB を挿してアプリがテザリングを ON にすれば
+自動で DHCP 接続します。
+
+## 元に戻す
+
+- テザリング OFF: アプリのボタン、または
+ `adb shell am broadcast -a jp.example.tethering.USB_OFF`
+- SoftBank の認証アプリを戻す:
+ `adb shell pm enable jp.softbank.mb.tetherAuthNfp`
+- 京セラのモバイルデータ確認ダイアログを戻す:
+ `adb shell pm enable android/com.android.internal.app.KcAlertMobiledataActivity`
+- アプリのアンインストール:
+ `adb uninstall jp.example.tethering`
+- PC 側を元に戻す:
+ `Set-NetIPInterface -InterfaceIndex <ifIndex> -Dhcp Enabled`
+ `Set-NetIPInterface -InterfaceIndex <ifIndex> -InterfaceMetric 25`
+
+## 注意
+
+- 京セラの「モバイルデータ通信」確認ダイアログ
+ (`android/com.android.internal.app.KcAlertMobiledataActivity`) は
+ アプリが root 経由で無効化します。
+ 戻す場合:
+ `adb shell pm enable android/com.android.internal.app.KcAlertMobiledataActivity`
+- ON 時に `jp.softbank.mb.tetherAuthNfp` を無効化し、`am force-stop` も実行します。
+- スマホ側の `bw_datalimit_OUTPUT` に `rmnet_data0` の REJECT があります。
+ データ制限中はテザリング先もインターネットに出られません。
+ APN / データ制限を確認してください。
+- 画面が閉じている(フリップ閉)状態でもアプリの自動 ON は動きます。
+ ステータス表示は画面を開いたときに更新されます。
+- アプリの状態表示には `INTERNET` 権限を使います(`usb0` の IP を見るため)。
diff --git a/assets/pc-autoconnect-freebsd.sh b/assets/pc-autoconnect-freebsd.sh
new file mode 100644
index 0000000..2410305
--- /dev/null
+++ b/assets/pc-autoconnect-freebsd.sh
@@ -0,0 +1,97 @@
+#!/bin/sh
+# 701KC USB tethering - FreeBSD host auto connect
+#
+# sudo ./pc-autoconnect-freebsd.sh # DHCP (recommended)
+# sudo ./pc-autoconnect-freebsd.sh --static # static 192.168.42.1/24
+# sudo IFACE=ue0 ./pc-autoconnect-freebsd.sh # force interface
+#
+# The phone's RNDIS gadget usually appears as ue0 (if_urndis) or cdce0.
+
+set -eu
+
+PHONE_IP=192.168.42.129
+STATIC=0
+if [ "${1:-}" = "--static" ]; then
+ STATIC=1
+fi
+
+if [ "$(id -u)" -ne 0 ]; then
+ echo "root で実行してください: sudo $0 $*" >&2
+ exit 1
+fi
+
+find_iface() {
+ if [ -n "${IFACE:-}" ]; then
+ echo "$IFACE"
+ return
+ fi
+ for iface in $(ifconfig -l); do
+ case "$iface" in
+ ue[0-9]*|cdce[0-9]*|ure[0-9]*)
+ echo "$iface"
+ return
+ ;;
+ esac
+ done
+}
+
+IFACE=$(find_iface || true)
+if [ -z "${IFACE:-}" ]; then
+ echo "RNDIS インターフェース (ue0 / cdce0 など) が見つかりません。" >&2
+ echo "USB を挿してスマホ側のテザリングを ON にしてください。" >&2
+ echo "手動指定: sudo IFACE=ue0 $0" >&2
+ exit 1
+fi
+
+echo "Interface: $IFACE"
+ifconfig "$IFACE" up
+
+if [ "$STATIC" -eq 1 ]; then
+ echo "Mode : static 192.168.42.1/24 via $PHONE_IP"
+ ifconfig "$IFACE" inet 192.168.42.1/24
+ route add -net 192.168.42.0/24 -iface "$IFACE" 2>/dev/null || true
+ route add default "$PHONE_IP" 2>/dev/null || route change default "$PHONE_IP" 2>/dev/null || true
+else
+ echo "Mode : DHCP"
+ if command -v dhclient >/dev/null 2>&1; then
+ dhclient "$IFACE"
+ elif command -v dhcpcd >/dev/null 2>&1; then
+ dhcpcd "$IFACE"
+ else
+ echo "dhclient / dhcpcd が見つかりません。--static を使ってください。" >&2
+ exit 1
+ fi
+fi
+
+echo "Waiting for $PHONE_IP ..."
+i=0
+while [ "$i" -lt 30 ]; do
+ if ping -c 1 -t 2 "$PHONE_IP" >/dev/null 2>&1; then
+ break
+ fi
+ i=$((i + 1))
+ sleep 1
+done
+
+ifconfig "$IFACE" || true
+netstat -rn | head -20 || true
+
+if ping -c 2 -t 2 "$PHONE_IP" >/dev/null 2>&1; then
+ echo "Phone : reachable at $PHONE_IP"
+else
+ echo "Phone : unreachable (テザリングが ON か確認してください)" >&2
+fi
+
+if command -v curl >/dev/null 2>&1; then
+ if curl -fsS --max-time 10 http://example.com/ >/dev/null 2>&1; then
+ echo "Internet: OK"
+ else
+ echo "Internet: NG (APN / データ制限を確認)" >&2
+ fi
+elif command -v fetch >/dev/null 2>&1; then
+ if fetch -q -T 10 -o /dev/null http://example.com/ 2>/dev/null; then
+ echo "Internet: OK"
+ else
+ echo "Internet: NG (APN / データ制限を確認)" >&2
+ fi
+fi
diff --git a/assets/pc-autoconnect-linux.sh b/assets/pc-autoconnect-linux.sh
new file mode 100644
index 0000000..ffbaa26
--- /dev/null
+++ b/assets/pc-autoconnect-linux.sh
@@ -0,0 +1,114 @@
+#!/bin/sh
+# 701KC USB tethering - Linux host auto connect
+#
+# sudo ./pc-autoconnect-linux.sh # DHCP (recommended)
+# sudo ./pc-autoconnect-linux.sh --static # static 192.168.42.1/24
+# sudo IFACE=usb0 ./pc-autoconnect-linux.sh # force interface
+#
+# The phone runs dnsmasq on usb0 (192.168.42.129), so DHCP normally works.
+
+set -eu
+
+PHONE_IP=192.168.42.129
+STATIC=0
+if [ "${1:-}" = "--static" ]; then
+ STATIC=1
+fi
+
+if [ "$(id -u)" -ne 0 ]; then
+ echo "root で実行してください: sudo $0 $*" >&2
+ exit 1
+fi
+
+find_iface() {
+ if [ -n "${IFACE:-}" ]; then
+ echo "$IFACE"
+ return
+ fi
+ for n in /sys/class/net/*; do
+ [ -e "$n" ] || continue
+ iface=${n##*/}
+ driver=$(readlink "$n/device/driver" 2>/dev/null | sed 's#.*/##')
+ case "$driver" in
+ rndis_host|cdc_ether|usbnet)
+ echo "$iface"
+ return
+ ;;
+ esac
+ done
+ for iface in usb0 ue0; do
+ [ -e "/sys/class/net/$iface" ] && { echo "$iface"; return; }
+ done
+}
+
+IFACE=$(find_iface || true)
+if [ -z "${IFACE:-}" ]; then
+ echo "RNDIS インターフェースが見つかりません。" >&2
+ echo "USB を挿してスマホ側のテザリングを ON にしてください。" >&2
+ echo "手動指定: sudo IFACE=usb0 $0" >&2
+ exit 1
+fi
+
+echo "Interface: $IFACE"
+ip link set "$IFACE" up
+
+if [ "$STATIC" -eq 1 ]; then
+ echo "Mode : static 192.168.42.1/24 via $PHONE_IP"
+ ip -4 addr flush dev "$IFACE" 2>/dev/null || true
+ ip addr add 192.168.42.1/24 dev "$IFACE"
+ ip route replace default via "$PHONE_IP" dev "$IFACE" metric 5
+else
+ echo "Mode : DHCP"
+ if command -v nmcli >/dev/null 2>&1 && [ "$(nmcli -t -f RUNNING general 2>/dev/null || true)" = "running" ]; then
+ con="tethering-701kc"
+ nmcli connection delete "$con" >/dev/null 2>&1 || true
+ nmcli connection add type ethernet ifname "$IFACE" con-name "$con" \
+ ipv4.method auto ipv4.route-metric 5 connection.autoconnect yes >/dev/null
+ nmcli connection up "$con" >/dev/null
+ elif command -v dhcpcd >/dev/null 2>&1; then
+ dhcpcd -n "$IFACE" 2>/dev/null || dhcpcd "$IFACE"
+ elif command -v dhclient >/dev/null 2>&1; then
+ dhclient -v "$IFACE"
+ elif command -v udhcpc >/dev/null 2>&1; then
+ udhcpc -i "$IFACE" -q -n
+ else
+ echo "DHCP クライアントが見つかりません。--static を使ってください。" >&2
+ exit 1
+ fi
+fi
+
+# Prefer the phone while it is connected.
+ip route replace default via "$PHONE_IP" dev "$IFACE" metric 5 2>/dev/null || true
+
+echo "Waiting for $PHONE_IP ..."
+i=0
+while [ "$i" -lt 30 ]; do
+ if ping -c 1 -W 2 "$PHONE_IP" >/dev/null 2>&1; then
+ break
+ fi
+ i=$((i + 1))
+ sleep 1
+done
+
+ip -4 addr show "$IFACE" || true
+ip route || true
+
+if ping -c 2 -W 2 "$PHONE_IP" >/dev/null 2>&1; then
+ echo "Phone : reachable at $PHONE_IP"
+else
+ echo "Phone : unreachable (テザリングが ON か確認してください)" >&2
+fi
+
+if command -v curl >/dev/null 2>&1; then
+ if curl -fsS --max-time 10 http://example.com/ >/dev/null 2>&1; then
+ echo "Internet: OK"
+ else
+ echo "Internet: NG (APN / データ制限を確認)" >&2
+ fi
+elif command -v wget >/dev/null 2>&1; then
+ if wget -q -T 10 -O /dev/null http://example.com/ 2>/dev/null; then
+ echo "Internet: OK"
+ else
+ echo "Internet: NG (APN / データ制限を確認)" >&2
+ fi
+fi
diff --git a/assets/pc-autoconnect.ps1 b/assets/pc-autoconnect.ps1
new file mode 100644
index 0000000..c58da82
--- /dev/null
+++ b/assets/pc-autoconnect.ps1
@@ -0,0 +1,115 @@
+#Requires -Version 5.1
+<#
+ 701KC USB tethering - PC side auto connect
+
+ Run once as Administrator. The RNDIS adapter is switched to DHCP, so from
+ then on Windows gets 192.168.42.x + gateway 192.168.42.129 automatically
+ every time the phone enables USB tethering.
+
+ If DHCP does not work on your machine, use:
+ .\pc-autoconnect.ps1 -Static
+ which sets 192.168.42.1/24 and default gateway 192.168.42.129.
+
+ To undo:
+ Set-NetIPInterface -InterfaceIndex <ifIndex> -Dhcp Enabled
+ Set-NetIPInterface -InterfaceIndex <ifIndex> -InterfaceMetric 25
+#>
+[CmdletBinding()]
+param(
+ [switch]$Static,
+ [string]$PhoneIp = '192.168.42.129'
+)
+
+$ErrorActionPreference = 'Stop'
+
+function Test-Admin {
+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
+ $principal = New-Object Security.Principal.WindowsPrincipal($identity)
+ return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
+}
+
+if (-not (Test-Admin)) {
+ Write-Host '管理者権限で再起動します...'
+ $argList = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', "`"$PSCommandPath`"")
+ if ($Static) { $argList += '-Static' }
+ Start-Process powershell.exe -Verb RunAs -ArgumentList $argList
+ exit
+}
+
+Write-Host '=== 701KC tethering: PC auto connect ==='
+
+$adapters = @(Get-NetAdapter | Where-Object { $_.InterfaceDescription -match 'Remote NDIS|RNDIS' })
+if ($adapters.Count -eq 0) {
+ Write-Error 'RNDIS アダプタが見つかりません。USB を接続し、スマホ側でテザリングを ON にしてください。'
+ exit 1
+}
+
+$adapter = $adapters | Where-Object { $_.Status -eq 'Up' } | Select-Object -First 1
+if (-not $adapter) {
+ $adapter = $adapters | Select-Object -First 1
+ Write-Warning "RNDIS アダプタ '$($adapter.Name)' は Up ではありません。テザリングを ON にしてから再実行してください。"
+}
+
+Write-Host "Adapter : $($adapter.Name) [$($adapter.InterfaceDescription)] ifIndex=$($adapter.ifIndex) status=$($adapter.Status)"
+
+try {
+ Set-NetConnectionProfile -InterfaceIndex $adapter.ifIndex -NetworkCategory Private -ErrorAction Stop
+ Write-Host 'Network category: Private'
+} catch {
+ Write-Warning "ネットワーク種別を Private にできませんでした: $($_.Exception.Message)"
+}
+
+if ($Static) {
+ Write-Host 'Mode : Static 192.168.42.1/24, gateway 192.168.42.129'
+ Get-NetIPAddress -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
+ Remove-NetIPAddress -Confirm:$false -ErrorAction SilentlyContinue
+ Get-NetRoute -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
+ Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue
+ New-NetIPAddress -InterfaceIndex $adapter.ifIndex -IPAddress '192.168.42.1' -PrefixLength 24 -DefaultGateway $PhoneIp | Out-Null
+ Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ServerAddresses $PhoneIp, '8.8.8.8'
+} else {
+ Write-Host 'Mode : DHCP (phone runs dnsmasq at 192.168.42.129)'
+ # Remove the old static 192.168.42.1 configuration before switching to DHCP.
+ Get-NetIPAddress -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
+ Remove-NetIPAddress -Confirm:$false -ErrorAction SilentlyContinue
+ Get-NetRoute -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
+ Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue
+ Set-NetIPInterface -InterfaceIndex $adapter.ifIndex -Dhcp Enabled
+ Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ResetServerAddresses -ErrorAction SilentlyContinue
+ ipconfig /renew "$($adapter.Name)" | Out-Null
+}
+
+# Prefer the phone over Wi-Fi/Ethernet while it is connected.
+Set-NetIPInterface -InterfaceIndex $adapter.ifIndex -InterfaceMetric 5
+Write-Host 'Interface metric: 5 (phone is preferred)'
+
+$reachable = $false
+for ($i = 1; $i -le 30; $i++) {
+ if (Test-Connection -ComputerName $PhoneIp -Count 1 -Quiet -ErrorAction SilentlyContinue) {
+ $reachable = $true
+ break
+ }
+ Start-Sleep -Seconds 1
+}
+
+if ($reachable) {
+ Write-Host "Phone : reachable at $PhoneIp"
+} else {
+ Write-Warning "Phone : $PhoneIp に到達できません。スマホのテザリングが ON か確認してください。"
+}
+
+Write-Host ''
+Get-NetIPConfiguration -InterfaceIndex $adapter.ifIndex | Format-List
+
+if ($reachable) {
+ try {
+ $r = Invoke-WebRequest -Uri 'http://example.com/' -UseBasicParsing -TimeoutSec 10
+ Write-Host "Internet: HTTP $($r.StatusCode) (via the phone)"
+ } catch {
+ Write-Warning "Internet: 確認できませんでした: $($_.Exception.Message)"
+ Write-Warning 'スマホ側の APN / データ制限(bw_datalimit)を確認してください。'
+ }
+}
+
+Write-Host ''
+Write-Host 'Done. 以後は USB を挿してアプリがテザリングを ON にすれば自動で接続します。'
diff --git a/assets/pc-autoconnect.sh b/assets/pc-autoconnect.sh
new file mode 100644
index 0000000..5f2a224
--- /dev/null
+++ b/assets/pc-autoconnect.sh
@@ -0,0 +1,22 @@
+#!/bin/sh
+# 701KC USB tethering - OS dispatcher
+#
+# sudo ./pc-autoconnect.sh # DHCP
+# sudo ./pc-autoconnect.sh --static # static fallback
+#
+set -eu
+
+DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+
+case "$(uname -s)" in
+ Linux*)
+ exec "$DIR/pc-autoconnect-linux.sh" "$@"
+ ;;
+ FreeBSD*)
+ exec "$DIR/pc-autoconnect-freebsd.sh" "$@"
+ ;;
+ *)
+ echo "Unsupported OS: $(uname -s)" >&2
+ exit 1
+ ;;
+esac
diff --git a/build.ps1 b/build.ps1
new file mode 100644
index 0000000..706303b
--- /dev/null
+++ b/build.ps1
@@ -0,0 +1,64 @@
+$ErrorActionPreference = 'Stop'
+
+$sdk = 'C:\Users\forest\AppData\Local\Android\Sdk'
+$buildTools = Join-Path $sdk 'build-tools\35.0.0'
+$androidJar = Join-Path $sdk 'platforms\android-34\android.jar'
+$root = Split-Path -Parent $MyInvocation.MyCommand.Path
+$build = Join-Path $root 'build'
+
+Write-Host '=== clean ==='
+if (Test-Path $build) { Remove-Item $build -Recurse -Force }
+New-Item -ItemType Directory -Path $build | Out-Null
+New-Item -ItemType Directory -Path (Join-Path $build 'classes') | Out-Null
+New-Item -ItemType Directory -Path (Join-Path $build 'dex') | Out-Null
+
+Write-Host '=== javac ==='
+$sources = @(Get-ChildItem (Join-Path $root 'src') -Recurse -Filter *.java | ForEach-Object { $_.FullName })
+& javac -encoding UTF-8 -cp $androidJar -d (Join-Path $build 'classes') $sources
+if ($LASTEXITCODE -ne 0) { throw 'javac failed' }
+
+Write-Host '=== d8 ==='
+$classes = @(Get-ChildItem (Join-Path $build 'classes') -Recurse -Filter *.class | ForEach-Object { $_.FullName })
+& (Join-Path $buildTools 'd8.bat') --min-api 21 --lib $androidJar --output (Join-Path $build 'dex') $classes
+if ($LASTEXITCODE -ne 0) { throw 'd8 failed' }
+
+Write-Host '=== aapt package ==='
+$unsigned = Join-Path $build 'app-unsigned.apk'
+& (Join-Path $buildTools 'aapt.exe') package -f -M (Join-Path $root 'AndroidManifest.xml') -S (Join-Path $root 'res') -A (Join-Path $root 'assets') -I $androidJar -F $unsigned
+if ($LASTEXITCODE -ne 0) { throw 'aapt package failed' }
+
+Push-Location (Join-Path $build 'dex')
+try {
+ & (Join-Path $buildTools 'aapt.exe') add $unsigned classes.dex
+ if ($LASTEXITCODE -ne 0) { throw 'aapt add failed' }
+} finally {
+ Pop-Location
+}
+
+Write-Host '=== zipalign ==='
+$aligned = Join-Path $build 'app-aligned.apk'
+& (Join-Path $buildTools 'zipalign.exe') -f 4 $unsigned $aligned
+if ($LASTEXITCODE -ne 0) { throw 'zipalign failed' }
+
+Write-Host '=== keystore ==='
+$ks = Join-Path $root 'debug.keystore'
+if (-not (Test-Path $ks)) {
+ & keytool -genkeypair -keystore $ks -alias androiddebugkey -storepass android -keypass android `
+ -keyalg RSA -keysize 2048 -validity 10000 -dname 'CN=Android Debug,O=Android,C=US'
+ if ($LASTEXITCODE -ne 0) { throw 'keytool failed' }
+}
+
+Write-Host '=== apksigner ==='
+$out = Join-Path $build 'Tethering-debug.apk'
+& (Join-Path $buildTools 'apksigner.bat') sign --ks $ks --ks-pass pass:android --key-pass pass:android `
+ --out $out $aligned
+if ($LASTEXITCODE -ne 0) { throw 'apksigner failed' }
+
+$asciiOut = 'C:\Users\forest\AppData\Local\Temp\opencode\Tethering-debug.apk'
+Copy-Item $out $asciiOut -Force
+
+Write-Host ''
+Write-Host "APK: $out"
+Write-Host "Install copy (ASCII path): $asciiOut"
+Write-Host " adb install -r `"$asciiOut`""
+Get-Item $out | Select-Object FullName, Length, LastWriteTime
diff --git a/pc/pc-autoconnect-freebsd.sh b/pc/pc-autoconnect-freebsd.sh
new file mode 100644
index 0000000..2410305
--- /dev/null
+++ b/pc/pc-autoconnect-freebsd.sh
@@ -0,0 +1,97 @@
+#!/bin/sh
+# 701KC USB tethering - FreeBSD host auto connect
+#
+# sudo ./pc-autoconnect-freebsd.sh # DHCP (recommended)
+# sudo ./pc-autoconnect-freebsd.sh --static # static 192.168.42.1/24
+# sudo IFACE=ue0 ./pc-autoconnect-freebsd.sh # force interface
+#
+# The phone's RNDIS gadget usually appears as ue0 (if_urndis) or cdce0.
+
+set -eu
+
+PHONE_IP=192.168.42.129
+STATIC=0
+if [ "${1:-}" = "--static" ]; then
+ STATIC=1
+fi
+
+if [ "$(id -u)" -ne 0 ]; then
+ echo "root で実行してください: sudo $0 $*" >&2
+ exit 1
+fi
+
+find_iface() {
+ if [ -n "${IFACE:-}" ]; then
+ echo "$IFACE"
+ return
+ fi
+ for iface in $(ifconfig -l); do
+ case "$iface" in
+ ue[0-9]*|cdce[0-9]*|ure[0-9]*)
+ echo "$iface"
+ return
+ ;;
+ esac
+ done
+}
+
+IFACE=$(find_iface || true)
+if [ -z "${IFACE:-}" ]; then
+ echo "RNDIS インターフェース (ue0 / cdce0 など) が見つかりません。" >&2
+ echo "USB を挿してスマホ側のテザリングを ON にしてください。" >&2
+ echo "手動指定: sudo IFACE=ue0 $0" >&2
+ exit 1
+fi
+
+echo "Interface: $IFACE"
+ifconfig "$IFACE" up
+
+if [ "$STATIC" -eq 1 ]; then
+ echo "Mode : static 192.168.42.1/24 via $PHONE_IP"
+ ifconfig "$IFACE" inet 192.168.42.1/24
+ route add -net 192.168.42.0/24 -iface "$IFACE" 2>/dev/null || true
+ route add default "$PHONE_IP" 2>/dev/null || route change default "$PHONE_IP" 2>/dev/null || true
+else
+ echo "Mode : DHCP"
+ if command -v dhclient >/dev/null 2>&1; then
+ dhclient "$IFACE"
+ elif command -v dhcpcd >/dev/null 2>&1; then
+ dhcpcd "$IFACE"
+ else
+ echo "dhclient / dhcpcd が見つかりません。--static を使ってください。" >&2
+ exit 1
+ fi
+fi
+
+echo "Waiting for $PHONE_IP ..."
+i=0
+while [ "$i" -lt 30 ]; do
+ if ping -c 1 -t 2 "$PHONE_IP" >/dev/null 2>&1; then
+ break
+ fi
+ i=$((i + 1))
+ sleep 1
+done
+
+ifconfig "$IFACE" || true
+netstat -rn | head -20 || true
+
+if ping -c 2 -t 2 "$PHONE_IP" >/dev/null 2>&1; then
+ echo "Phone : reachable at $PHONE_IP"
+else
+ echo "Phone : unreachable (テザリングが ON か確認してください)" >&2
+fi
+
+if command -v curl >/dev/null 2>&1; then
+ if curl -fsS --max-time 10 http://example.com/ >/dev/null 2>&1; then
+ echo "Internet: OK"
+ else
+ echo "Internet: NG (APN / データ制限を確認)" >&2
+ fi
+elif command -v fetch >/dev/null 2>&1; then
+ if fetch -q -T 10 -o /dev/null http://example.com/ 2>/dev/null; then
+ echo "Internet: OK"
+ else
+ echo "Internet: NG (APN / データ制限を確認)" >&2
+ fi
+fi
diff --git a/pc/pc-autoconnect-linux.sh b/pc/pc-autoconnect-linux.sh
new file mode 100644
index 0000000..ffbaa26
--- /dev/null
+++ b/pc/pc-autoconnect-linux.sh
@@ -0,0 +1,114 @@
+#!/bin/sh
+# 701KC USB tethering - Linux host auto connect
+#
+# sudo ./pc-autoconnect-linux.sh # DHCP (recommended)
+# sudo ./pc-autoconnect-linux.sh --static # static 192.168.42.1/24
+# sudo IFACE=usb0 ./pc-autoconnect-linux.sh # force interface
+#
+# The phone runs dnsmasq on usb0 (192.168.42.129), so DHCP normally works.
+
+set -eu
+
+PHONE_IP=192.168.42.129
+STATIC=0
+if [ "${1:-}" = "--static" ]; then
+ STATIC=1
+fi
+
+if [ "$(id -u)" -ne 0 ]; then
+ echo "root で実行してください: sudo $0 $*" >&2
+ exit 1
+fi
+
+find_iface() {
+ if [ -n "${IFACE:-}" ]; then
+ echo "$IFACE"
+ return
+ fi
+ for n in /sys/class/net/*; do
+ [ -e "$n" ] || continue
+ iface=${n##*/}
+ driver=$(readlink "$n/device/driver" 2>/dev/null | sed 's#.*/##')
+ case "$driver" in
+ rndis_host|cdc_ether|usbnet)
+ echo "$iface"
+ return
+ ;;
+ esac
+ done
+ for iface in usb0 ue0; do
+ [ -e "/sys/class/net/$iface" ] && { echo "$iface"; return; }
+ done
+}
+
+IFACE=$(find_iface || true)
+if [ -z "${IFACE:-}" ]; then
+ echo "RNDIS インターフェースが見つかりません。" >&2
+ echo "USB を挿してスマホ側のテザリングを ON にしてください。" >&2
+ echo "手動指定: sudo IFACE=usb0 $0" >&2
+ exit 1
+fi
+
+echo "Interface: $IFACE"
+ip link set "$IFACE" up
+
+if [ "$STATIC" -eq 1 ]; then
+ echo "Mode : static 192.168.42.1/24 via $PHONE_IP"
+ ip -4 addr flush dev "$IFACE" 2>/dev/null || true
+ ip addr add 192.168.42.1/24 dev "$IFACE"
+ ip route replace default via "$PHONE_IP" dev "$IFACE" metric 5
+else
+ echo "Mode : DHCP"
+ if command -v nmcli >/dev/null 2>&1 && [ "$(nmcli -t -f RUNNING general 2>/dev/null || true)" = "running" ]; then
+ con="tethering-701kc"
+ nmcli connection delete "$con" >/dev/null 2>&1 || true
+ nmcli connection add type ethernet ifname "$IFACE" con-name "$con" \
+ ipv4.method auto ipv4.route-metric 5 connection.autoconnect yes >/dev/null
+ nmcli connection up "$con" >/dev/null
+ elif command -v dhcpcd >/dev/null 2>&1; then
+ dhcpcd -n "$IFACE" 2>/dev/null || dhcpcd "$IFACE"
+ elif command -v dhclient >/dev/null 2>&1; then
+ dhclient -v "$IFACE"
+ elif command -v udhcpc >/dev/null 2>&1; then
+ udhcpc -i "$IFACE" -q -n
+ else
+ echo "DHCP クライアントが見つかりません。--static を使ってください。" >&2
+ exit 1
+ fi
+fi
+
+# Prefer the phone while it is connected.
+ip route replace default via "$PHONE_IP" dev "$IFACE" metric 5 2>/dev/null || true
+
+echo "Waiting for $PHONE_IP ..."
+i=0
+while [ "$i" -lt 30 ]; do
+ if ping -c 1 -W 2 "$PHONE_IP" >/dev/null 2>&1; then
+ break
+ fi
+ i=$((i + 1))
+ sleep 1
+done
+
+ip -4 addr show "$IFACE" || true
+ip route || true
+
+if ping -c 2 -W 2 "$PHONE_IP" >/dev/null 2>&1; then
+ echo "Phone : reachable at $PHONE_IP"
+else
+ echo "Phone : unreachable (テザリングが ON か確認してください)" >&2
+fi
+
+if command -v curl >/dev/null 2>&1; then
+ if curl -fsS --max-time 10 http://example.com/ >/dev/null 2>&1; then
+ echo "Internet: OK"
+ else
+ echo "Internet: NG (APN / データ制限を確認)" >&2
+ fi
+elif command -v wget >/dev/null 2>&1; then
+ if wget -q -T 10 -O /dev/null http://example.com/ 2>/dev/null; then
+ echo "Internet: OK"
+ else
+ echo "Internet: NG (APN / データ制限を確認)" >&2
+ fi
+fi
diff --git a/pc/pc-autoconnect.bat b/pc/pc-autoconnect.bat
new file mode 100644
index 0000000..dd7fadc
--- /dev/null
+++ b/pc/pc-autoconnect.bat
@@ -0,0 +1,5 @@
+@echo off
+setlocal
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0pc-autoconnect.ps1" %*
+echo.
+pause
diff --git a/pc/pc-autoconnect.ps1 b/pc/pc-autoconnect.ps1
new file mode 100644
index 0000000..c58da82
--- /dev/null
+++ b/pc/pc-autoconnect.ps1
@@ -0,0 +1,115 @@
+#Requires -Version 5.1
+<#
+ 701KC USB tethering - PC side auto connect
+
+ Run once as Administrator. The RNDIS adapter is switched to DHCP, so from
+ then on Windows gets 192.168.42.x + gateway 192.168.42.129 automatically
+ every time the phone enables USB tethering.
+
+ If DHCP does not work on your machine, use:
+ .\pc-autoconnect.ps1 -Static
+ which sets 192.168.42.1/24 and default gateway 192.168.42.129.
+
+ To undo:
+ Set-NetIPInterface -InterfaceIndex <ifIndex> -Dhcp Enabled
+ Set-NetIPInterface -InterfaceIndex <ifIndex> -InterfaceMetric 25
+#>
+[CmdletBinding()]
+param(
+ [switch]$Static,
+ [string]$PhoneIp = '192.168.42.129'
+)
+
+$ErrorActionPreference = 'Stop'
+
+function Test-Admin {
+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
+ $principal = New-Object Security.Principal.WindowsPrincipal($identity)
+ return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
+}
+
+if (-not (Test-Admin)) {
+ Write-Host '管理者権限で再起動します...'
+ $argList = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', "`"$PSCommandPath`"")
+ if ($Static) { $argList += '-Static' }
+ Start-Process powershell.exe -Verb RunAs -ArgumentList $argList
+ exit
+}
+
+Write-Host '=== 701KC tethering: PC auto connect ==='
+
+$adapters = @(Get-NetAdapter | Where-Object { $_.InterfaceDescription -match 'Remote NDIS|RNDIS' })
+if ($adapters.Count -eq 0) {
+ Write-Error 'RNDIS アダプタが見つかりません。USB を接続し、スマホ側でテザリングを ON にしてください。'
+ exit 1
+}
+
+$adapter = $adapters | Where-Object { $_.Status -eq 'Up' } | Select-Object -First 1
+if (-not $adapter) {
+ $adapter = $adapters | Select-Object -First 1
+ Write-Warning "RNDIS アダプタ '$($adapter.Name)' は Up ではありません。テザリングを ON にしてから再実行してください。"
+}
+
+Write-Host "Adapter : $($adapter.Name) [$($adapter.InterfaceDescription)] ifIndex=$($adapter.ifIndex) status=$($adapter.Status)"
+
+try {
+ Set-NetConnectionProfile -InterfaceIndex $adapter.ifIndex -NetworkCategory Private -ErrorAction Stop
+ Write-Host 'Network category: Private'
+} catch {
+ Write-Warning "ネットワーク種別を Private にできませんでした: $($_.Exception.Message)"
+}
+
+if ($Static) {
+ Write-Host 'Mode : Static 192.168.42.1/24, gateway 192.168.42.129'
+ Get-NetIPAddress -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
+ Remove-NetIPAddress -Confirm:$false -ErrorAction SilentlyContinue
+ Get-NetRoute -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
+ Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue
+ New-NetIPAddress -InterfaceIndex $adapter.ifIndex -IPAddress '192.168.42.1' -PrefixLength 24 -DefaultGateway $PhoneIp | Out-Null
+ Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ServerAddresses $PhoneIp, '8.8.8.8'
+} else {
+ Write-Host 'Mode : DHCP (phone runs dnsmasq at 192.168.42.129)'
+ # Remove the old static 192.168.42.1 configuration before switching to DHCP.
+ Get-NetIPAddress -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
+ Remove-NetIPAddress -Confirm:$false -ErrorAction SilentlyContinue
+ Get-NetRoute -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
+ Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue
+ Set-NetIPInterface -InterfaceIndex $adapter.ifIndex -Dhcp Enabled
+ Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ResetServerAddresses -ErrorAction SilentlyContinue
+ ipconfig /renew "$($adapter.Name)" | Out-Null
+}
+
+# Prefer the phone over Wi-Fi/Ethernet while it is connected.
+Set-NetIPInterface -InterfaceIndex $adapter.ifIndex -InterfaceMetric 5
+Write-Host 'Interface metric: 5 (phone is preferred)'
+
+$reachable = $false
+for ($i = 1; $i -le 30; $i++) {
+ if (Test-Connection -ComputerName $PhoneIp -Count 1 -Quiet -ErrorAction SilentlyContinue) {
+ $reachable = $true
+ break
+ }
+ Start-Sleep -Seconds 1
+}
+
+if ($reachable) {
+ Write-Host "Phone : reachable at $PhoneIp"
+} else {
+ Write-Warning "Phone : $PhoneIp に到達できません。スマホのテザリングが ON か確認してください。"
+}
+
+Write-Host ''
+Get-NetIPConfiguration -InterfaceIndex $adapter.ifIndex | Format-List
+
+if ($reachable) {
+ try {
+ $r = Invoke-WebRequest -Uri 'http://example.com/' -UseBasicParsing -TimeoutSec 10
+ Write-Host "Internet: HTTP $($r.StatusCode) (via the phone)"
+ } catch {
+ Write-Warning "Internet: 確認できませんでした: $($_.Exception.Message)"
+ Write-Warning 'スマホ側の APN / データ制限(bw_datalimit)を確認してください。'
+ }
+}
+
+Write-Host ''
+Write-Host 'Done. 以後は USB を挿してアプリがテザリングを ON にすれば自動で接続します。'
diff --git a/pc/pc-autoconnect.sh b/pc/pc-autoconnect.sh
new file mode 100644
index 0000000..5f2a224
--- /dev/null
+++ b/pc/pc-autoconnect.sh
@@ -0,0 +1,22 @@
+#!/bin/sh
+# 701KC USB tethering - OS dispatcher
+#
+# sudo ./pc-autoconnect.sh # DHCP
+# sudo ./pc-autoconnect.sh --static # static fallback
+#
+set -eu
+
+DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+
+case "$(uname -s)" in
+ Linux*)
+ exec "$DIR/pc-autoconnect-linux.sh" "$@"
+ ;;
+ FreeBSD*)
+ exec "$DIR/pc-autoconnect-freebsd.sh" "$@"
+ ;;
+ *)
+ echo "Unsupported OS: $(uname -s)" >&2
+ exit 1
+ ;;
+esac
diff --git a/res/values/strings.xml b/res/values/strings.xml
new file mode 100644
index 0000000..a6b652a
--- /dev/null
+++ b/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">テザリング</string>
+</resources>
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();
+ }
+}