Windows and macOS: SSH by libdmodemssh, built in

The Windows app runs libdmodemssh on a thread that posts its events to
the main window, with a login dialog that fits its questions; the
Windows 95 build keeps Windows' ssh.exe in a pseudo console.  The macOS
app's SSHConnection polls it on a thread for the main queue, with
SwiftUI alerts for a new host, a password or the server's questions;
PtySpawn goes.  libssh and mbedTLS are built universal for macOS by the
repository's CMake.  Linux CI logs in to a real sshd; docs follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRSV65geuGd6zMt2V6r
This commit is contained in:
Claude committed 2026-11-12 13:09:00 +00:00
1 parent c9456be42a
commit fe56f25743
16 files changed
+845 -134

No files matched your search

+15 -2
View File
@@ -33,7 +33,19 @@ jobs:
cmake -S . -B build-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_C_FLAGS="-fsanitize=address,undefined -fno-sanitize-recover=all"
cmake --build build-asan --target dmodemctl_test
ctest --test-dir build-asan --output-on-failure
ctest --test-dir build-asan --output-on-failure -R dmodemctl
- name: SSH against a real sshd
run: |
sudo apt-get install -y --no-install-recommends openssh-server
sudo useradd -m dmtest
echo 'dmtest:Sesame-42' | sudo chpasswd
ssh-keygen -q -t ed25519 -N '' -f "$RUNNER_TEMP/key"
sudo install -d -m 700 -o dmtest ~dmtest/.ssh
sudo install -m 600 -o dmtest "$RUNNER_TEMP/key.pub" ~dmtest/.ssh/authorized_keys
sudo mkdir -p /run/sshd
sudo /usr/sbin/sshd -p 2222 -o ListenAddress=127.0.0.1 -o PasswordAuthentication=yes
DMODEM_SSH_TEST=127.0.0.1:2222:dmtest:Sesame-42 DMODEM_SSH_TEST_KEY="$RUNNER_TEMP/key" \
build/ssh/dmodemssh_test
windows-9x:
name: Windows 95 and later (Open Watcom)
@@ -73,7 +85,8 @@ jobs:
- uses: actions/checkout@v4
- name: Library tests
run: |
cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo
cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0
cmake --build build
ctest --test-dir build --output-on-failure
- name: Project
+6 -2
View File
@@ -14,7 +14,7 @@ behave the same.
- **Phone**: voice calls through the sound card (dial, answer, keypad), and an
answering machine that takes messages on this computer when turned on (off by default)
- **Terminal**: the AT console, and the modem's own setup screens (AT!CF, AT!CT)
- **Remote**: log in to a server by SSH, Telnet or rlogin, in a terminal of its own
- **Remote**: log in to a server by SSH (built in, on libssh: OpenSSH's keys, agent, config and known hosts), Telnet or rlogin, in a terminal of its own
- **Settings**: every modem setting as a native control, from AT!M
- **Call Stats**: the last call's rate, modulation, error control and line figures (AT#UD, ATI11)
- **Line settings**: a SIP account, a USB modem, or a modem that already runs
@@ -40,7 +40,11 @@ Linux:
Windows: `cmake -S . -B build -A Win32 && cmake --build build --config Release`,
or for Windows 95 and later, `windows/build-watcom.sh` with Open Watcom 2.0.
macOS: `brew install xcodegen && cd macos && xcodegen && open DModem.xcodeproj`.
macOS: `cmake -S . -B build -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 && cmake --build build`
(libssh, for SSH), then `brew install xcodegen && cd macos && xcodegen && open DModem.xcodeproj`.
The first CMake build downloads libssh and mbedTLS for SSH (Windows and
macOS always; Linux when the system's libssh is older than 0.11).
The Settings page needs a dmodemd with AT!M (D-Modem's main branch since
D-Modem/D-Modem#103); the other pages work with any D-Modem 1.0.
+27 -5
View File
@@ -70,14 +70,36 @@ Linux and macOS; a TCP address or a COM port on Windows.
The Remote page logs in to a server, beside the modem, in a terminal of
its own. Telnet and rlogin are a TCP connection each app makes in its own
way, with libdmodemctl's `dmc_net` for the protocol (sans-I/O, as the
session). SSH is the system's OpenSSH client, so that the user's keys,
agent, `known_hosts` and `~/.ssh/config` apply:
session). SSH is libdmodemssh (`ssh/`), D-Modem's own client on libssh
0.11, the same engine the Android and iOS apps use, so that SSH is the
same everywhere and needs nothing installed:
- one thread per connection calls `dmc_ssh_poll()` and hands each event
to the UI's thread; what is typed, a window's size and the answers go
straight to the connection from the UI (it locks);
- the host's key is checked against OpenSSH's `known_hosts`: a known key
goes on, a new one is shown (its SHA256 fingerprint) and added if the
user accepts it, a changed one is refused with a warning;
- the login is OpenSSH's order: the agent and `~/.ssh`'s keys first,
then keyboard-interactive or a password (three tries), in the app's own
dialogs; `~/.ssh/config` is read (host aliases, users, ports);
- Ed25519, ECDSA and RSA keys; a shell on a pty with TERM
`xterm-256color`, its size sent as it changes. The engine also has
commands, direct channels (`-L`, `-D`), remote listens (`-R`), agent
channels (`-A`) and keys made or re-encrypted, which the mobile apps use.
libssh and mbedTLS come from the system when it has libssh 0.11 or later
(Linux), else they are built from their release tarballs, checked by
hash (`ssh/cmake/BundledLibssh.cmake`): always on Windows and macOS. The
Windows 95 build (Open Watcom) has no libssh: it runs Windows' own
`ssh.exe` in a pseudo console when it finds one (Windows 10 1809 and
later).
| | Telnet and rlogin | SSH | Kept in |
| --- | --- | --- | --- |
| Linux | GSocketClient, its socket on the main loop (G_IO_PRI for rlogin's urgent byte) | `ssh` on a pty of the page's own (forkpty), TERM `xterm-256color` | `settings.ini`, `[remote]` |
| Windows | Winsock 1.1, `WSAAsyncSelect` (FD_OOB for rlogin), on every Windows from 95 | Windows' `ssh.exe` (the OpenSSH Client feature) in a pseudo console: Windows 10 1809 and later, looked up at run time | `dmodem.ini`, `[remote]` |
| macOS | a BSD socket on a dispatch source | `/usr/bin/ssh` on a pty (`PtySpawn.c`) | UserDefaults |
| Linux | GSocketClient, its socket on the main loop (G_IO_PRI for rlogin's urgent byte) | libdmodemssh on a GThread, events by `g_main_context_invoke`, AdwAlertDialogs | `settings.ini`, `[remote]` |
| Windows | Winsock 1.1, `WSAAsyncSelect` (FD_OOB for rlogin), on every Windows from 95 | libdmodemssh on a thread, events posted (`WM_APP_SSH`), the profile's `.ssh` | `dmodem.ini`, `[remote]` |
| macOS | a BSD socket on a dispatch source | libdmodemssh (`SSHConnection.swift`) on a thread, events on the main queue, SwiftUI alerts | UserDefaults |
Telnet tells the server the terminal type and the window's size (NAWS),
and sends a typed CR as CR NUL. rlogin sends the user as both the local
+2 -2
View File
@@ -2,7 +2,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 D-Modem Authors
*
* Bridging.h - libdmodemctl, for Swift
* Bridging.h - libdmodemctl and libdmodemssh, for Swift
*/
#include "dmodemctl.h"
#include "PtySpawn.h"
#include "dmodemssh.h"
-42
View File
@@ -1,42 +0,0 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 D-Modem Authors
*
* PtySpawn.c - a program started on a new pty, for the Remote page's ssh
*/
#include <fcntl.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <util.h>
#include "PtySpawn.h"
int dm_pty_spawn(const char *path, const char *const *argv, const char *term,
int cols, int rows, pid_t *pid)
{
struct winsize ws = { 0 };
ws.ws_col = (unsigned short)cols;
ws.ws_row = (unsigned short)rows;
int fd;
pid_t p = forkpty(&fd, NULL, NULL, &ws);
if (p < 0)
return -1;
if (p == 0) {
setenv("TERM", term, 1);
execv(path, (char *const *)argv);
_exit(127);
}
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
fcntl(fd, F_SETFD, FD_CLOEXEC);
*pid = p;
return fd;
}
void dm_pty_resize(int fd, int cols, int rows)
{
struct winsize ws = { 0 };
ws.ws_col = (unsigned short)cols;
ws.ws_row = (unsigned short)rows;
ioctl(fd, TIOCSWINSZ, &ws);
}
-21
View File
@@ -1,21 +0,0 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 D-Modem Authors
*
* PtySpawn.h - a program started on a new pty (the Remote page's ssh):
* Swift can't fork, so this is C
*/
#ifndef DMODEM_PTY_SPAWN_H
#define DMODEM_PTY_SPAWN_H
#include <sys/types.h>
/* path started with argv (NULL-ended) and TERM=term on a pty of cols by
rows, as the leader of its own session: the pty's master (non-blocking),
and its pid in *pid; -1 if it could not be */
int dm_pty_spawn(const char *path, const char *const *argv, const char *term,
int cols, int rows, pid_t *pid);
/* the pty's new size, told to the program (SIGWINCH) */
void dm_pty_resize(int fd, int cols, int rows);
#endif
+240 -51
View File
@@ -5,8 +5,9 @@
// or rlogin, in a terminal of its own (TerminalView.swift's view)
//
// Telnet and rlogin are a socket made here and libdmodemctl's dmc_net
// for the protocol. SSH is the system's /usr/bin/ssh on a pty
// (PtySpawn.c), so that its keys, agent and config are the user's.
// for the protocol. SSH is libdmodemssh (the apps' own client, on
// libssh) through SSHConnection.swift: it reads OpenSSH's config,
// known_hosts, keys and agent, so that they are the user's.
import Darwin
import Foundation
@@ -35,14 +36,31 @@ final class RemoteSession: ObservableObject, TerminalHost {
@Published private(set) var status = "Not connected"
/// bumped when the screen changed, to draw it again
@Published private(set) var screenVersion = 0
/// what the SSH login asks the user, if anything
@Published var question: Question?
/// an SSH login's question
enum Question {
/// a server not known yet: its key type and fingerprint
case newHost(type: String, fingerprint: String)
/// a password; why the last was refused
case password(why: String)
/// the server's questions (keyboard-interactive): each with
/// whether its answer may be shown
case prompts(title: String, instruction: String, questions: [(String, Bool)])
}
let vt: OpaquePointer
private var fd: Int32 = -1 // the socket, or the pty's master
private var fd: Int32 = -1 // Telnet's and rlogin's socket
private var source: DispatchSourceRead?
private var writer: DispatchSourceWrite?
private var exitSource: DispatchSourceProcess?
private var net: OpaquePointer?
private var pid: pid_t = 0
/// SSH: the connection, the shell's channel, the logins tried
private var ssh: SSHConnection?
private var shell: Int32 = 0
private var triedKeys = false
private var asks = 0
private var exitStatus = 0
private var pending: [UInt8] = []
private var cols = 80, rows = 24
private var timer: Timer?
@@ -80,7 +98,12 @@ final class RemoteSession: ObservableObject, TerminalHost {
}
private func send(_ bytes: [UInt8]) {
guard running, fd >= 0, !bytes.isEmpty else { return }
guard running, !bytes.isEmpty else { return }
if let ssh {
if shell > 0 { ssh.write(shell, bytes) }
return
}
guard fd >= 0 else { return }
if let net {
bytes.withUnsafeBufferPointer { b in
b.baseAddress!.withMemoryRebound(to: CChar.self, capacity: b.count) {
@@ -117,10 +140,9 @@ final class RemoteSession: ObservableObject, TerminalHost {
running = true
if proto == .ssh {
guard startSSH(host: h, port: p) else {
ended("Could not start ssh")
ended("Could not start SSH")
return
}
status = "Connected by SSH"
} else {
net = dmc_net_new(proto.net, user, "ansi", Int32(cols), Int32(rows))
connectSocket(host: h, port: p, gen: gen)
@@ -132,37 +154,154 @@ final class RemoteSession: ObservableObject, TerminalHost {
func stop() { ended(nil) }
// MARK: - SSH
private func startSSH(host: String, port: Int) -> Bool {
var args = ["ssh", "-p", String(port)]
if !user.isEmpty { args += ["-l", user] }
args += ["--", host]
let cargs: [UnsafeMutablePointer<CChar>?] = args.map { strdup($0) } + [nil]
defer { for a in cargs { free(a) } }
var p: pid_t = 0
let f = cargs.map { UnsafePointer($0) }.withUnsafeBufferPointer {
dm_pty_spawn("/usr/bin/ssh", $0.baseAddress, "xterm", Int32(cols), Int32(rows), &p)
let u = user.isEmpty ? NSUserName() : user
guard let c = SSHConnection(host: host, port: port, user: u) else { return false }
ssh = c
shell = 0
triedKeys = false
asks = 0
exitStatus = 0
c.start { [weak self, weak c] ev in
guard let self, let c else { return }
self.sshEvent(c, ev)
}
guard f >= 0 else { return false }
fd = f
pid = p
watch()
let e = DispatchSource.makeProcessSource(identifier: p, eventMask: .exit, queue: .main)
e.setEventHandler { [weak self] in self?.childExited(p) }
e.resume()
exitSource = e
return true
}
private func childExited(_ p: pid_t) {
var st: Int32 = 0
waitpid(p, &st, 0)
guard p == pid else { return }
pid = 0
readable() // (what is left)
let code = (st & 0x7f) == 0 ? (st >> 8) & 0xff : 0
ended(code != 0 ? "ssh exited with status \(code)" : "Connection closed")
/// an event of the connection's, on the main queue
private func sshEvent(_ c: SSHConnection, _ ev: SSHConnection.Event) {
if ev.type == DMC_SSH_EV_CLOSED {
c.finish()
guard c === ssh else { return }
ssh = nil
question = nil
if ev.data == nil && exitStatus > 0 {
ended("the shell exited with status \(exitStatus)")
} else {
ended(ev.text)
}
return
}
guard c === ssh else { return }
switch ev.type {
case DMC_SSH_EV_HOSTKEY:
hostKey(c, ev.text ?? "", Int(ev.value))
case DMC_SSH_EV_AUTH:
login(c, methods: Int(ev.value), why: ev.text ?? "")
case DMC_SSH_EV_PROMPTS:
if ev.value == 0 {
dmc_ssh_answered(c.s)
} else {
var qs: [(String, Bool)] = []
for i in 0..<Int(ev.value) {
var echo: Int32 = 0
let q = String(cString: dmc_ssh_prompt(c.s, Int32(i), &echo))
qs.append((q, echo != 0))
}
let t = ev.text ?? ""
question = .prompts(title: t.isEmpty ? "The server asks" : t,
instruction: String(cString: dmc_ssh_instruction(c.s)),
questions: qs)
}
case DMC_SSH_EV_READY:
if let d = ev.data, !d.isEmpty { feed(d) }
shell = dmc_ssh_shell(c.s, "xterm-256color", Int32(cols), Int32(rows), 0)
status = "Connected by SSH"
case DMC_SSH_EV_OPEN:
if ev.value == 0 {
show("\r\n[The server refused the shell]\r\n")
c.disconnect()
}
case DMC_SSH_EV_DATA:
if ev.channel == shell, let d = ev.data {
feed(d)
pump()
}
case DMC_SSH_EV_EXIT:
if ev.channel == shell { exitStatus = Int(ev.value) }
case DMC_SSH_EV_CLOSE:
// (the shell's over: so is the connection)
if ev.channel == shell { c.disconnect() }
case DMC_SSH_EV_INCOMING:
dmc_ssh_close(c.s, ev.channel)
default:
break
}
}
/// the server's key: known goes on; new is asked; changed is refused
private func hostKey(_ c: SSHConnection, _ key: String, _ known: Int) {
if known == DMC_SSH_HOST_KNOWN {
dmc_ssh_trust(c.s, 1, 0)
return
}
var fp = [CChar](repeating: 0, count: 128)
dmc_ssh_fingerprint(key, &fp, Int32(fp.count))
let type = String(key.prefix { $0 != " " })
let print = String(cString: fp)
if known == DMC_SSH_HOST_CHANGED || known == DMC_SSH_HOST_OTHER_TYPE {
show("\r\n\u{1b}[1;31mThe server's host key has changed (it is now \(type) \(print)).\r\n" +
"Someone may be in the middle; or the server has a new key. If that is\r\n" +
"expected, remove its old line from ~/.ssh/known_hosts.\u{1b}[0m\r\n")
dmc_ssh_trust(c.s, 0, 0)
return
}
question = .newHost(type: type, fingerprint: print)
}
/// what's tried, in OpenSSH's order: its keys and agent, then the
/// server's questions or a password (three times at most)
private func login(_ c: SSHConnection, methods: Int, why: String) {
if methods & DMC_SSH_AUTH_PUBLICKEY != 0 && !triedKeys {
triedKeys = true
dmc_ssh_auth_auto(c.s)
return
}
asks += 1
if asks > 3 {
dmc_ssh_auth_cancel(c.s)
} else if methods & DMC_SSH_AUTH_INTERACTIVE != 0 {
dmc_ssh_auth_interactive(c.s)
} else if methods & DMC_SSH_AUTH_PASSWORD != 0 {
question = .password(why: asks > 1 ? why : "")
} else {
dmc_ssh_auth_cancel(c.s)
}
}
/// the user's answer to [question]: the answers (none for a new
/// host's yes), or nil for no
func answer(_ answers: [String]?) {
guard let q = question, let c = ssh else { return }
question = nil
guard let answers else {
if case .newHost = q { dmc_ssh_trust(c.s, 0, 0) } else { dmc_ssh_auth_cancel(c.s) }
return
}
switch q {
case .newHost:
dmc_ssh_trust(c.s, 1, 1)
case .password:
dmc_ssh_auth_password(c.s, answers.first ?? "")
case .prompts:
for (i, a) in answers.enumerated() { dmc_ssh_answer(c.s, Int32(i), a) }
dmc_ssh_answered(c.s)
}
}
private func feed(_ d: [UInt8]) {
d.withUnsafeBufferPointer { b in
b.baseAddress!.withMemoryRebound(to: CChar.self, capacity: b.count) {
dmc_vt_feed(vt, $0, Int32(b.count))
}
}
}
// MARK: - Telnet and rlogin
private func connectSocket(host: String, port: Int, gen: Int) {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
var hints = addrinfo()
@@ -247,14 +386,9 @@ final class RemoteSession: ObservableObject, TerminalHost {
}
if n < 0 && errno == EINTR { continue }
if n < 0 && errno == EAGAIN { break }
// the end: the server closed, or ssh's pty (its exit says why)
// the end: the server closed
pump()
if net != nil {
ended("Connection closed by the server")
} else {
source?.cancel()
source = nil
}
ended("Connection closed by the server")
return
}
pump()
@@ -273,8 +407,10 @@ final class RemoteSession: ObservableObject, TerminalHost {
while true {
let k = dmc_vt_reply(vt, &buf, Int32(buf.count))
if k <= 0 { break }
if let net { dmc_net_type(net, buf, k) } else {
pending.append(contentsOf: buf[0..<Int(k)].map { UInt8(bitPattern: $0) })
if let net {
dmc_net_type(net, buf, k)
} else if let ssh, shell > 0 {
ssh.write(shell, buf[0..<Int(k)].map { UInt8(bitPattern: $0) })
}
}
if let net {
@@ -322,8 +458,8 @@ final class RemoteSession: ObservableObject, TerminalHost {
rows = r
if let net {
dmc_net_resize(net, Int32(c), Int32(r))
} else if fd >= 0 {
dm_pty_resize(fd, Int32(c), Int32(r))
} else if let ssh, shell > 0 {
ssh.resize(shell, cols: c, rows: r)
}
}
pump()
@@ -345,14 +481,11 @@ final class RemoteSession: ObservableObject, TerminalHost {
source = nil
writer?.cancel()
writer = nil
exitSource?.cancel()
exitSource = nil
if pid > 0 {
kill(pid, SIGHUP)
let p = pid
DispatchQueue.global().async { var st: Int32 = 0; waitpid(p, &st, 0) }
pid = 0
}
// (let go: its thread ends with it)
ssh?.disconnect()
ssh = nil
shell = 0
question = nil
if fd >= 0 {
close(fd)
fd = -1
@@ -402,5 +535,61 @@ struct RemotePage: View {
}
.padding(.horizontal, 8).padding(.vertical, 4)
}
.onChange(of: session.question != nil) { _ in
answers = Array(repeating: "", count: answers.count)
}
.alert(title, isPresented: asking, presenting: session.question) { q in
switch q {
case .newHost:
Button("Connect") { session.answer([]) }
Button("Cancel", role: .cancel) { session.answer(nil) }
case .password:
SecureField("Password", text: answerBinding(0))
Button("Log In") { session.answer([answers[0]]) }
Button("Cancel", role: .cancel) { session.answer(nil) }
case .prompts(_, _, let qs):
ForEach(qs.indices, id: \.self) { i in
if qs[i].1 {
TextField(qs[i].0, text: answerBinding(i))
} else {
SecureField(qs[i].0, text: answerBinding(i))
}
}
Button("Log In") { session.answer(Array(answers.prefix(qs.count))) }
Button("Cancel", role: .cancel) { session.answer(nil) }
}
} message: { q in
switch q {
case .newHost(let type, let fp):
Text("This server is not known yet. Its key's fingerprint is\n\n\(type) \(fp)\n\n" +
"If it's the one you expect, it will be added to ~/.ssh/known_hosts.")
case .password(let why):
Text(why)
case .prompts(_, let instruction, let qs):
Text(instruction.isEmpty ? qs.map(\.0).joined(separator: "\n") : instruction)
}
}
}
/// the answers being typed, cleared for each question
@State private var answers = ["", "", "", "", "", "", "", ""]
private func answerBinding(_ i: Int) -> Binding<String> {
Binding(get: { i < answers.count ? answers[i] : "" },
set: { if i < answers.count { answers[i] = $0 } })
}
private var asking: Binding<Bool> {
// (dismissed by its buttons, each of which answers)
Binding(get: { session.question != nil }, set: { _ in })
}
private var title: String {
switch session.question {
case .newHost: return "Connect to a new server?"
case .password: return "Log in to \(session.host)"
case .prompts(let t, _, _): return t
case nil: return ""
}
}
}
+98
View File
@@ -0,0 +1,98 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 D-Modem Authors
//
// SSHConnection.swift - a libdmodemssh connection polled on a thread of
// its own, each event handed to the main queue. It reads OpenSSH's
// config and known_hosts. Its dmc_ssh is freed by finish(), once the
// DMC_SSH_EV_CLOSED that ends it has been handed over.
import Foundation
final class SSHConnection {
/// an event, copied off the connection's thread
struct Event {
let type: Int
let channel: Int32
let value: Int32
let data: [UInt8]?
/// the data as UTF-8 text
var text: String? { data.map { String(decoding: $0, as: UTF8.self) } }
}
let s: OpaquePointer
private let done = DispatchSemaphore(value: 0)
private var started = false
private var freed = false
init?(host: String, port: Int, user: String) {
guard let s = dmc_ssh_new(host, Int32(port), user) else { return nil }
self.s = s
// OpenSSH's own config and known hosts: the user's
dmc_ssh_option(s, "config", "")
dmc_ssh_option(s, "knownhosts", "")
}
deinit {
if !freed {
if started {
dmc_ssh_disconnect(s)
done.wait()
}
dmc_ssh_free(s)
}
}
/// polled until it's over, each event to handle on the main queue
func start(_ handle: @escaping (Event) -> Void) {
started = true
let s = self.s
let done = self.done
let t = Thread {
var ev = dmc_ssh_event()
while true {
let n = dmc_ssh_poll(s, 1000, &ev)
if n < 0 { break }
if n == 0 { continue }
let data: [UInt8]? = ev.data.map { p in
p.withMemoryRebound(to: UInt8.self, capacity: Int(ev.len)) {
Array(UnsafeBufferPointer(start: $0, count: Int(ev.len)))
}
}
let e = Event(type: Int(ev.type), channel: ev.channel, value: ev.value, data: data)
DispatchQueue.main.async { handle(e) }
if Int(ev.type) == DMC_SSH_EV_CLOSED { break }
}
done.signal()
}
t.name = "ssh"
t.start()
}
/// what's typed, to a channel
func write(_ channel: Int32, _ bytes: [UInt8]) {
bytes.withUnsafeBufferPointer { b in
b.baseAddress!.withMemoryRebound(to: CChar.self, capacity: b.count) {
_ = dmc_ssh_write(s, channel, $0, Int32(b.count))
}
}
}
/// a shell's new size
func resize(_ channel: Int32, cols: Int, rows: Int) {
dmc_ssh_resize(s, channel, Int32(cols), Int32(rows))
}
/// closed by the user: a DMC_SSH_EV_CLOSED comes
func disconnect() {
if !freed { dmc_ssh_disconnect(s) }
}
/// the connection freed, once its thread has ended
func finish() {
guard !freed else { return }
done.wait()
freed = true
dmc_ssh_free(s)
}
}
+12 -2
View File
@@ -1,4 +1,8 @@
# The macOS app's Xcode project, made by XcodeGen:
# The macOS app's Xcode project, made by XcodeGen. libssh and mbedTLS
# (for libdmodemssh) are built first by the repository's CMake, for both
# architectures, into ../build:
# cmake -S .. -B ../build -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" \
# -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 && cmake --build ../build
# brew install xcodegen && cd macos && xcodegen
# xcodebuild -project DModem.xcodeproj -scheme DModem build
name: DModem
@@ -14,13 +18,19 @@ targets:
- path: DModem
- path: ../core/src
buildPhase: sources
- path: ../ssh/src
buildPhase: sources
settings:
base:
PRODUCT_NAME: D-Modem
PRODUCT_BUNDLE_IDENTIFIER: io.github.d-modem.DModem
MARKETING_VERSION: "1.0.0"
CURRENT_PROJECT_VERSION: "1"
HEADER_SEARCH_PATHS: $(SRCROOT)/../core/include
HEADER_SEARCH_PATHS: $(SRCROOT)/../core/include $(SRCROOT)/../ssh/include $(SRCROOT)/../build/dmodem-libssh/include
GCC_PREPROCESSOR_DEFINITIONS: LIBSSH_STATIC=1
# libssh and mbedTLS, as CMake built them (see above)
LIBRARY_SEARCH_PATHS: $(SRCROOT)/../build/dmodem-libssh/lib
OTHER_LDFLAGS: -lssh -lmbedtls -lmbedx509 -lmbedcrypto -leverest -lp256m
SWIFT_OBJC_BRIDGING_HEADER: DModem/Bridging.h
SWIFT_VERSION: "5.0"
GCC_C_LANGUAGE_STANDARD: c11
+4
View File
@@ -70,6 +70,10 @@ target_compile_definitions(dmodem_libssh INTERFACE LIBSSH_STATIC=1)
target_link_libraries(dmodem_libssh INTERFACE ${_prefix}/lib/${_ssh_lib} ${_mbed_paths})
if(WIN32)
target_link_libraries(dmodem_libssh INTERFACE ws2_32 iphlpapi bcrypt shell32 advapi32)
# (MinGW's libssh locks with winpthreads)
if(MINGW)
target_link_libraries(dmodem_libssh INTERFACE pthread)
endif()
elseif(UNIX)
find_package(Threads REQUIRED)
target_link_libraries(dmodem_libssh INTERFACE Threads::Threads)
+5
View File
@@ -16,6 +16,11 @@ add_executable(dmodem WIN32
res/app.rc)
target_include_directories(dmodem PRIVATE src)
target_link_libraries(dmodem PRIVATE dmodemctl comctl32 wsock32 comdlg32 gdi32 winmm msacm32)
# the Remote page's SSH: libdmodemssh (libssh, built in)
if(TARGET dmodemssh)
target_link_libraries(dmodem PRIVATE dmodemssh)
target_compile_definitions(dmodem PRIVATE DMODEM_HAVE_SSH)
endif()
if(MSVC)
target_compile_definitions(dmodem PRIVATE _CRT_SECURE_NO_WARNINGS)
# (a manifest of our own in app.rc)
+25
View File
@@ -80,6 +80,31 @@ BEGIN
PUSHBUTTON "Cancel", IDCANCEL, 182, 90, 50, 14
END
/* the Remote page's SSH login: up to four questions, each answer shown
(IDC_A_E0 + i) or hidden (IDC_A_E0P + i) */
IDD_ASK DIALOG 0, 0, 260, 170
STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Log In"
FONT 8, "MS Shell Dlg"
BEGIN
LTEXT "", IDC_A_HEAD, 8, 8, 244, 10
LTEXT "", IDC_A_TEXT, 8, 20, 244, 24
LTEXT "", IDC_A_Q0, 8, 48, 90, 8
EDITTEXT IDC_A_E0, 100, 46, 152, 12, ES_AUTOHSCROLL
EDITTEXT IDC_A_E0P, 100, 46, 152, 12, ES_AUTOHSCROLL | ES_PASSWORD
LTEXT "", 964, 8, 66, 90, 8
EDITTEXT 968, 100, 64, 152, 12, ES_AUTOHSCROLL
EDITTEXT 972, 100, 64, 152, 12, ES_AUTOHSCROLL | ES_PASSWORD
LTEXT "", 965, 8, 84, 90, 8
EDITTEXT 969, 100, 82, 152, 12, ES_AUTOHSCROLL
EDITTEXT 973, 100, 82, 152, 12, ES_AUTOHSCROLL | ES_PASSWORD
LTEXT "", 966, 8, 102, 90, 8
EDITTEXT 970, 100, 100, 152, 12, ES_AUTOHSCROLL
EDITTEXT 974, 100, 100, 152, 12, ES_AUTOHSCROLL | ES_PASSWORD
DEFPUSHBUTTON "&Log In", IDOK, 146, 150, 50, 14
PUSHBUTTON "Cancel", IDCANCEL, 202, 150, 50, 14
END
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,0
PRODUCTVERSION 1,0,0,0
+4
View File
@@ -106,6 +106,8 @@ void link_wait(int tag, ResponseFn fn, void *data);
#define TIMER_VOICE 2
#define WM_APP_REMOTE (WM_APP + 2)
#define TIMER_REMOTE 3
/* an event of the Remote page's SSH connection, from its thread */
#define WM_APP_SSH (WM_APP + 3)
/* main.cpp */
void app_log(const char *line);
@@ -153,6 +155,8 @@ void remote_page_layout(HWND page, int w, int h);
/* its socket's messages (WM_APP_REMOTE) and its timer (TIMER_REMOTE) */
void remote_socket(WPARAM w, LPARAM l);
void remote_tick();
/* an SSH event (WM_APP_SSH's lParam) */
void remote_ssh(LPARAM l);
/* the focus to its first control */
bool remote_focus();
void remote_stop();
+3
View File
@@ -299,6 +299,9 @@ static LRESULT CALLBACK main_proc(HWND w, UINT m, WPARAM wp, LPARAM lp)
case WM_APP_REMOTE:
remote_socket(wp, lp);
return 0;
case WM_APP_SSH:
remote_ssh(lp);
return 0;
case WM_DESTROY:
KillTimer(w, TIMER_PUMP);
KillTimer(w, TIMER_VOICE);
+396 -7
View File
@@ -7,11 +7,13 @@
*
* Telnet and rlogin: a Winsock 1.1 socket (WSAAsyncSelect, as the
* modem's link), the protocol libdmodemctl's dmc_net; every Windows from
* 95 on has them. SSH: Windows' own OpenSSH client, ssh.exe, in a
* pseudo console (ConPTY), so it needs Windows 10 1809 or later with
* the OpenSSH client feature; the ConPTY calls are looked up at run
* time, so that the app still starts on Windows 95. Its output is read
* from a timer (PeekNamedPipe), with no threads.
* 95 on has them. SSH: libdmodemssh (the apps' own client, on libssh),
* on a thread of its own that posts its events to the main window; it
* reads OpenSSH's config, known_hosts and keys in the profile's .ssh.
* The Windows 95 build (Open Watcom, no libssh) runs Windows' own
* ssh.exe in a pseudo console (ConPTY) instead, when it finds one
* (Windows 10 1809 and later): the ConPTY calls are looked up at run
* time and its output read from a timer.
*/
#include <stdio.h>
#include <stdlib.h>
@@ -38,6 +40,16 @@ static bool sock_open;
static char *pending;
static int pending_n, pending_cap;
#ifdef DMODEM_HAVE_SSH
#include "dmodemssh.h"
/* SSH: the connection (below) */
struct Ssh;
static Ssh *ssh;
static int shell;
static dmc_ssh *ssh_conn();
static void ssh_disconnect();
#else
/* SSH: the pseudo console, its pipes, ssh.exe */
static void *hpc;
static HANDLE con_in = INVALID_HANDLE_VALUE, con_out = INVALID_HANDLE_VALUE;
@@ -116,6 +128,7 @@ static bool find_ssh(char *out, int n)
}
return false;
}
#endif
/*
* the page
@@ -165,6 +178,12 @@ static void ended(const char *why)
net = NULL;
}
pending_n = 0;
#ifdef DMODEM_HAVE_SSH
/* (the connection is freed once its thread has said it's closed) */
if (ssh)
ssh_disconnect();
shell = 0;
#else
if (proc) {
TerminateProcess(proc, 0);
CloseHandle(proc);
@@ -184,6 +203,7 @@ static void ended(const char *why)
CloseHandle(con_in);
con_in = INVALID_HANDLE_VALUE;
}
#endif
char line[300];
_snprintf(line, sizeof(line), "\r\n\x1b[0m[%s]\r\n",
why ? why : "Disconnected");
@@ -237,10 +257,16 @@ static void typed(const char *data, int n, void *ctx)
if (net && sock_open) {
dmc_net_type(net, data, n);
flush();
} else if (con_in != INVALID_HANDLE_VALUE) {
}
#ifdef DMODEM_HAVE_SSH
else if (ssh && shell > 0)
dmc_ssh_write(ssh_conn(), shell, data, n);
#else
else if (con_in != INVALID_HANDLE_VALUE) {
DWORD w;
WriteFile(con_in, data, (DWORD)n, &w, NULL);
}
#endif
}
void remote_socket(WPARAM wp, LPARAM lp)
@@ -305,13 +331,20 @@ void remote_tick()
if (net) {
dmc_net_resize(net, c, r);
flush();
} else if (hpc) {
}
#ifdef DMODEM_HAVE_SSH
else if (ssh && shell > 0)
dmc_ssh_resize(ssh_conn(), shell, c, r);
#else
else if (hpc) {
COORD sz;
sz.X = (SHORT)c;
sz.Y = (SHORT)r;
resize_pc(hpc, sz);
}
#endif
}
#ifndef DMODEM_HAVE_SSH
if (con_out == INVALID_HANDLE_VALUE)
return;
for (;;) {
@@ -338,8 +371,356 @@ void remote_tick()
m[sizeof(m) - 1] = '\0';
ended(m);
}
#endif
}
#ifdef DMODEM_HAVE_SSH
/*
* SSH: libdmodemssh, polled on a thread of its own, its events posted
* to the main window (WM_APP_SSH)
*/
/* a connection and the thread that polls it */
struct Ssh {
dmc_ssh *s;
HANDLE thread;
};
/* one of its events, posted */
struct SshMsg {
Ssh *ssh;
int type, channel, value, len;
char *data;
};
static int tried_keys, asks, exit_status;
/* the connection's dmc_ssh */
static dmc_ssh *ssh_conn()
{
return ssh->s;
}
/* the connection closed by the user: its thread ends with it */
static void ssh_disconnect()
{
dmc_ssh_disconnect(ssh->s);
}
static DWORD WINAPI ssh_poll(void *p)
{
Ssh *c = (Ssh *)p;
dmc_ssh_event ev;
int n;
while ((n = dmc_ssh_poll(c->s, 1000, &ev)) >= 0) {
if (n == 0)
continue;
SshMsg *m = (SshMsg *)calloc(1, sizeof(SshMsg));
if (!m)
continue;
m->ssh = c;
m->type = ev.type;
m->channel = ev.channel;
m->value = ev.value;
m->len = ev.len;
if (ev.data) {
m->data = (char *)malloc((size_t)ev.len + 1);
if (m->data) {
memcpy(m->data, ev.data, (size_t)ev.len);
m->data[ev.len] = '\0';
}
}
/* (a window gone: the event too) */
if (!PostMessage(app.main, WM_APP_SSH, 0, (LPARAM)m)) {
free(m->data);
free(m);
}
if (ev.type == DMC_SSH_EV_CLOSED)
break;
}
return 0;
}
/* text the dialog shows (the system's code page) */
static void set_text(HWND d, int id, const char *utf8)
{
char a[600];
to_ansi(utf8 ? utf8 : "", a, sizeof(a));
SetDlgItemText(d, id, a);
}
/* an answer typed (the system's code page) as UTF-8 */
static void get_answer(HWND d, int id, char *out, int n)
{
char a[512];
wchar_t w[512];
GetDlgItemText(d, id, a, sizeof(a));
int k = MultiByteToWideChar(CP_ACP, 0, a, -1, w, 512);
if (!k || !WideCharToMultiByte(CP_UTF8, 0, w, -1, out, n, NULL, NULL))
lstrcpyn(out, a, n);
}
/* what the login dialog asks: a password (prompts 0) or the server's
questions (four at most) */
struct Ask {
const char *head, *text;
int prompts;
char answers[4][256];
};
static INT_PTR CALLBACK ask_proc(HWND d, UINT msg, WPARAM wp, LPARAM lp)
{
Ask *a = (Ask *)GetWindowLongPtr(d, DWLP_USER);
switch (msg) {
case WM_INITDIALOG: {
a = (Ask *)lp;
SetWindowLongPtr(d, DWLP_USER, (LONG_PTR)a);
set_text(d, IDC_A_HEAD, a->head);
set_text(d, IDC_A_TEXT, a->text);
int n = a->prompts ? a->prompts : 1;
HWND first = NULL;
for (int i = 0; i < 4; i++) {
int echo = 0;
const char *q = i >= n ? "" : a->prompts ?
dmc_ssh_prompt(ssh->s, i, &echo) : "Password:";
set_text(d, IDC_A_Q0 + i, q);
ShowWindow(GetDlgItem(d, IDC_A_Q0 + i), i < n ? SW_SHOW : SW_HIDE);
ShowWindow(GetDlgItem(d, IDC_A_E0 + i), i < n && echo ? SW_SHOW : SW_HIDE);
ShowWindow(GetDlgItem(d, IDC_A_E0P + i), i < n && !echo ? SW_SHOW : SW_HIDE);
if (i < n && !first)
first = GetDlgItem(d, echo ? IDC_A_E0 + i : IDC_A_E0P + i);
}
/* (the buttons under the last question, the box fitted to them) */
RECT b = { 0, 46 + 18 * n + 8, 50, 46 + 18 * n + 8 + 14 };
MapDialogRect(d, &b);
RECT ok, cl, wr;
GetWindowRect(GetDlgItem(d, IDOK), &ok);
MapWindowPoints(NULL, d, (POINT *)&ok, 2);
SetWindowPos(GetDlgItem(d, IDOK), NULL, ok.left, b.top, 0, 0,
SWP_NOSIZE | SWP_NOZORDER);
GetWindowRect(GetDlgItem(d, IDCANCEL), &ok);
MapWindowPoints(NULL, d, (POINT *)&ok, 2);
SetWindowPos(GetDlgItem(d, IDCANCEL), NULL, ok.left, b.top, 0, 0,
SWP_NOSIZE | SWP_NOZORDER);
GetClientRect(d, &cl);
GetWindowRect(d, &wr);
RECT pad = { 0, 0, 0, 8 };
MapDialogRect(d, &pad);
int extra = (wr.bottom - wr.top) - cl.bottom;
SetWindowPos(d, NULL, 0, 0, wr.right - wr.left,
b.bottom + pad.bottom + extra, SWP_NOMOVE | SWP_NOZORDER);
SetFocus(first);
return FALSE;
}
case WM_COMMAND:
if (LOWORD(wp) == IDOK) {
for (int i = 0; i < 4; i++) {
int id = IsWindowVisible(GetDlgItem(d, IDC_A_E0 + i)) ?
IDC_A_E0 + i : IDC_A_E0P + i;
get_answer(d, id, a->answers[i], sizeof(a->answers[i]));
}
EndDialog(d, IDOK);
return TRUE;
}
if (LOWORD(wp) == IDCANCEL) {
EndDialog(d, IDCANCEL);
return TRUE;
}
break;
}
return FALSE;
}
/* the server's key: known goes on; new is asked; changed is refused */
static void ssh_hostkey(const char *key, int known)
{
char fp[128] = "";
dmc_ssh_fingerprint(key, fp, sizeof(fp));
int tl = (int)strcspn(key, " ");
if (known == DMC_SSH_HOST_KNOWN) {
dmc_ssh_trust(ssh->s, 1, 0);
return;
}
char m[600];
if (known == DMC_SSH_HOST_CHANGED || known == DMC_SSH_HOST_OTHER_TYPE) {
_snprintf(m, sizeof(m),
"\r\n\x1b[1;31mThe server's host key has changed (it is now %.*s %s).\r\n"
"Someone may be in the middle; or the server has a new key. If that is\r\n"
"expected, remove its old line from .ssh\\known_hosts in your profile.\x1b[0m\r\n",
tl, key, fp);
m[sizeof(m) - 1] = '\0';
show_line(m);
dmc_ssh_trust(ssh->s, 0, 0);
return;
}
Ssh *c = ssh;
_snprintf(m, sizeof(m), "This server is not known yet. Its key's fingerprint is\n\n"
"%.*s %s\n\nIf it's the one you expect, it will be added to "
".ssh\\known_hosts in your profile.\n\nConnect?", tl, key, fp);
m[sizeof(m) - 1] = '\0';
int r = MessageBox(app.main, m, "Connect to a new server?",
MB_YESNO | MB_ICONQUESTION);
/* (the connection may have gone while it asked) */
if (c == ssh)
dmc_ssh_trust(ssh->s, r == IDYES, 1);
}
/* a password or the server's questions, asked */
static void ssh_ask(const char *head, const char *text, int prompts)
{
Ssh *c = ssh;
Ask a;
memset(&a, 0, sizeof(a));
a.head = head;
a.text = text;
a.prompts = prompts > 4 ? 4 : prompts;
INT_PTR r = DialogBoxParam(app.inst, MAKEINTRESOURCE(IDD_ASK), app.main,
ask_proc, (LPARAM)&a);
if (c != ssh)
return;
if (r != IDOK)
dmc_ssh_auth_cancel(ssh->s);
else if (!prompts)
dmc_ssh_auth_password(ssh->s, a.answers[0]);
else {
for (int i = 0; i < a.prompts; i++)
dmc_ssh_answer(ssh->s, i, a.answers[i]);
dmc_ssh_answered(ssh->s);
}
SecureZeroMemory(&a, sizeof(a));
}
/* what's tried, in OpenSSH's order: its keys, then the server's
questions or a password (three times at most) */
static void ssh_auth(int methods, const char *why)
{
if ((methods & DMC_SSH_AUTH_PUBLICKEY) && !tried_keys) {
tried_keys = 1;
dmc_ssh_auth_auto(ssh->s);
return;
}
if (asks++ >= 3) {
dmc_ssh_auth_cancel(ssh->s);
return;
}
char host[256], head[300];
GetWindowText(host_ed, host, sizeof(host));
_snprintf(head, sizeof(head), "Log in to %s", host);
head[sizeof(head) - 1] = '\0';
if (methods & DMC_SSH_AUTH_INTERACTIVE)
dmc_ssh_auth_interactive(ssh->s);
else if (methods & DMC_SSH_AUTH_PASSWORD)
ssh_ask(head, asks > 1 ? why : "", 0);
else
dmc_ssh_auth_cancel(ssh->s);
}
void remote_ssh(LPARAM l)
{
SshMsg *m = (SshMsg *)l;
Ssh *c = m->ssh;
if (m->type == DMC_SSH_EV_CLOSED) {
/* (its thread has ended: the connection can go) */
WaitForSingleObject(c->thread, INFINITE);
CloseHandle(c->thread);
dmc_ssh_free(c->s);
free(c);
if (c == ssh) {
ssh = NULL;
shell = 0;
if (!m->data && exit_status > 0) {
char why[64];
_snprintf(why, sizeof(why), "the shell exited with status %d",
exit_status);
why[sizeof(why) - 1] = '\0';
ended(why);
} else {
ended(m->data);
}
}
} else if (c == ssh) {
switch (m->type) {
case DMC_SSH_EV_HOSTKEY:
ssh_hostkey(m->data, m->value);
break;
case DMC_SSH_EV_AUTH:
ssh_auth(m->value, m->data ? m->data : "");
break;
case DMC_SSH_EV_PROMPTS:
if (m->value == 0)
dmc_ssh_answered(ssh->s);
else
ssh_ask(m->data && *m->data ? m->data : "The server asks",
dmc_ssh_instruction(ssh->s), m->value);
break;
case DMC_SSH_EV_READY:
if (m->data && *m->data)
show(m->data, m->len);
shell = dmc_ssh_shell(ssh->s, "xterm-256color", cols, rows, 0);
set_status("Connected by SSH");
break;
case DMC_SSH_EV_OPEN:
if (!m->value) {
show_line("\r\n[The server refused the shell]\r\n");
dmc_ssh_disconnect(ssh->s);
}
break;
case DMC_SSH_EV_DATA:
if (m->channel == shell)
show(m->data, m->len);
break;
case DMC_SSH_EV_EXIT:
if (m->channel == shell)
exit_status = m->value;
break;
case DMC_SSH_EV_CLOSE:
/* (the shell's over: so is the connection) */
if (m->channel == shell)
dmc_ssh_disconnect(ssh->s);
break;
case DMC_SSH_EV_INCOMING:
dmc_ssh_close(ssh->s, m->channel);
break;
}
}
free(m->data);
free(m);
}
static bool start_ssh(const char *host, int port, const char *user)
{
char me[128];
DWORD n = sizeof(me);
if (!*user && GetUserName(me, &n))
user = me;
dmc_ssh *s = dmc_ssh_new(host, port, user);
if (!s) {
app_message("Could not start SSH");
return false;
}
/* OpenSSH's config and known hosts, in the profile's .ssh */
dmc_ssh_option(s, "config", "");
dmc_ssh_option(s, "knownhosts", "");
Ssh *c = (Ssh *)calloc(1, sizeof(Ssh));
c->s = s;
DWORD id;
c->thread = CreateThread(NULL, 0, ssh_poll, c, 0, &id);
if (!c->thread) {
dmc_ssh_free(s);
free(c);
app_message("Could not start SSH");
return false;
}
ssh = c;
shell = 0;
tried_keys = 0;
asks = 0;
exit_status = 0;
return true;
}
#else
static bool start_ssh(const char *host, int port, const char *user)
{
if (!conpty_available()) {
@@ -418,6 +799,12 @@ static bool start_ssh(const char *host, int port, const char *user)
return true;
}
void remote_ssh(LPARAM l)
{
(void)l;
}
#endif
static bool start_socket(int proto, const char *host, int port,
const char *user)
{
@@ -512,8 +899,10 @@ static void connect_clicked()
set_status("Not connected");
return;
}
#ifndef DMODEM_HAVE_SSH
if (proto == DMC_NET_SSH)
set_status("Connected by SSH");
#endif
running = proto;
SetTimer(app.main, TIMER_REMOTE, 30, NULL);
controls();
+8
View File
@@ -125,4 +125,12 @@
#define IDC_S_RANGE 955
#define IDC_S_DEFAULT 956
/* the Remote page's SSH questions: a heading, words, four answers */
#define IDD_ASK 960
#define IDC_A_HEAD 961
#define IDC_A_TEXT 962
#define IDC_A_Q0 963
#define IDC_A_E0 967
#define IDC_A_E0P 971
#endif