mirror of
https://github.com/D-Modem/app.git
synced 2026-11-28 17:38:05 -08:00
Dial-up internet: a login script before PPP, as chat(8) has them
Expect and send strings in turn, run on the call after the CONNECT and before PPP: \U and \P the login, \d and \p waits, \c no return, ^X control characters, an expect's alternative (ogin:--ogin:), ABORT and TIMEOUT; the password kept out of the log. Set in the ISP's settings. Tested on its own, and on a modem call to an ISP that asks login: and Password: before its PPP. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
6 files changed
+301
-3
No files matched your search
@@ -0,0 +1,166 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.ppp
|
||||
|
||||
import com.neodesktop.dmodem.transfer.TransferIo
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* A dial-up login script, as chat(8) has them, run on the call before
|
||||
* PPP: expect and send strings in turn ("ogin: \U assword: \P"), quoted
|
||||
* when they have spaces; an expect's alternative after "-" ("ogin:--ogin:":
|
||||
* nothing came, a return sent and it looked for again); TIMEOUT <s>, and
|
||||
* ABORT <text> (what ends the login if it comes); "" expects nothing.
|
||||
*
|
||||
* Sent strings end with a return unless \c ends them; in either kind
|
||||
* \r \n \t \\ \s (a space) \N (none), \d (a second's wait) and \p (a
|
||||
* quarter's) in a sent one, \U the user name and \P the password, ^X a
|
||||
* control character.
|
||||
*/
|
||||
class ChatScript(private val script: String, private val user: String, private val password: String) {
|
||||
|
||||
/** the script's tokens, its quotes taken off (an empty string kept: "") */
|
||||
fun tokens(): List<String> {
|
||||
val out = ArrayList<String>()
|
||||
var i = 0
|
||||
val s = script
|
||||
while (i < s.length) {
|
||||
val c = s[i]
|
||||
when {
|
||||
c.isWhitespace() -> i++
|
||||
c == '#' && (i == 0 || s[i - 1] == '\n') -> { while (i < s.length && s[i] != '\n') i++ }
|
||||
c == '"' || c == '\'' -> {
|
||||
val sb = StringBuilder()
|
||||
i++
|
||||
while (i < s.length && s[i] != c) {
|
||||
if (s[i] == '\\' && i + 1 < s.length) { sb.append(s[i]).append(s[i + 1]); i += 2 } else sb.append(s[i++])
|
||||
}
|
||||
i++
|
||||
out.add(sb.toString())
|
||||
}
|
||||
else -> {
|
||||
val sb = StringBuilder()
|
||||
while (i < s.length && !s[i].isWhitespace()) {
|
||||
if (s[i] == '\\' && i + 1 < s.length) { sb.append(s[i]).append(s[i + 1]); i += 2 } else sb.append(s[i++])
|
||||
}
|
||||
out.add(sb.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** a string's escapes undone; for a sent one, whether a return follows ([sending]) */
|
||||
private fun unescape(t: String, sending: Boolean): Pair<String, Boolean> {
|
||||
val sb = StringBuilder()
|
||||
var cr = sending
|
||||
var i = 0
|
||||
while (i < t.length) {
|
||||
val c = t[i]
|
||||
if (c == '\\' && i + 1 < t.length) {
|
||||
when (val e = t[i + 1]) {
|
||||
'r' -> sb.append('\r')
|
||||
'n' -> sb.append('\n')
|
||||
't' -> sb.append('\t')
|
||||
's' -> sb.append(' ')
|
||||
'\\' -> sb.append('\\')
|
||||
'c' -> cr = false
|
||||
'N' -> {}
|
||||
'U' -> sb.append(user)
|
||||
'P' -> sb.append(password)
|
||||
// (the waits: marks for run())
|
||||
'd' -> sb.append(WAIT_SECOND)
|
||||
'p' -> sb.append(WAIT_QUARTER)
|
||||
else -> sb.append(e)
|
||||
}
|
||||
i += 2
|
||||
} else if (c == '^' && i + 1 < t.length && t[i + 1] in '@'..'_') {
|
||||
sb.append((t[i + 1].code - 64).toChar())
|
||||
i += 2
|
||||
} else {
|
||||
sb.append(c)
|
||||
i++
|
||||
}
|
||||
}
|
||||
return sb.toString() to cr
|
||||
}
|
||||
|
||||
/**
|
||||
* the script run on [io] (the call's octets, after CONNECT); throws
|
||||
* when an expect isn't met (its timeout) or an ABORT string comes.
|
||||
* [log]: what it does (the password left out)
|
||||
*/
|
||||
fun run(io: TransferIo, log: (String) -> Unit = {}) {
|
||||
val t = tokens()
|
||||
var timeoutMs = 45_000L
|
||||
val aborts = ArrayList<String>()
|
||||
var i = 0
|
||||
var expecting = true
|
||||
while (i < t.size) {
|
||||
val tok = t[i]
|
||||
when (tok.uppercase()) {
|
||||
"TIMEOUT" -> { timeoutMs = (t.getOrNull(i + 1)?.toLongOrNull() ?: 45) * 1000; i += 2; continue }
|
||||
"ABORT" -> { t.getOrNull(i + 1)?.let { aborts.add(unescape(it, false).first) }; i += 2; continue }
|
||||
}
|
||||
if (expecting) {
|
||||
// "a-b-c": a; if it doesn't come, send b and expect c
|
||||
val alts = tok.split('-')
|
||||
var ok = false
|
||||
var k = 0
|
||||
while (k < alts.size) {
|
||||
val want = unescape(alts[k], false).first
|
||||
log("expect \"$want\"")
|
||||
if (want.isEmpty() || expect(io, want, aborts, timeoutMs)) { ok = true; break }
|
||||
if (k + 1 >= alts.size) break
|
||||
send(io, alts[k + 1], log)
|
||||
k += 2
|
||||
}
|
||||
if (!ok) throw IOException("the login script waited for \"${unescape(alts.last(), false).first}\" in vain")
|
||||
} else {
|
||||
send(io, tok, log)
|
||||
}
|
||||
expecting = !expecting
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
private fun send(io: TransferIo, tok: String, log: (String) -> Unit) {
|
||||
val (text, cr) = unescape(tok, true)
|
||||
log("send \"" + (if (tok.contains("\\P")) "(the password)" else text.replace("\r", "\\r")) + "\"")
|
||||
val sb = StringBuilder()
|
||||
fun flush() {
|
||||
if (sb.isNotEmpty()) io.write(sb.toString().toByteArray(Charsets.ISO_8859_1))
|
||||
sb.setLength(0)
|
||||
}
|
||||
for (c in text) {
|
||||
when (c) {
|
||||
WAIT_SECOND -> { flush(); Thread.sleep(1000) }
|
||||
WAIT_QUARTER -> { flush(); Thread.sleep(250) }
|
||||
else -> sb.append(c)
|
||||
}
|
||||
}
|
||||
if (cr) sb.append('\r')
|
||||
flush()
|
||||
}
|
||||
|
||||
/** octets read until [want] comes (true), an ABORT string (an exception), or the time is up (false) */
|
||||
private fun expect(io: TransferIo, want: String, aborts: List<String>, timeoutMs: Long): Boolean {
|
||||
val end = System.currentTimeMillis() + timeoutMs
|
||||
val seen = StringBuilder()
|
||||
while (true) {
|
||||
val left = end - System.currentTimeMillis()
|
||||
if (left <= 0) return false
|
||||
val c = io.read(left)
|
||||
if (c < 0) return false
|
||||
seen.append(c.toChar())
|
||||
if (seen.endsWith(want)) return true
|
||||
aborts.firstOrNull { seen.endsWith(it) }?.let { throw IOException("the login script stopped at \"${it.trim()}\"") }
|
||||
if (seen.length > 4096) seen.delete(0, 2048)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val WAIT_SECOND = ''
|
||||
private const val WAIT_QUARTER = ''
|
||||
}
|
||||
}
|
||||
@@ -109,6 +109,12 @@ object Internet {
|
||||
if (r == null || !r.startsWith("CONNECT")) throw IOException(dialResult(r))
|
||||
online = true
|
||||
set { it.copy(phase = "Logging in", connect = r) }
|
||||
// the ISP's login script first, if it has one (a text login before PPP)
|
||||
if (isp.script.isNotBlank()) {
|
||||
set { it.copy(phase = "Running the login script") }
|
||||
ChatScript(isp.script, isp.user, isp.password).run(io) { ModemState.log.add("script: $it") }
|
||||
set { it.copy(phase = "Logging in") }
|
||||
}
|
||||
val done = java.util.concurrent.CountDownLatch(1)
|
||||
val p = Ppp(
|
||||
send = { b -> if (!hub.writeAs(listener, b)) throw IOException("the modem has gone") },
|
||||
|
||||
@@ -18,6 +18,8 @@ data class IspSettings(
|
||||
val user: String = "",
|
||||
val password: String = "",
|
||||
val initCommands: String = "",
|
||||
/** a login script for after the CONNECT, before PPP (chat's: "ogin: \\U assword: \\P"); empty: none */
|
||||
val script: String = "",
|
||||
) {
|
||||
val complete: Boolean get() = number.isNotBlank()
|
||||
}
|
||||
@@ -30,10 +32,11 @@ class IspSettingsStore(private val context: Context) {
|
||||
val user = stringPreferencesKey("user")
|
||||
val password = stringPreferencesKey("password")
|
||||
val init = stringPreferencesKey("init")
|
||||
val script = stringPreferencesKey("script")
|
||||
}
|
||||
|
||||
val settings: Flow<IspSettings> = context.ispStore.data.map { p ->
|
||||
IspSettings(p[K.number] ?: "", p[K.user] ?: "", p[K.password] ?: "", p[K.init] ?: "")
|
||||
IspSettings(p[K.number] ?: "", p[K.user] ?: "", p[K.password] ?: "", p[K.init] ?: "", p[K.script] ?: "")
|
||||
}
|
||||
|
||||
suspend fun current(): IspSettings = settings.first()
|
||||
@@ -44,6 +47,7 @@ class IspSettingsStore(private val context: Context) {
|
||||
p[K.user] = s.user.trim()
|
||||
p[K.password] = s.password
|
||||
p[K.init] = s.initCommands.trim()
|
||||
p[K.script] = s.script.trim()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,6 +146,20 @@ fun IspSettingsSection() {
|
||||
value = s.initCommands, onValueChange = { s = s.copy(initCommands = it) }, label = { Text("AT commands before the dial (optional)") },
|
||||
singleLine = true, modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = s.script, onValueChange = { s = s.copy(script = it) },
|
||||
label = { Text("Login script before PPP (optional)") },
|
||||
placeholder = { Text("ogin: \\U assword: \\P") },
|
||||
supportingText = {
|
||||
Text(
|
||||
"As chat has them: what to wait for, then what to send, in turn; \\U the user, \\P the password, " +
|
||||
"\\d a second's wait, \\c no return after; ABORT text, TIMEOUT seconds; \"\" waits for nothing",
|
||||
)
|
||||
},
|
||||
minLines = 2,
|
||||
textStyle = MaterialTheme.typography.bodyMedium.copy(fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Button(onClick = {
|
||||
scope.launch { store.save(s) }
|
||||
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show()
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.ppp
|
||||
|
||||
import com.neodesktop.dmodem.transfer.TransferIo
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
|
||||
/** chat(8)'s scripts: tokens and escapes, a login, an expect's alternative, ABORT, TIMEOUT. */
|
||||
class ChatScriptTest {
|
||||
|
||||
/** a host: what it was sent, and its answers to it ([answer]: a line it got, what it says back) */
|
||||
private class Host(val answer: (String) -> String?) {
|
||||
val got = ByteArrayOutputStream()
|
||||
private val line = StringBuilder()
|
||||
lateinit var io: TransferIo
|
||||
|
||||
init {
|
||||
io = TransferIo { b ->
|
||||
synchronized(got) { got.write(b) }
|
||||
for (c in String(b, Charsets.ISO_8859_1)) {
|
||||
if (c == '\r') {
|
||||
val l = line.toString()
|
||||
line.setLength(0)
|
||||
answer(l)?.let { a -> Thread { Thread.sleep(20); io.feed(a.toByteArray(Charsets.ISO_8859_1)) }.start() }
|
||||
} else {
|
||||
line.append(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun say(s: String) = io.feed(s.toByteArray(Charsets.ISO_8859_1))
|
||||
fun sent() = synchronized(got) { String(got.toByteArray(), Charsets.ISO_8859_1) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tokensAndEscapes() {
|
||||
val c = ChatScript("ABORT 'NO CARRIER' \"\" ATZ\nogin:--ogin: \\U 'word: ' \\P\n# a comment\n\"\" ^M\\c", "alice", "pw")
|
||||
assertEquals(listOf("ABORT", "NO CARRIER", "", "ATZ", "ogin:--ogin:", "\\U", "word: ", "\\P", "", "^M\\c"), c.tokens())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLoginWithItsPrompts() {
|
||||
// the host says its banner and "login:" only after a return (ogin:--ogin: sends one)
|
||||
val h = Host { l ->
|
||||
when (l) {
|
||||
"" -> "\r\nWelcome to the BBS ISP\r\nlogin: "
|
||||
"alice" -> "Password: "
|
||||
"s3cret" -> "\r\nStarting PPP...\r\n"
|
||||
else -> "\r\nLogin incorrect\r\n"
|
||||
}
|
||||
}
|
||||
val log = ArrayList<String>()
|
||||
ChatScript("TIMEOUT 2 ABORT incorrect ogin:--ogin: \\U assword: \\P PPP", "alice", "s3cret").run(h.io) { log.add(it) }
|
||||
assertEquals("\ralice\rs3cret\r", h.sent())
|
||||
// (the password not in the log)
|
||||
assertTrue(log.toString(), log.none { it.contains("s3cret") } && log.any { it.contains("(the password)") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun abortAndTimeout() {
|
||||
val h = Host { l -> if (l == "alice") "Password: " else "\r\nLogin incorrect\r\n" }
|
||||
h.say("login: ")
|
||||
val e = runCatching { ChatScript("ABORT incorrect ogin: \\U assword: \\P PPP", "alice", "wrong").run(h.io) }.exceptionOrNull()
|
||||
assertTrue("$e", e is IOException && e.message!!.contains("incorrect"))
|
||||
|
||||
val quiet = Host { null }
|
||||
val t0 = System.currentTimeMillis()
|
||||
val e2 = runCatching { ChatScript("TIMEOUT 1 ogin: \\U", "a", "b").run(quiet.io) }.exceptionOrNull()
|
||||
assertTrue("$e2", e2 is IOException && e2.message!!.contains("ogin:"))
|
||||
assertTrue(System.currentTimeMillis() - t0 in 900..3000)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun controlCharactersAndNoReturn() {
|
||||
val h = Host { null }
|
||||
ChatScript("\"\" ^C\\c \"\" 'a b\\c' \"\" x\\ty", "", "").run(h.io)
|
||||
assertEquals("\u0003a bx\ty\r", h.sent())
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,13 @@ class InternetLineTest {
|
||||
private fun dump() = (ModemState.log.flow.value.takeLast(40) + log.takeLast(40)).joinToString("\n")
|
||||
|
||||
@Test
|
||||
fun onlineAndPacketsBothWays() {
|
||||
fun onlineAndPacketsBothWays() = online(script = false)
|
||||
|
||||
/** an ISP that asks for a text login first (its PPP after "Starting PPP"), and a script for it */
|
||||
@Test
|
||||
fun aLoginScriptBeforePpp() = online(script = true)
|
||||
|
||||
private fun online(script: Boolean) {
|
||||
// the ISP's modem, and its PPP once the call is up
|
||||
ProcessBuilder("stty", "-F", b, "raw", "-echo").start().waitFor()
|
||||
val input = FileInputStream(b)
|
||||
@@ -103,7 +109,8 @@ class InternetLineTest {
|
||||
val fromLink = ArrayBlockingQueue<ByteArray>(100)
|
||||
val tunnels = ArrayBlockingQueue<Ppp.IpConfig>(1)
|
||||
var closed = false
|
||||
val err = Internet.connect(IspSettings("5551000", "alice", "s3cret")) { cfg ->
|
||||
val isp0 = IspSettings("5551000", "alice", "s3cret", script = if (script) "ABORT incorrect ogin:--ogin: \\U assword: \\P PPP" else "")
|
||||
val err = Internet.connect(isp0) { cfg ->
|
||||
tunnels.add(cfg)
|
||||
object : Internet.Tunnel {
|
||||
override fun write(packet: ByteArray) { fromLink.add(packet) }
|
||||
@@ -113,6 +120,23 @@ class InternetLineTest {
|
||||
assertEquals(null, err)
|
||||
assertTrue(dump(), waitLog("modemA: run cmd: ATD5551000"))
|
||||
assertTrue(c.command("A", 60_000).orEmpty().startsWith("CONNECT"))
|
||||
if (script) {
|
||||
// the host's text login: a banner, login:, Password:, then PPP
|
||||
fun say(s: String) { output.write(s.toByteArray()); output.flush() }
|
||||
say("\r\nD-Modem test ISP\r\nlogin: ")
|
||||
fun typed(): String {
|
||||
val sb = StringBuilder()
|
||||
while (true) {
|
||||
val ch = io.read(30_000)
|
||||
if (ch < 0 || ch == '\r'.code) return sb.toString()
|
||||
if (ch != '\n'.code) sb.append(ch.toChar())
|
||||
}
|
||||
}
|
||||
assertEquals("alice", typed())
|
||||
say("Password: ")
|
||||
assertEquals("s3cret", typed())
|
||||
say("\r\nStarting PPP...\r\n")
|
||||
}
|
||||
isp = TestIsp(Ppp.PROTO_CHAP, "alice", "s3cret", echo = true) { f -> output.write(f); output.flush() }
|
||||
isp.start()
|
||||
|
||||
|
||||
Reference in new issue
Block a user