From b3dbb89529a9f4ea5e2029a09e64d675ef7fb595 Mon Sep 17 00:00:00 2001 From: Emery Hemingway Date: Wed, 7 Jun 2023 13:15:05 +0100 Subject: [PATCH] ssh server Bad idea, use unix:// instead --- Tuprules.tup | 1 + src/nix_actor.nim | 12 +++++++++++- src/nix_actor/sockets.nim | 34 +++++++++++++++++++++++++++++----- 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/Tuprules.tup b/Tuprules.tup index f28e9b7..0d43639 100644 --- a/Tuprules.tup +++ b/Tuprules.tup @@ -1,4 +1,5 @@ include ../syndicate-nim/depends.tup NIM_FLAGS += --path:$(TUP_CWD)/../syndicate-nim/src +NIM_FLAGS += --path:$(TUP_CWD)/../libssh/src NIM_FLAGS += --backend:cpp diff --git a/src/nix_actor.nim b/src/nix_actor.nim index 443dc0b..769d9e0 100644 --- a/src/nix_actor.nim +++ b/src/nix_actor.nim @@ -112,16 +112,26 @@ type dataspace: Ref SocketArgs {.preservesDictionary.} = object `listen-socket`: string + ServeSshArgs {.preservesDictionary.} = object + `keyfile`: string + `sshhost`: string + `sshport`: int proc bootNixActor(root: Ref; turn: var Turn) = connectStdio(root, turn) + during(turn, root, ?RefArgs) do (ds: Ref): discard bootNixFacet(ds, turn) + during(turn, root, ?SocketArgs) do (path: string): removeFile(path) asyncCheck(turn, emulateSocket(path)) + + during(turn, root, ?ServeSshArgs) do (keyFile: string, host: string, port: int): + let srv = serveSsh(keyFile, host, port) do: - removeFile(path) + stderr.writeLine "stop SSH server" + stop(srv) initNix() # Nix lib isn't actually being used but it's nice to know that it links. runActor("main", bootNixActor) diff --git a/src/nix_actor/sockets.nim b/src/nix_actor/sockets.nim index 8aa9157..7da59aa 100644 --- a/src/nix_actor/sockets.nim +++ b/src/nix_actor/sockets.nim @@ -457,8 +457,32 @@ proc emulateSocket*(path: string) {.async, gcsafe.} = except ProtocolError as err: stderr.writeLine "failed to service client, ", err.msg -when isMainModule: - const path = "/tmp/worker.nix.socket" - if fileExists(path): removeFile(path) - try: waitFor emulateSocket(path) - finally: removeFile(path) +import libssh + +type Server* = ref object + bnd: Bind + callbacks: BindCallbacks + +proc stop*(srv: Server) = + free(srv.bnd) + +proc serveSsh*(keyFile: string, host: string, port: int): Server = + stderr.writeLine "initialize libssh" + libssh.init() + + let srv = Server(bnd: newBind()) + try: + stderr.writeLine "load key ", keyFile + setOption(srv.bnd, SSH_BIND_OPTIONS_HOSTKEY, keyFile) + setOption(srv.bnd, SSH_BIND_OPTIONS_BINDADDR, host) + setOption(srv.bnd, SSH_BIND_OPTIONS_BINDPORT, uint port) + + srv.callbacks.incoming_connection = proc (b: Bind; data: pointer) {.cdecl.} = + let srv = cast[Server](data) + stderr.writeLine "got an incoming connection" + setCallbacks(srv.bnd, addr srv.callbacks, cast[pointer](srv)) + listen(srv.bnd) + return srv + except CatchableError as err: + stop(srv) + raise err