diff --git a/app/src/main/java/com/neodesktop/dmodem/local/LocalShell.kt b/app/src/main/java/com/neodesktop/dmodem/local/LocalShell.kt index 7de9557..fd04410 100644 --- a/app/src/main/java/com/neodesktop/dmodem/local/LocalShell.kt +++ b/app/src/main/java/com/neodesktop/dmodem/local/LocalShell.kt @@ -33,6 +33,7 @@ class LocalShell( if (!rc.exists()) rc.writeText(DEFAULT_RC) } + /** the shell's environment: the app's with its home, tmp, terminal, start-up file and the system's bins first on the PATH */ fun environment(): Map { val env = LinkedHashMap(base) env["HOME"] = home.path diff --git a/app/src/main/java/com/neodesktop/dmodem/local/Pty.kt b/app/src/main/java/com/neodesktop/dmodem/local/Pty.kt index 6e639f9..b4902a2 100644 --- a/app/src/main/java/com/neodesktop/dmodem/local/Pty.kt +++ b/app/src/main/java/com/neodesktop/dmodem/local/Pty.kt @@ -19,21 +19,25 @@ object Pty { path: String, argv: Array, envp: Array, cwd: String?, rows: Int, cols: Int, pidOut: IntArray, ): Int + /** the pty of master [fd] told it is [rows]x[cols] now */ @JvmStatic external fun resize(fd: Int, rows: Int, cols: Int) /** bytes read, or -1 at the end */ @JvmStatic external fun read(fd: Int, b: ByteArray, off: Int, len: Int): Int + /** all of [b] from [off] for [len] written; false if it can't be */ @JvmStatic external fun write(fd: Int, b: ByteArray, off: Int, len: Int): Boolean /** the exit status (128 + the signal for one that was killed) */ @JvmStatic external fun waitFor(pid: Int): Int + /** [sig] to the process group of [pid] (to [pid] alone if that fails) */ @JvmStatic external fun signal(pid: Int, sig: Int) /** [sig] to every process in session [sid] (the shell's pid): its jobs too; how many */ @JvmStatic external fun signalSession(sid: Int, sig: Int): Int + /** master [fd] closed */ @JvmStatic external fun close(fd: Int) /** a pty with no program on it, its slave raw (the modem's /dev/ttyDM0): the master's fd */ diff --git a/app/src/main/java/com/neodesktop/dmodem/local/Tar.kt b/app/src/main/java/com/neodesktop/dmodem/local/Tar.kt index 7bc3f41..34651e6 100644 --- a/app/src/main/java/com/neodesktop/dmodem/local/Tar.kt +++ b/app/src/main/java/com/neodesktop/dmodem/local/Tar.kt @@ -34,6 +34,7 @@ object Tar { var bytes = 0L } + /** [input]'s tar unpacked into [dest], [onEntry] told each entry's name: how much of each kind */ fun extract(input: InputStream, dest: File, onEntry: (String) -> Unit = {}): Stats { val root = dest.toPath().toAbsolutePath().normalize() Files.createDirectories(root) @@ -131,6 +132,7 @@ object Tar { return p } + /** [mode]'s permission bits set on [p] (the owner's read and write always kept), if the file system allows */ private fun setMode(p: Path, mode: Int) { val perms = HashSet() val all = PosixFilePermission.values() // OWNER_READ .. OTHERS_EXECUTE: bits 8..0 @@ -158,22 +160,26 @@ object Tar { Files.walkFileTree( root, object : SimpleFileVisitor() { + /** the directory made writable first, so its entries can be removed */ override fun preVisitDirectory(d: Path, attrs: BasicFileAttributes): FileVisitResult { // (a read-only directory's entries can't be removed until it's writable) runCatching { d.toFile().setWritable(true, true); d.toFile().setExecutable(true, true); d.toFile().setReadable(true, true) } return FileVisitResult.CONTINUE } + /** a file or link removed */ override fun visitFile(f: Path, attrs: BasicFileAttributes): FileVisitResult { Files.delete(f) return FileVisitResult.CONTINUE } + /** one that can't be read removed anyway */ override fun visitFileFailed(f: Path, exc: IOException): FileVisitResult { Files.deleteIfExists(f) return FileVisitResult.CONTINUE } + /** the directory removed, now empty */ override fun postVisitDirectory(d: Path, exc: IOException?): FileVisitResult { Files.delete(d) return FileVisitResult.CONTINUE @@ -184,6 +190,7 @@ object Tar { // ------------------------------------------------------------------ + /** [b] filled from [i]: false at a clean end before any of it, EOFException if cut short */ private fun readFully(i: InputStream, b: ByteArray): Boolean { var n = 0 while (n < b.size) { @@ -197,6 +204,7 @@ object Tar { return true } + /** an extended header's data of [size] read, with its padding */ private fun readData(i: InputStream, size: Long): ByteArray { if (size > 1 shl 20) throw IOException("tar extended header too big") val b = ByteArray(size.toInt()) @@ -205,6 +213,7 @@ object Tar { return b } + /** [size] bytes of [i] copied to [o] */ private fun copy(i: InputStream, o: java.io.OutputStream, size: Long) { val buf = ByteArray(64 * 1024) var left = size @@ -216,17 +225,20 @@ object Tar { } } + /** [size] bytes and their padding passed over */ private fun skip(i: InputStream, size: Long) { // (OutputStream.nullOutputStream is Android 13's) copy(i, object : java.io.OutputStream() { override fun write(b: Int) {}; override fun write(b: ByteArray, off: Int, len: Int) {} }, size) skipPadding(i, size) } + /** the zeros after [size] bytes of data, to the next 512-byte block, passed over */ private fun skipPadding(i: InputStream, size: Long) { val pad = ((512 - size % 512) % 512).toInt() if (pad > 0) readFully(i, ByteArray(pad)) } + /** the NUL-terminated UTF-8 string in [len] bytes of [b] from [off] */ private fun cString(b: ByteArray, off: Int = 0, len: Int = b.size): String { var end = off while (end < off + len && b[end] != 0.toByte()) end++ @@ -244,6 +256,7 @@ object Tar { return if (s.isEmpty()) 0 else s.toLong(8) } + /** whether header [h]'s checksum (its bytes summed, the checksum field as spaces) is right */ private fun checksumOk(h: ByteArray): Boolean { val want = number(h, 148, 8) var sum = 0L diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/BluetoothModem.kt b/app/src/main/java/com/neodesktop/dmodem/modem/BluetoothModem.kt index 7933d05..d8f8377 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/BluetoothModem.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/BluetoothModem.kt @@ -64,6 +64,7 @@ class ResultCodeStatus(private val onStatus: (NativeModem.Status) -> Unit) { private val line = StringBuilder() private var status = ModemState.IDLE + /** what the modem sent, [length] octets of [data], read a line at a time for its result codes */ fun feed(data: ByteArray, length: Int) { for (i in 0 until length) { val c = data[i].toInt() and 0xff @@ -76,6 +77,7 @@ class ResultCodeStatus(private val onStatus: (NativeModem.Status) -> Unit) { } } + /** the status after result code [r], told if it changed */ private fun result(r: String) { val next = when { r.startsWith("CONNECT") -> { diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/CallTones.kt b/app/src/main/java/com/neodesktop/dmodem/modem/CallTones.kt index 8124bbe..65f9b5e 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/CallTones.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/CallTones.kt @@ -97,6 +97,7 @@ class CallTones( } } + /** the playing thread told to end (its generation moved on), nothing current */ private fun stopLocked() { generation++ current = null @@ -129,7 +130,9 @@ class CallTones( */ class CallProgress(private val player: Player, private val clock: () -> Long = System::currentTimeMillis) { interface Player { + /** [kind] played for [ms] (0: until stopped), in place of what was */ fun play(kind: CallTones.Kind, ms: Int) + /** stopped (only if it's [only], when given) */ fun stop(only: CallTones.Kind? = null) } @@ -153,6 +156,7 @@ class CallProgress(private val player: Player, private val clock: () -> Long = S } } + /** the tones for result code [r]: busy, congestion for a dialled call that failed, none once connected */ private fun result(r: String) { when { r == "RING" -> lastRing = clock() diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/DteHub.kt b/app/src/main/java/com/neodesktop/dmodem/modem/DteHub.kt index baa50a2..9d37338 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/DteHub.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/DteHub.kt @@ -34,6 +34,7 @@ class DteHub : TerminalLink { return true } + /** the modem back to everyone, if [l] had it */ fun release(l: TerminalLink.Listener) { synchronized(this) { if (owner === l) owner = null } } @@ -57,10 +58,12 @@ class DteHub : TerminalLink { private var input: InputStream? = null private var reader: Thread? = null + /** [l] hears what the modem sends from now */ override fun addListener(l: TerminalLink.Listener) { listeners.add(l) } + /** [l] no longer hears the modem */ override fun removeListener(l: TerminalLink.Listener) { listeners.remove(l) } @@ -113,6 +116,7 @@ class DteHub : TerminalLink { override fun write(data: ByteArray, offset: Int, length: Int): Boolean = if (owner != null) false else writeRaw(data, offset, length) + /** octets to the modem, whoever has it (counted for the lights): false if there is none or it has gone */ private fun writeRaw(data: ByteArray, offset: Int, length: Int): Boolean = synchronized(outLock) { bytesOut += length @@ -126,8 +130,10 @@ class DteHub : TerminalLink { } } + /** [text] (ISO-8859-1) to the modem: false as for [write] */ fun write(text: String): Boolean = write(text.toByteArray(Charsets.ISO_8859_1)) + /** what the modem sends, read until its stream ends: to the owner, if any, else every listener */ private fun read(s: InputStream) { val buf = ByteArray(4096) while (true) { diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/IncomingCalls.kt b/app/src/main/java/com/neodesktop/dmodem/modem/IncomingCalls.kt index 5372fe3..2f0e316 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/IncomingCalls.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/IncomingCalls.kt @@ -48,6 +48,7 @@ class IncomingCalls(private val clock: () -> Long = System::currentTimeMillis) { } } + /** a RING counted (none while off hook): a new call, or one more ring of this one */ private fun ring() { if (offhook) return lastRing = clock() diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/LineRecordings.kt b/app/src/main/java/com/neodesktop/dmodem/modem/LineRecordings.kt index 6a5ee64..83daea1 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/LineRecordings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/LineRecordings.kt @@ -14,6 +14,7 @@ object LineRecordings { const val KEEP = 5 private const val PREFIX = "line" + /** the app's captures folder on external storage (null: none to have) */ private fun dir(context: Context): File? = context.applicationContext.getExternalFilesDir("captures") /** the path D-Modem-RE's DMODEM_USB_REC is given (null: nowhere to record to) */ diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt b/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt index 7dbec0a..353977c 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt @@ -67,12 +67,14 @@ class ModemService : Service() { /** the speaker's sound socket, kept open for the process's life */ @Volatile private var speakerSocket: android.os.ParcelFileDescriptor? = null + /** the service started in the foreground, and the modem with it */ fun start(context: Context) { context.startForegroundService( Intent(context, ModemService::class.java).setAction(ACTION_START), ) } + /** the modem stopped, and the service with it */ fun stop(context: Context) { context.startService(Intent(context, ModemService::class.java).setAction(ACTION_STOP)) } @@ -109,8 +111,10 @@ class ModemService : Service() { /** the default network and its addresses the modem started on */ private var netKey: String? = null + /** not bound: started and stopped only */ override fun onBind(intent: Intent?): IBinder? = null + /** the settings' store, and the watches: the bridges kept as their settings say while the modem runs, the notification kept up to date, a pending restart once on hook */ override fun onCreate() { super.onCreate() store = SettingsStore(this) @@ -135,6 +139,7 @@ class ModemService : Service() { } } + /** the notification's Ignore, a stop, or else a start (in the foreground, the modem started off the main thread) */ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { when (intent?.action) { ACTION_IGNORE -> { @@ -157,6 +162,7 @@ class ModemService : Service() { return START_NOT_STICKY } + /** everything let go before the service ends */ override fun onDestroy() { runBlocking(scope.coroutineContext) { shutdown() } scope.cancel() @@ -427,6 +433,7 @@ class ModemService : Service() { } } + /** everything let go, the foreground's notification removed and the service ended */ private fun stopModem() { shutdown() ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) @@ -446,6 +453,7 @@ class ModemService : Service() { ModemState.setRun(ModemState.Run.STOPPED) } + /** [why] logged and shown as the error, the service stopped */ private fun fail(why: String) { log("error: $why") ModemState.setError(why) @@ -453,20 +461,24 @@ class ModemService : Service() { } private val nativeListener = object : NativeModem.Listener { + /** the modem's log line kept (with a word on the local network if Android hasn't allowed it) */ override fun onLog(line: String) { ModemState.log.add(line) // (what Android says when the LAN isn't the app's to reach) if (line.endsWith("Operation not permitted") && !localNetworkAllowed()) log(NO_LOCAL_NETWORK) } + /** the modem's status now */ override fun onStatus(status: NativeModem.Status) { ModemState.setStatus(status) } + /** the modem's speaker on at ATL's [level], or off */ override fun onSpeaker(level: Int) { ModemState.speaker.setLevel(level) } + /** a call's sound to the peer line ([caller]: ours, to [dial]), or turned away when there is no line */ override fun onLine(caller: Boolean, dial: String, line: android.os.ParcelFileDescriptor) { if (settings.noLine) { // (nothing plugged in: a dial gets NO DIALTONE, an answer NO CARRIER) @@ -477,6 +489,7 @@ class ModemService : Service() { com.neodesktop.dmodem.peer.Peers.lineStarted(caller, dial, line) } + /** an exit not ours (not stopping): the service fails with it */ override fun onExit(result: Int) { // (on the modem's thread: stop() waits for it, so nothing that stops here) if (stopping) return @@ -488,18 +501,22 @@ class ModemService : Service() { // the network + /** [net] and its addresses, as one key: a change of either is a new network */ private fun keyOf(net: Network, lp: LinkProperties): String = "$net " + lp.linkAddresses.joinToString(",") { it.address.hostAddress ?: "" } + /** the default network watched (once): its changes to [networkChanged], its loss logged */ private fun watchNetwork() { if (networkCallback != null) return val cm = getSystemService(ConnectivityManager::class.java) val cb = object : ConnectivityManager.NetworkCallback() { + /** the default network's addresses, maybe new: to [networkChanged] */ override fun onLinkPropertiesChanged(network: Network, lp: LinkProperties) { val key = keyOf(network, lp) scope.launch { networkChanged(key) } } + /** the default network gone, logged */ override fun onLost(network: Network) { scope.launch { log("the network ${network} is gone") } } @@ -508,6 +525,7 @@ class ModemService : Service() { networkCallback = cb } + /** the default network no longer watched */ private fun unwatchNetwork() { val cb = networkCallback ?: return networkCallback = null @@ -530,6 +548,7 @@ class ModemService : Service() { // locks + /** the wake lock and the low-latency Wi-Fi lock taken, held until [releaseLocks] */ @android.annotation.SuppressLint("WakelockTimeout") private fun acquireLocks() { if (wakeLock == null) { @@ -551,6 +570,7 @@ class ModemService : Service() { } } + /** the wake and Wi-Fi locks let go */ private fun releaseLocks() { wakeLock?.let { if (it.isHeld) it.release() } wakeLock = null @@ -560,6 +580,7 @@ class ModemService : Service() { // the notification + /** the modem's ongoing notification for [run] and [s], with Stop */ private fun notification(run: ModemState.Run, s: NativeModem.Status): Notification { val text = when { run == ModemState.Run.STARTING -> "Starting…" @@ -616,6 +637,7 @@ class ModemService : Service() { nm.cancel(CALL_NOTIFICATION_ID) return } + /** a pending intent to MainActivity with [action], request code [code] */ fun activity(code: Int, action: String) = PendingIntent.getActivity( this, code, Intent(this, MainActivity::class.java).setAction(action) @@ -651,6 +673,7 @@ class ModemService : Service() { } } + /** [n] the modem's notification now (none if Android won't allow it) */ private fun notify(n: Notification) { try { getSystemService(android.app.NotificationManager::class.java).notify(NOTIFICATION_ID, n) @@ -666,6 +689,7 @@ class ModemService : Service() { checkSelfPermission(android.Manifest.permission.ACCESS_LOCAL_NETWORK) == android.content.pm.PackageManager.PERMISSION_GRANTED + /** [line] to logcat and the app's log */ private fun log(line: String) { Log.i(TAG, line) ModemState.log.add("app: $line") diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/ModemSpeaker.kt b/app/src/main/java/com/neodesktop/dmodem/modem/ModemSpeaker.kt index 9d68e7e..b839af6 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/ModemSpeaker.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemSpeaker.kt @@ -27,9 +27,11 @@ class ModemSpeaker( ) { /** a player: 8000 Hz, 16 bit, mono */ interface Sink { + /** [n] bytes of [pcm] played (may wait for room) */ fun write(pcm: ByteArray, n: Int) /** 0..1 */ fun volume(v: Float) + /** the player let go */ fun close() } @@ -113,14 +115,17 @@ class ModemSpeaker( .apply { play() } } + /** [n] bytes of [pcm] to the track (blocking until there's room) */ override fun write(pcm: ByteArray, n: Int) { track.write(pcm, 0, n) } + /** the track's volume, 0..1 */ override fun volume(v: Float) { track.setVolume(v) } + /** the track stopped, what's left in it dropped, and released */ override fun close() { runCatching { track.pause(); track.flush() } track.release() diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt b/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt index 465dd93..93c2104 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt @@ -60,14 +60,17 @@ object ModemState { /** The text the modem sent the DTE lately (the status screen's console). */ val console = TextBuffer(MAX_CONSOLE) + /** [r] the modem's run now */ internal fun setRun(r: Run) { _run.value = r } + /** [s] the modem's status now */ internal fun setStatus(s: NativeModem.Status) { _status.value = s } + /** [e] the error to show now (null: none) */ internal fun setError(e: String?) { _error.value = e } @@ -90,6 +93,7 @@ class LineBuffer(private val max: Int, private val clock: () -> Long = System::c private val _entries = MutableStateFlow>(emptyList()) val entries: StateFlow> = _entries.asStateFlow() + /** [line] added, stamped with [clock], the oldest dropped past [max] */ @Synchronized fun add(line: String) { lines.addLast(LogLine(clock(), line)) @@ -98,6 +102,7 @@ class LineBuffer(private val max: Int, private val clock: () -> Long = System::c _flow.value = _entries.value.map { it.text } } + /** every line dropped */ @Synchronized fun clear() { lines.clear() @@ -112,6 +117,7 @@ class TextBuffer(private val max: Int) { private val _flow = MutableStateFlow("") val flow: StateFlow = _flow.asStateFlow() + /** [s] added, the oldest characters dropped past [max] */ @Synchronized fun append(s: String) { sb.append(s) @@ -119,6 +125,7 @@ class TextBuffer(private val max: Int) { _flow.value = sb.toString() } + /** the text dropped */ @Synchronized fun clear() { sb.setLength(0) diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt b/app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt index 3de6a11..5cd4203 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt @@ -41,6 +41,7 @@ object UsbModems { /** which of them a USB device with these IDs is, or null */ fun kindOf(vendor: Int, product: Int): Kind? = Kind.entries.firstOrNull { it.vendor == vendor && product in it.products } + /** which of them USB device [d] is, or null */ fun kindOf(d: UsbDevice): Kind? = kindOf(d.vendorId, d.productId) /** the ones plugged in, and which each is; not [gone] (the device name of one just unplugged, which Android may still list) */ @@ -65,6 +66,7 @@ object UsbModems { fun watch(context: Context, log: (String) -> Unit) { for ((d, kind) in plugged(context)) log("USB: ${said(d, kind)}: plugged in") val r = object : BroadcastReceiver() { + /** a modem plugged in or gone, said to [log] (other devices: nothing) */ override fun onReceive(c: Context, i: Intent) { @Suppress("DEPRECATION") val d = i.getParcelableExtra(UsbManager.EXTRA_DEVICE) ?: return @@ -113,6 +115,7 @@ object UsbModems { private suspend fun ask(context: Context, m: UsbManager, dev: UsbDevice): Boolean = suspendCancellableCoroutine { cont -> val receiver = object : BroadcastReceiver() { + /** Android's answer: the question's receiver let go, [cont] resumed with it */ override fun onReceive(c: Context, i: Intent) { runCatching { context.unregisterReceiver(this) } if (cont.isActive) cont.resume(i.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) diff --git a/app/src/main/java/com/neodesktop/dmodem/peer/Peers.kt b/app/src/main/java/com/neodesktop/dmodem/peer/Peers.kt index 9356080..f3cb886 100644 --- a/app/src/main/java/com/neodesktop/dmodem/peer/Peers.kt +++ b/app/src/main/java/com/neodesktop/dmodem/peer/Peers.kt @@ -26,6 +26,7 @@ import com.neodesktop.dmodem.io.asSource class FdDuplex(private val pfd: ParcelFileDescriptor, override val name: String = "modem") : Duplex { override val input: Source = FileInputStream(pfd.fileDescriptor).asSource() override val output: Sink = FileOutputStream(pfd.fileDescriptor).asSink() + /** the socket shut down both ways (waking a blocked read), then closed */ override fun close() { runCatching { Os.shutdown(pfd.fileDescriptor, OsConstants.SHUT_RDWR) } pfd.close() @@ -97,6 +98,7 @@ object Peers { return ok } + /** the line stopped and no longer offered on the network */ @Synchronized fun stop() { line?.stop() @@ -128,9 +130,13 @@ object Peers { setPort(port) } val l = object : NsdManager.RegistrationListener { + /** registered: nothing to do */ override fun onServiceRegistered(i: NsdServiceInfo) {} + /** not registered: nothing to do (the line still takes calls by address) */ override fun onRegistrationFailed(i: NsdServiceInfo, code: Int) {} + /** unregistered: nothing to do */ override fun onServiceUnregistered(i: NsdServiceInfo) {} + /** not unregistered: nothing to do */ override fun onUnregistrationFailed(i: NsdServiceInfo, code: Int) {} } runCatching { m.registerService(info, NsdManager.PROTOCOL_DNS_SD, l) }.onSuccess { nsd = l } @@ -145,19 +151,28 @@ class PeerFinder(context: Context, private val found: (String, String) -> Unit) private val nsd = context.applicationContext.getSystemService(NsdManager::class.java) private var listener: NsdManager.DiscoveryListener? = null + /** the search started: each phone found resolved, then to [found] */ fun start() { val m = nsd ?: return val l = object : NsdManager.DiscoveryListener { + /** started: nothing to do */ override fun onDiscoveryStarted(type: String) {} + /** stopped: nothing to do */ override fun onDiscoveryStopped(type: String) {} + /** not started: nothing found */ override fun onStartDiscoveryFailed(type: String, code: Int) {} + /** not stopped: nothing to do */ override fun onStopDiscoveryFailed(type: String, code: Int) {} + /** one gone: left in the list (nothing to do) */ override fun onServiceLost(info: NsdServiceInfo) {} + /** one found: resolved, for its address */ override fun onServiceFound(info: NsdServiceInfo) { @Suppress("DEPRECATION") runCatching { m.resolveService(info, object : NsdManager.ResolveListener { + /** not resolved: left out */ override fun onResolveFailed(i: NsdServiceInfo, code: Int) {} + /** its host (bracketed, if IPv6) and port to [found], with its name */ override fun onServiceResolved(i: NsdServiceInfo) { @Suppress("DEPRECATION") val host = i.host?.hostAddress ?: return @@ -171,6 +186,7 @@ class PeerFinder(context: Context, private val found: (String, String) -> Unit) runCatching { m.discoverServices(TcpPeerTransport.SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, l) }.onSuccess { listener = l } } + /** the search stopped */ fun stop() { listener?.let { l -> runCatching { nsd?.stopServiceDiscovery(l) } } listener = null diff --git a/app/src/main/java/com/neodesktop/dmodem/peer/Transports.kt b/app/src/main/java/com/neodesktop/dmodem/peer/Transports.kt index ebe9a4a..33cc0fa 100644 --- a/app/src/main/java/com/neodesktop/dmodem/peer/Transports.kt +++ b/app/src/main/java/com/neodesktop/dmodem/peer/Transports.kt @@ -23,6 +23,7 @@ class SocketDuplex(private val socket: Socket, override val name: String = socke init { runCatching { socket.tcpNoDelay = true } } override val input: Source = socket.getInputStream().asSource() override val output: Sink = socket.getOutputStream().asSink() + /** the connection closed */ override fun close() = socket.close() } @@ -41,6 +42,7 @@ class TcpPeerTransport( /** the port listened on (with port 0: the one given) */ val localPort: Int get() = server?.localPort ?: port + /** calls taken on [port] (every address, or [bindTo]): each to [accept] on a thread of its own */ override fun listen(accept: (Duplex) -> Unit) { val s = ServerSocket() s.reuseAddress = true @@ -54,6 +56,7 @@ class TcpPeerTransport( }, "peer-listen").apply { isDaemon = true; start() } } + /** a call to [address] (`host[:port]`, [port] if none), 10 s to connect */ override fun connect(address: String): Duplex { val (host, p) = parse(address, port) val s = Socket() @@ -66,6 +69,7 @@ class TcpPeerTransport( return SocketDuplex(s, address) } + /** no more calls taken (the listening socket closed) */ override fun close() { runCatching { server?.close() } server = null @@ -111,9 +115,11 @@ class BluetoothPeerTransport(private val context: Context) : PeerTransport { override val input: Source = s.inputStream.asSource() override val output: Sink = s.outputStream.asSink() override val name: String = runCatching { s.remoteDevice?.let { it.name ?: it.address } }.getOrNull() ?: "Bluetooth" + /** the RFCOMM connection closed */ override fun close() = s.close() } + /** calls taken on our RFCOMM service: each to [accept] on a thread of its own; IOException if there's no Bluetooth, or it's off */ override fun listen(accept: (Duplex) -> Unit) { val a = adapter ?: throw IOException("this phone has no Bluetooth") if (!a.isEnabled) throw IOException("Bluetooth is off") @@ -127,6 +133,7 @@ class BluetoothPeerTransport(private val context: Context) : PeerTransport { }, "peer-listen").apply { isDaemon = true; start() } } + /** a call to the paired phone at Bluetooth [address], on our RFCOMM service */ override fun connect(address: String): Duplex { val a = adapter ?: throw IOException("this phone has no Bluetooth") if (!a.isEnabled) throw IOException("Bluetooth is off") @@ -141,6 +148,7 @@ class BluetoothPeerTransport(private val context: Context) : PeerTransport { return BtDuplex(s) } + /** no more calls taken (the server socket closed) */ override fun close() { runCatching { server?.close() } server = null diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/DialIn.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/DialIn.kt index e0ca4a1..57f7217 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ppp/DialIn.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ppp/DialIn.kt @@ -72,6 +72,7 @@ object DialIn { private var watching = false private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + /** [s] to the app's log, as dial-in's */ private fun log(s: String) = ModemState.log.add("dial-in: $s") /** the settings watched, the modem's calls too (the app's start) */ @@ -110,6 +111,7 @@ object DialIn { /** the modem's line being read (its results come in pieces) */ private val line = StringBuilder() + /** the modem's [n] octets of [data], read a line at a time: at a caller's CONNECT, its PPP started on what follows */ private fun modemText(data: ByteArray, n: Int) { if (!enabled) { line.setLength(0) @@ -173,6 +175,7 @@ object DialIn { /** the caller's bytes so far, each way (in, out) */ fun bytes(): Pair = call?.ppp?.let { it.bytesIn to it.bytesOut } ?: (0L to 0L) + /** the last call's state cleared, unless one is going */ fun dismiss() { if (call == null) _state.value = null } @@ -183,6 +186,7 @@ object DialIn { var ppp: Ppp? = null var nat: NatStack? = null + /** the DTE claimed and the call's PPP server and NAT started ([first] its first input): false if the modem is someone else's */ fun begin(first: ByteArray): Boolean { val hub = ModemState.dte listener = TerminalLink.Listener { d, n -> ppp?.input(d, 0, n) } @@ -193,16 +197,20 @@ object DialIn { val p = Ppp( send = { b -> hub.writeAs(listener, b) }, events = object : Ppp.Events { + /** the caller online: the NAT's MSS from the link's MTU, the state Online */ override fun up(config: Ppp.IpConfig) { n.mss = config.mtu - 40 DialIn.log("the caller is online: ${peer.hostAddress}") _state.value = State("Online", connectLine, online = true, since = System.currentTimeMillis()) } + /** the caller's IP packet to the NAT */ override fun ip(packet: ByteArray) = n.input(packet) + /** PPP down: the call ended (off PPP's thread) */ override fun down(reason: String) { // (off PPP's thread: the hang-up waits out the guard times) Thread { end(reason) }.start() } + /** PPP's [line] to the log */ override fun log(line: String) = DialIn.log("ppp: $line") }, server = Ppp.Server(local, peer, local), @@ -237,6 +245,7 @@ object DialIn { finish(why) } + /** the call's end logged and shown, the DTE released */ private fun finish(why: String) { log("over: $why") ModemState.dte.release(listener) diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/Internet.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/Internet.kt index c2c0ddd..e61d123 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ppp/Internet.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ppp/Internet.kt @@ -32,6 +32,7 @@ object Internet { interface Tunnel { /** a packet from the link */ fun write(packet: ByteArray) + /** the tunnel let go (the link's down) */ fun close() } @@ -63,6 +64,7 @@ object Internet { val running: Boolean get() = _state.value?.running == true + /** the state changed by [f], if there is one */ private fun set(f: (State) -> State) { _state.value = _state.value?.let(f) } @@ -121,6 +123,7 @@ object Internet { user = isp.user, password = isp.password, events = object : Ppp.Events { + /** the link has its address: the tunnel opened on it, or PPP stopped if it can't be */ override fun up(config: Ppp.IpConfig) { val t = try { openTunnel(config) } catch (e: Exception) { null } if (t == null) { @@ -131,11 +134,14 @@ object Internet { tunnel = t set { it.copy(phase = "", config = config, since = System.currentTimeMillis()) } } + /** a packet from the link to the tunnel */ override fun ip(packet: ByteArray) { tunnel?.write(packet) } + /** PPP down: [reason] kept (unless there's one already), the call let end */ override fun down(reason: String) { if (why == null) why = reason done.countDown() } + /** PPP's [line] to the log */ override fun log(line: String) { ModemState.log.add("ppp: $line") } }, ) @@ -191,6 +197,7 @@ object Internet { _state.value = s } + /** the last link's state cleared, unless one is going */ fun dismiss() { if (!running) _state.value = null } @@ -214,6 +221,7 @@ object Internet { } } + /** why a dial ended with result [r], in a word for the user */ private fun dialResult(r: String?) = when (r) { null -> "no answer" "BUSY" -> "busy" diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/NatStack.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/NatStack.kt index 6fe1c42..f16adc9 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ppp/NatStack.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ppp/NatStack.kt @@ -51,6 +51,7 @@ class NatStack( timer.scheduleWithFixedDelay({ tick() }, 250, 250, TimeUnit.MILLISECONDS) } + /** every connection and flow ended (TCP's aborted), the timer and workers stopped */ fun close() { closed = true tcp.values.forEach { it.abort() } @@ -62,6 +63,7 @@ class NatStack( val connections: Int get() = tcp.size + udp.size + /** packet [p] to the computer, unless closed */ private fun send(p: ByteArray) { if (!closed) runCatching { toClient(p) } } @@ -84,8 +86,11 @@ class NatStack( } } + /** the big-endian 16-bit value at [i] of [b] */ private fun u16(b: ByteArray, i: Int) = ((b[i].toInt() and 0xff) shl 8) or (b[i + 1].toInt() and 0xff) + /** the big-endian 32-bit value at [i] of [b] */ private fun u32(b: ByteArray, i: Int) = (u16(b, i) shl 16) or u16(b, i + 2) + /** the address of [b]'s four octets */ private fun addr(b: ByteArray) = InetAddress.getByAddress(b) // ------------------------------------------------------------------ @@ -122,9 +127,11 @@ class NatStack( runCatching { socket.send(DatagramPacket(payload, payload.size, to)) } } + /** the flow's socket closed */ fun close() = runCatching { socket.close() } } + /** a UDP datagram from the computer: to its flow (made for a new one); to the gateway only DNS */ private fun udpIn(src: ByteArray, dst: ByteArray, b: ByteArray) { if (b.size < 8) return val sport = u16(b, 0) @@ -145,6 +152,7 @@ class NatStack( // ------------------------------------------------------------------ // ICMP: echo + /** an echo request from the computer: answered for the gateway, else if the phone can reach the host */ private fun icmpIn(src: ByteArray, dst: ByteArray, b: ByteArray) { if (b.size < 8 || b[0].toInt() != 8) return val rest = b.copyOfRange(4, b.size) @@ -181,16 +189,20 @@ class NatStack( val toSocket = LinkedBlockingQueue() val lock = Object() + /** a segment to the computer with [flags], [seq] and [data] (an MSS option if [mssOpt]), acknowledging [rcvNxt] */ fun seg(flags: Int, seq: Int, data: ByteArray = ByteArray(0), mssOpt: Int = 0) = send(Ip.tcp(dst, client, dport, cport, seq, rcvNxt, flags, window(), data, mssOpt)) + /** the window offered the computer: what's free of 64K queued for the socket */ fun window(): Int = (65535 - toSocket.sumOf { it.size }).coerceIn(0, 65535) + /** the SYN-ACK to the computer, with our MSS */ fun synAck() { seg(Ip.SYN or Ip.ACK, iss, mssOpt = mss) lastSent = System.currentTimeMillis() } + /** the connection over at once: its socket closed, its writer woken to end, forgotten */ fun abort() { st = St.CLOSED runCatching { socket?.close() } @@ -199,6 +211,7 @@ class NatStack( tcp.remove(key) } + /** a reset to the computer, and the connection aborted */ fun reset() { seg(Ip.RST or Ip.ACK, sndNxt) abort() @@ -264,6 +277,7 @@ class NatStack( } } + /** a TCP segment from the computer: to its connection, a SYN opening a new one, anything else reset */ private fun tcpIn(src: ByteArray, dst: ByteArray, b: ByteArray) { if (b.size < 20) return val sport = u16(b, 0) diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/PppHost.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/PppHost.kt index d13831d..7e73960 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ppp/PppHost.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ppp/PppHost.kt @@ -52,15 +52,20 @@ class PppHost( /** whether the computer has its address (the link up) */ val online: StateFlow = _online.asStateFlow() + /** [l] hears what the host says to the computer */ override fun addListener(l: TerminalLink.Listener) { listeners.add(l) } + /** [l] no longer hears the host */ override fun removeListener(l: TerminalLink.Listener) { listeners.remove(l) } + /** [b] to the computer (every listener) */ private fun say(b: ByteArray) { for (l in listeners) l.onData(b, b.size) } + /** [s] (ISO-8859-1) to the computer */ private fun say(s: String) = say(s.toByteArray(Charsets.ISO_8859_1)) + /** result code [s] to the computer, framed as V1 or V0 says */ private fun result(s: String) = say(if (verbose) "\r\n$s\r\n" else "$s\r") /** the computer's octets */ @@ -97,6 +102,7 @@ class PppHost( return true } + /** the computer's command line [l]: E, V, Z and &F kept; a dial or ATA brings up PPP, CLIENT too (a direct cable connection); I answered; else OK */ private fun command(l: String) { val u = l.uppercase() when { @@ -126,18 +132,22 @@ class PppHost( } } + /** the PPP server and its NAT started, if not already */ private fun startPpp() { if (ppp != null) return lateinit var n: NatStack val p = Ppp( send = { b -> say(b) }, events = object : Ppp.Events { + /** the computer has its address: the NAT's MSS from the link's MTU, online */ override fun up(config: Ppp.IpConfig) { n.mss = config.mtu - 40 log("the computer is online: ${peer.hostAddress}") _online.value = true } + /** the computer's IP packet to the NAT */ override fun ip(packet: ByteArray) = n.input(packet) + /** the link down: the NAT closed, offline, NO CARRIER to the computer */ override fun down(reason: String) { log("the computer's link down: $reason") synchronized(lock) { @@ -150,6 +160,7 @@ class PppHost( } } } + /** PPP's [line] to the host's log */ override fun log(line: String) = this@PppHost.log("ppp: $line") }, server = Ppp.Server(local, peer, local), @@ -165,6 +176,7 @@ class PppHost( ppp?.stop("the computer hung up") } + /** the link hung up, the NAT closed, the link closed */ override fun close() { hangUp() nat?.close() diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/PppVpnService.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/PppVpnService.kt index bbae084..fc67e08 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ppp/PppVpnService.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ppp/PppVpnService.kt @@ -24,12 +24,14 @@ class PppVpnService : VpnService() { @Volatile private var out: FileOutputStream? = null private var reader: Thread? = null + /** the service is the one [open] uses, and ready */ override fun onCreate() { super.onCreate() instance = this ready.countDown() } + /** ACTION_STOP: the VPN closed and the service ended; anything else: nothing (it's started to be there) */ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent?.action == ACTION_STOP) { close() @@ -38,6 +40,7 @@ class PppVpnService : VpnService() { return START_NOT_STICKY } + /** the VPN taken away (the user's, or another's): the call hung up, the interface closed */ override fun onRevoke() { // the user turned the VPN off (or another took over): the call hung up Internet.disconnect() @@ -45,6 +48,7 @@ class PppVpnService : VpnService() { super.onRevoke() } + /** the interface closed, the service forgotten (the next start waits for a new one) */ override fun onDestroy() { close() if (instance === this) instance = null @@ -52,6 +56,7 @@ class PppVpnService : VpnService() { super.onDestroy() } + /** the VPN's interface for [cfg] (all IPv4, the app itself left out), its packets read to the link: its tunnel, null if Android won't establish it */ private fun open(cfg: Ppp.IpConfig): Internet.Tunnel? { close() val b = Builder() @@ -78,10 +83,12 @@ class PppVpnService : VpnService() { } }, "vpn-reader").apply { isDaemon = true; start() } return object : Internet.Tunnel { + /** a packet from the link to the interface */ override fun write(packet: ByteArray) { runCatching { out?.write(packet) } } + /** the interface closed and the service ended */ override fun close() { this@PppVpnService.close() stopSelf() @@ -89,6 +96,7 @@ class PppVpnService : VpnService() { } } + /** the interface closed, its reader let end */ private fun close() { runCatching { pfd?.close() } pfd = null diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/AppearanceSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/AppearanceSettings.kt index 3f814a0..22edffa 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/AppearanceSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/AppearanceSettings.kt @@ -52,6 +52,7 @@ class AppearanceStore(private val context: Context) { val lightsOnTop = booleanPreferencesKey("lights_on_top") } + /** the appearance stored in [p], the defaults for what isn't (or isn't known) */ private fun from(p: Preferences): Appearance { val d = Appearance() return Appearance( @@ -75,6 +76,7 @@ class AppearanceStore(private val context: Context) { } } + /** [a] stored as it is */ suspend fun save(a: Appearance) { context.appearanceStore.edit { p -> p[K.dark] = a.dark.name diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt index f886739..63054cf 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt @@ -70,6 +70,7 @@ class BridgeSettingsStore(private val context: Context) { val settings: Flow = context.bridgeStore.data.map { from(it) } + /** the bridges' settings stored in [p], the defaults for what isn't */ private fun from(p: Preferences): BridgeSettings { val d = BridgeSettings() return BridgeSettings( @@ -91,6 +92,7 @@ class BridgeSettingsStore(private val context: Context) { ) } + /** what's stored now */ suspend fun current(): BridgeSettings = settings.first() /** a change made to what's stored now (two quick changes don't undo each other) */ @@ -98,10 +100,12 @@ class BridgeSettingsStore(private val context: Context) { context.bridgeStore.edit { p -> write(p, change(from(p))) } } + /** [s] stored as it is */ suspend fun save(s: BridgeSettings) { context.bridgeStore.edit { p -> write(p, s) } } + /** [s] into [p] (the TCP port kept in range, the Bluetooth address trimmed) */ private fun write(p: androidx.datastore.preferences.core.MutablePreferences, s: BridgeSettings) { run { p[K.tcp] = s.tcp diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/FaxSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/FaxSettings.kt index 94c5cd1..ece05ab 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/FaxSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/FaxSettings.kt @@ -40,6 +40,7 @@ class FaxSettingsStore(private val context: Context) { val ecm = booleanPreferencesKey("ecm") } + /** the fax settings stored in [p], the defaults for what isn't */ private fun read(p: Preferences): FaxSettings { val d = FaxSettings() return FaxSettings(p[K.ident] ?: d.ident, p[K.answer] ?: d.answer, p[K.maxBps] ?: d.maxBps, p[K.fine] ?: d.fine, p[K.ecm] ?: d.ecm) @@ -47,8 +48,10 @@ class FaxSettingsStore(private val context: Context) { val settings: Flow = context.faxStore.data.map { p -> read(p) } + /** what's stored now */ suspend fun current(): FaxSettings = settings.first() + /** a change made to what's stored now (two quick changes don't undo each other) */ suspend fun update(change: (FaxSettings) -> FaxSettings) { context.faxStore.edit { p -> val s = change(read(p)) @@ -56,6 +59,7 @@ class FaxSettingsStore(private val context: Context) { } } + /** [s] into [p] (the ident only digits, + and spaces, 20 at most) */ private fun write(p: MutablePreferences, s: FaxSettings) { p[K.ident] = s.ident.filter { it.isDigit() || it == '+' || it == ' ' }.take(20) p[K.answer] = s.answer diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/IspSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/IspSettings.kt index 2c31a4d..bd3d974 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/IspSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/IspSettings.kt @@ -43,8 +43,10 @@ class IspSettingsStore(private val context: Context) { IspSettings(p[K.number] ?: "", p[K.user] ?: "", p[K.password] ?: "", p[K.init] ?: "", p[K.script] ?: "", p[K.dialIn] ?: false) } + /** what's stored now */ suspend fun current(): IspSettings = settings.first() + /** [s] stored (the number, user, init commands and script trimmed) */ suspend fun save(s: IspSettings) { context.ispStore.edit { p -> p[K.number] = s.number.trim() diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt index cab861e..b672f51 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt @@ -201,8 +201,10 @@ class SettingsStore(private val context: Context) { ) } + /** what's stored now */ suspend fun current(): ModemSettings = settings.first() + /** [s] stored (addresses and names trimmed, the USB gain kept in -20..20) */ suspend fun save(s: ModemSettings) { context.dataStore.edit { p -> p[Keys.user] = s.user.trim() diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/TerminalSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/TerminalSettings.kt index 7f501d9..472c9e4 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/TerminalSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/TerminalSettings.kt @@ -89,11 +89,13 @@ class TerminalSettingsStore(private val context: Context) { val drawBoxes = booleanPreferencesKey("draw_boxes") } + /** the [E] named [s], or [d] for none or one not known */ private inline fun > enumOf(s: String?, d: E): E = s?.let { runCatching { enumValueOf(it) }.getOrNull() } ?: d val settings: Flow = context.terminalStore.data.map { from(it) } + /** the terminal's settings stored in [p], the defaults for what isn't */ private fun from(p: Preferences): TerminalSettings { val d = TerminalSettings() return TerminalSettings( @@ -120,6 +122,7 @@ class TerminalSettingsStore(private val context: Context) { ) } + /** what's stored now */ suspend fun current(): TerminalSettings = settings.first() /** one change made to what is saved now (not to a copy that may be behind: changes in quick succession) */ @@ -127,10 +130,12 @@ class TerminalSettingsStore(private val context: Context) { context.terminalStore.edit { p -> write(p, change(from(p))) } } + /** [s] stored as it is */ suspend fun save(s: TerminalSettings) { context.terminalStore.edit { p -> write(p, s) } } + /** [s] into [p], enums by name */ private fun write(p: MutablePreferences, s: TerminalSettings) { p[K.theme] = s.themeId p[K.font] = s.font.name @@ -154,10 +159,12 @@ class TerminalSettingsStore(private val context: Context) { p[K.drawBoxes] = s.drawBoxes } + /** the font size [sp] stored alone (the pinch's) */ suspend fun setFontSize(sp: Float) { context.terminalStore.edit { it[K.fontSize] = sp } } + /** the fixed columns [n] stored alone */ suspend fun setFixedColumns(n: Int) { context.terminalStore.edit { it[K.fixedColumns] = n } } diff --git a/app/src/main/java/com/neodesktop/dmodem/ssh/Agent.kt b/app/src/main/java/com/neodesktop/dmodem/ssh/Agent.kt index 52633a1..4c25e10 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ssh/Agent.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ssh/Agent.kt @@ -38,6 +38,7 @@ class AgentKeys( */ class AgentServer(private val keys: AgentKeys, private val owner: Any = Unit, private val log: (String) -> Unit = {}) { + /** requests read from [i] and answered on [o], each length-prefixed, until the stream ends (or a message is too long) */ fun serve(i: InputStream, o: OutputStream) { val d = DataInputStream(i) try { @@ -67,6 +68,7 @@ class AgentServer(private val keys: AgentKeys, private val owner: Any = Unit, pr FAILURE } + /** the keys' list: each key's blob and name */ private fun identities(): ByteArray { val ks = keys.list() val r = Buffer.PlainBuffer().putByte(IDENTITIES_ANSWER.toByte()).putUInt32(ks.size.toLong()) @@ -74,6 +76,7 @@ class AgentServer(private val keys: AgentKeys, private val owner: Any = Unit, pr return r.compactData } + /** [data] signed with the key whose blob is [blob] (RSA's hash as [flags] ask), once confirmed: the response, or FAILURE */ private fun sign(blob: ByteArray, data: ByteArray, flags: Int): ByteArray { val (name, kp) = keys.list().firstOrNull { KeyFormat.blob(it.second.public).contentEquals(blob) } ?: return FAILURE if (keys.confirm?.invoke(name, owner) == false) { @@ -97,6 +100,7 @@ class AgentServer(private val keys: AgentKeys, private val owner: Any = Unit, pr return Buffer.PlainBuffer().putByte(SIGN_RESPONSE.toByte()).putBytes(inner).compactData } + /** a signature of algorithm [alg], from sshj's key algorithms */ private fun signature(alg: String): Signature { val f = DefaultConfig().keyAlgorithms.firstOrNull { it.name == alg } ?: throw IOException("no $alg signatures") return f.create().newSignature() @@ -134,6 +138,7 @@ class AgentForwarder(conn: Connection, private val server: AgentServer) : private class AgentChannel(conn: Connection, recipient: Int, window: Long, maxPacket: Long) : AbstractForwardedChannel(conn, TYPE, recipient, window, maxPacket, "", 0) + /** the server's agent channel opened: confirmed and served, on the listener's thread */ override fun handleOpen(buf: SSHPacket) { val ch = AgentChannel(conn, buf.readUInt32AsInt(), buf.readUInt32(), buf.readUInt32()) callListener( diff --git a/app/src/main/java/com/neodesktop/dmodem/ssh/Forwarding.kt b/app/src/main/java/com/neodesktop/dmodem/ssh/Forwarding.kt index 2d208e9..cec4c65 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ssh/Forwarding.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ssh/Forwarding.kt @@ -39,6 +39,7 @@ data class ForwardSpec( DYNAMIC('D', "SOCKS proxy"), } + /** the spec as its line, the one [parse] reads ("L 8080:db:5432") */ override fun toString(): String { val b = bind?.let { (if (it.contains(':')) "[$it]" else it) + ":" } ?: "" val to = if (type == Type.DYNAMIC) "" else ":" + (if (host.contains(':')) "[$host]" else host) + ":$hostPort" @@ -62,6 +63,7 @@ data class ForwardSpec( if (s.isEmpty()) return null val type = Type.entries.firstOrNull { it.flag == s[0].uppercaseChar() } ?: return null val parts = split(s.substring(1).trim()) ?: return null + /** [p] as a port, 0..65535, or null */ fun port(p: String) = p.toIntOrNull()?.takeIf { it in 0..65535 } return when (type) { Type.DYNAMIC -> when (parts.size) { @@ -139,6 +141,7 @@ class Forwards( @Volatile private var closed = false + /** the state of [spec]'s forward changed by [f] */ private fun set(spec: ForwardSpec, f: (ForwardState) -> ForwardState) = _states.update { l -> l.map { if (it.spec == spec) f(it) else it } } @@ -168,6 +171,7 @@ class Forwards( _states.update { l -> l.filter { it.spec != spec } } } + /** every forward stopped, their states kept as not listening; no more started */ @Synchronized override fun close() { closed = true @@ -176,6 +180,7 @@ class Forwards( _states.update { l -> l.map { it.copy(listening = false) } } } + /** a local or SOCKS forward's socket bound (loopback unless [ForwardSpec.bind] says, "*" every address), each connection served on a thread of its own: the socket, to close it */ private fun listen(spec: ForwardSpec): Closeable { val addr = InetAddress.getByName(spec.bind?.takeIf { it != "*" && it != "localhost" } ?: if (spec.bind == "*") "0.0.0.0" else "127.0.0.1") val server = ServerSocket() @@ -195,6 +200,7 @@ class Forwards( return server } + /** a connection to a local or SOCKS forward: its channel from the server (SOCKS's to where its client asks), spliced to it, counted while open */ private fun serve(spec: ForwardSpec, s: Socket) { counted(spec) { s.use { @@ -221,6 +227,7 @@ class Forwards( } } + /** the server asked to listen for a remote forward, each connection to host:hostport from here: its cancel */ private fun remote(spec: ForwardSpec): Closeable { val rpf = client.remotePortForwarder val listener = ConnectListener { ch -> @@ -242,6 +249,7 @@ class Forwards( return Closeable { runCatching { rpf.cancel(bound) } } } + /** [body] run as one of [spec]'s connections: counted open while it runs, and in the total */ private inline fun counted(spec: ForwardSpec, body: () -> Unit) { set(spec) { it.copy(open = it.open + 1, total = it.total + 1) } try { @@ -252,6 +260,7 @@ class Forwards( } companion object { + /** [body] run on a daemon thread named [name] */ fun thread(name: String, body: () -> Unit) = Thread(body, name).apply { isDaemon = true }.start() /** both ways between a socket and a channel, until either ends */ @@ -265,6 +274,7 @@ class Forwards( up.join(30_000) } + /** [i] copied to [o] until it ends (or fails) */ private fun copy(i: InputStream, o: OutputStream) { val buf = ByteArray(32 * 1024) try { @@ -295,6 +305,7 @@ object Socks { } } + /** a SOCKS 4/4a request read (the version read already) and, a CONNECT, [open]ed; granted or refused: what was opened */ private fun socks4(d: java.io.DataInputStream, o: OutputStream, open: (String, Int) -> T?): T? { val cmd = d.readUnsignedByte() val port = d.readUnsignedShort() @@ -312,6 +323,7 @@ object Socks { return ch } + /** a NUL-terminated string (255 characters at most) */ private fun cstring(d: java.io.DataInputStream): String { val b = java.io.ByteArrayOutputStream() while (true) { @@ -323,6 +335,7 @@ object Socks { return b.toString(Charsets.ISO_8859_1.name()) } + /** a SOCKS 5 greeting (no authentication only) and request read (the version read already), a CONNECT [open]ed: what was opened, or null */ private fun socks5(d: java.io.DataInputStream, o: OutputStream, open: (String, Int) -> T?): T? { val n = d.readUnsignedByte() val methods = ByteArray(n).also { d.readFully(it) } @@ -348,6 +361,7 @@ object Socks { return reply5(o, if (ch != null) 0 else 5, ch) } + /** SOCKS 5 reply [code] written (an IPv4 bound address of zeros): [ch], passed back */ private fun reply5(o: OutputStream, code: Int, ch: T?): T? { o.write(byteArrayOf(5, code.toByte(), 0, 1, 0, 0, 0, 0, 0, 0)) o.flush() diff --git a/app/src/main/java/com/neodesktop/dmodem/ssh/KeyGen.kt b/app/src/main/java/com/neodesktop/dmodem/ssh/KeyGen.kt index b638f55..34ff57c 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ssh/KeyGen.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ssh/KeyGen.kt @@ -41,6 +41,7 @@ object KeyGen { else -> "ED25519" } + /** the SHA-256 of the key's blob (its fingerprint's digest) */ fun sha256(k: PublicKey): ByteArray = MessageDigest.getInstance("SHA-256").digest(KeyFormat.blob(k)) /** MD5:xx:xx:... (as ssh-keygen -E md5) */ @@ -50,6 +51,7 @@ object KeyGen { /** the "drunken bishop" picture of the SHA256 fingerprint, as ssh-keygen -lv draws it */ fun randomart(k: PublicKey): String = randomart(sha256(k), "[${typeName(k)} ${bits(k)}]", "[SHA256]") + /** the "drunken bishop" picture of [digest], [title] on its top border and [hashName] on its bottom */ fun randomart(digest: ByteArray, title: String, hashName: String): String { val w = 17 val h = 9 @@ -71,6 +73,7 @@ object KeyGen { } field[w / 2][h / 2] = len - 1 field[x][y] = len + /** a border line of the picture's width, [label] in its middle */ fun border(label: String): String { val sb = StringBuilder("+") val left = (w - label.length) / 2 @@ -129,6 +132,7 @@ object KeyGen { return "-----BEGIN OPENSSH PRIVATE KEY-----\n$b64\n-----END OPENSSH PRIVATE KEY-----\n" } + /** the key's type and private fields into [b], as OpenSSH's private key section has them (RSA, ECDSA or Ed25519) */ private fun privateFields(kp: KeyPair, b: Buffer.PlainBuffer) { val type = KeyFormat.type(kp.public) b.putString(type) diff --git a/app/src/main/java/com/neodesktop/dmodem/ssh/Keys.kt b/app/src/main/java/com/neodesktop/dmodem/ssh/Keys.kt index 3ecd171..8c654cb 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ssh/Keys.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ssh/Keys.kt @@ -55,13 +55,17 @@ data class SshKey( /** The public key's SSH form and its fingerprint (SHA256:..., as ssh-keygen -l). */ object KeyFormat { + /** the key in SSH's wire form (its type, then its fields) */ fun blob(k: PublicKey): ByteArray = Buffer.PlainBuffer().putPublicKey(k).compactData + /** the key's SSH type: ssh-ed25519, ecdsa-sha2-nistp256, ssh-rsa... */ fun type(k: PublicKey): String = KeyType.fromKey(k).toString() + /** the key's authorized_keys line: its type, its blob in base64, and [comment] if any */ fun openSsh(k: PublicKey, comment: String = ""): String = type(k) + " " + Base64.getEncoder().encodeToString(blob(k)) + if (comment.isNotEmpty()) " $comment" else "" + /** the key's fingerprint, SHA256: and its blob's digest in unpadded base64 */ fun fingerprint(k: PublicKey): String = "SHA256:" + Base64.getEncoder().withoutPadding().encodeToString(MessageDigest.getInstance("SHA-256").digest(blob(k))) } @@ -94,6 +98,7 @@ class SshKeys(private val dir: File, private val box: SecretBox) { } } + /** [list] written to keys.json and the keys now */ @Synchronized private fun saveIndex(list: List) { val a = JSONArray() @@ -126,7 +131,9 @@ class SshKeys(private val dir: File, private val box: SecretBox) { fun import(text: String, passphrase: String?, name: String): SshKey { SshSecurity.ensure() val finder = object : PasswordFinder { + /** [passphrase] for the key (none: empty) */ override fun reqPassword(resource: Resource<*>?): CharArray = (passphrase ?: "").toCharArray() + /** asked once: a wrong passphrase isn't asked again */ override fun shouldRetry(resource: Resource<*>?) = false } val provider: KeyProvider = when { @@ -139,6 +146,7 @@ class SshKeys(private val dir: File, private val box: SecretBox) { return keep(KeyPair(provider.public, provider.private), name, if (Ppk.isPpk(text)) Ppk.comment(text)?.takeIf { it.isNotBlank() } else null) } + /** [given] kept: its private half sealed in its own file (an RSA one made whole first), its entry added */ private fun keep(given: KeyPair, name: String, comment: String? = null): SshKey { val pair = withCrt(given) val id = UUID.randomUUID().toString() @@ -236,16 +244,20 @@ class SshKeys(private val dir: File, private val box: SecretBox) { ) } + /** the key as sshj's key provider, for authentication */ fun provider(id: String): KeyProvider = KeyPairWrapper(keyPair(id)) + /** the key's name changed to [name] */ fun rename(id: String, name: String) { saveIndex(_keys.value.map { if (it.id == id) it.copy(name = name) else it }) } + /** the key's sealed file deleted and its entry gone */ fun delete(id: String) { File(dir, "$id.key").delete() saveIndex(_keys.value.filter { it.id != id }) } + /** the key with [id], or null */ fun byId(id: String): SshKey? = _keys.value.firstOrNull { it.id == id } } diff --git a/app/src/main/java/com/neodesktop/dmodem/ssh/KnownHosts.kt b/app/src/main/java/com/neodesktop/dmodem/ssh/KnownHosts.kt index 26b0280..6b8c604 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ssh/KnownHosts.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ssh/KnownHosts.kt @@ -17,8 +17,10 @@ import java.util.Base64 class KnownHosts(private val file: File, private val ask: (Prompt.HostKey, Any?) -> Answer) : HostKeyVerifier { + /** the host as known_hosts names it: bare on port 22, else "[host]:port" */ private fun hostPart(host: String, port: Int) = if (port == 22) host else "[$host]:$port" + /** the file's lines, blank ones left out (none if there's no file) */ @Synchronized private fun lines(): List = if (file.exists()) file.readLines().filter { it.isNotBlank() } else emptyList() @@ -32,6 +34,7 @@ class KnownHosts(private val file: File, private val ask: (Prompt.HostKey, Any?) } } + /** [key] kept for the host, in place of a key of its type kept before */ @Synchronized fun keep(host: String, port: Int, key: PublicKey) { val hp = hostPart(host, port) @@ -60,6 +63,7 @@ class KnownHosts(private val file: File, private val ask: (Prompt.HostKey, Any?) }.joinToString("\n", postfix = "\n")) } + /** every key kept for the host gone */ @Synchronized fun forget(host: String, port: Int) { val hp = hostPart(host, port) @@ -67,6 +71,7 @@ class KnownHosts(private val file: File, private val ask: (Prompt.HostKey, Any?) .joinToString("\n", postfix = "\n")) } + /** [verify] with no owner for the question */ override fun verify(hostname: String, port: Int, key: PublicKey): Boolean = verify(hostname, port, key, null) /** verify(), the question (if any) asked as [owner]'s: the connection's */ @@ -91,6 +96,7 @@ class KnownHosts(private val file: File, private val ask: (Prompt.HostKey, Any?) override fun findExistingAlgorithms(hostname: String, port: Int): List = keysFor(hostname, port).map { it.first }.distinct() + /** the SHA256 fingerprint of a key kept in base64, or "(unreadable)" */ private fun fingerprintOf(b64: String): String = try { val key = Buffer.PlainBuffer(Base64.getDecoder().decode(b64)).readPublicKey() KeyFormat.fingerprint(key) diff --git a/app/src/main/java/com/neodesktop/dmodem/ssh/Ppk.kt b/app/src/main/java/com/neodesktop/dmodem/ssh/Ppk.kt index fe5bc71..e71ed53 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ssh/Ppk.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ssh/Ppk.kt @@ -29,12 +29,14 @@ object Ppk { /** PuTTYgen's Argon2 defaults: 8 MiB, one lane; passes enough for a moment's work */ data class Argon(val memoryKiB: Int = 8192, val passes: Int = 13, val parallelism: Int = 1) + /** whether [text] is a .ppk (its first line PuTTY's) */ fun isPpk(text: String) = text.trimStart().startsWith("PuTTY-User-Key-File-") /** the "Comment:" a .ppk carries, if any */ fun comment(text: String): String? = text.lineSequence().firstOrNull { it.startsWith("Comment: ") }?.removePrefix("Comment: ")?.trim() + /** the key as a .ppk of [version] 3 or 2, [comment] in it, encrypted with [passphrase] unless it's empty (v3's key from Argon2id with [argon]) */ fun write(kp: KeyPair, comment: String, passphrase: String = "", version: Int = 3, argon: Argon = Argon()): String { require(version == 2 || version == 3) { "PPK versions 2 and 3 only" } val alg = KeyFormat.type(kp.public) @@ -76,6 +78,7 @@ object Ppk { cipherKey = ByteArray(0); iv = ByteArray(0); macKey = ByteArray(0) } } else { + /** the SHA-1 of [parts] one after another */ fun sha1(vararg parts: ByteArray) = MessageDigest.getInstance("SHA-1").run { parts.forEach { update(it) }; digest() } val p = passphrase.toByteArray() cipherKey = (sha1(byteArrayOf(0, 0, 0, 0), p) + sha1(byteArrayOf(0, 0, 0, 1), p)).copyOf(32) @@ -113,11 +116,15 @@ object Ppk { /** an HMAC key of no bytes (SecretKeySpec won't make one) */ private class EmptyKey(private val alg: String) : javax.crypto.SecretKey { + /** the key's algorithm, the MAC's */ override fun getAlgorithm() = alg + /** raw */ override fun getFormat() = "RAW" + /** no bytes */ override fun getEncoded() = ByteArray(0) } + /** the private half's fields as PuTTY's private blob has them (RSA's d, p, q, iqmp; ECDSA's s; Ed25519's seed) */ private fun privateBlob(kp: KeyPair): ByteArray { val b = Buffer.PlainBuffer() when (val p = kp.private) { @@ -128,7 +135,9 @@ object Ppk { return b.compactData } + /** [data] in base64, in lines of 64 */ private fun lines(data: ByteArray) = Base64.getEncoder().encodeToString(data).chunked(64) + /** [b] in lower-case hex */ private fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it) } } diff --git a/app/src/main/java/com/neodesktop/dmodem/ssh/Secrets.kt b/app/src/main/java/com/neodesktop/dmodem/ssh/Secrets.kt index cf49e41..ba7e330 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ssh/Secrets.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ssh/Secrets.kt @@ -16,7 +16,9 @@ import javax.crypto.spec.GCMParameterSpec /** Octets sealed for keeping on the device, and opened again. */ interface SecretBox { + /** [plain] sealed */ fun seal(plain: ByteArray): ByteArray + /** what [seal] sealed, opened again (throws if it can't be) */ fun open(sealed: ByteArray): ByteArray } @@ -27,6 +29,7 @@ interface SecretBox { * ciphertext with its tag. */ class KeystoreBox(private val alias: String = "dmodem-secrets") : SecretBox { + /** the Keystore's AES-256 GCM key under [alias], made the first time */ private fun key(): SecretKey { val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } (ks.getKey(alias, null) as? SecretKey)?.let { return it } @@ -41,12 +44,14 @@ class KeystoreBox(private val alias: String = "dmodem-secrets") : SecretBox { return g.generateKey() } + /** [plain] encrypted under the Keystore's key: its fresh IV, then the ciphertext and tag */ override fun seal(plain: ByteArray): ByteArray { val c = Cipher.getInstance("AES/GCM/NoPadding") c.init(Cipher.ENCRYPT_MODE, key()) return c.iv + c.doFinal(plain) } + /** the IV, ciphertext and tag [seal] made, decrypted (throws if the tag doesn't match) */ override fun open(sealed: ByteArray): ByteArray { val c = Cipher.getInstance("AES/GCM/NoPadding") c.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, sealed, 0, 12)) @@ -56,13 +61,16 @@ class KeystoreBox(private val alias: String = "dmodem-secrets") : SecretBox { /** No sealing at all: the JVM tests' (there is no Android Keystore there). */ class PlainBox : SecretBox { + /** a copy of [plain], as it is */ override fun seal(plain: ByteArray) = plain.copyOf() + /** a copy of [sealed], as it is */ override fun open(sealed: ByteArray) = sealed.copyOf() } /** Passwords kept for directory entries, sealed, by entry id. */ class PasswordStore(private val file: File, private val box: SecretBox) { + /** the file's entries, id to sealed password in base64 (none if it's missing or unreadable) */ @Synchronized private fun load(): JSONObject = try { if (file.exists()) JSONObject(file.readText()) else JSONObject() @@ -70,6 +78,7 @@ class PasswordStore(private val file: File, private val box: SecretBox) { JSONObject() } + /** the password kept for entry [id], opened; null if there's none, or it can't be opened */ @Synchronized fun get(id: String): String? = try { load().optString(id).takeIf { it.isNotEmpty() }?.let { @@ -79,6 +88,7 @@ class PasswordStore(private val file: File, private val box: SecretBox) { null } + /** [password] sealed and kept for entry [id] */ @Synchronized fun put(id: String, password: String) { val o = load() @@ -86,6 +96,7 @@ class PasswordStore(private val file: File, private val box: SecretBox) { file.writeText(o.toString()) } + /** entry [id]'s password gone */ @Synchronized fun remove(id: String) { val o = load() @@ -102,6 +113,7 @@ object SshSecurity { @Volatile private var done = false + /** the full BouncyCastle in place as "BC" and sshj told to use it (once) */ @Synchronized fun ensure() { if (done) return