aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2024-10-26 20:44:20 +0200
committerbptato <nincsnevem662@gmail.com>2024-10-26 21:21:06 +0200
commitd34e55343d9588d698ce588bb58f0dc054389f56 (patch)
tree6cf2f5edd20fa749d7904ab2ef0b2b4c7f6bb20b
parenta6238f187656ab312ec97fc730fa4e70b54324b0 (diff)
downloadchawan-d34e55343d9588d698ce588bb58f0dc054389f56.tar.gz
sftp: switch to libssh2
Just to remove a level of indirection; the libcurl API is annoying to deal with when you don't even need asynchrony. It doesn't change anything in actual dependencies, because libcurl uses libssh2 too - however, now only http depends on libcurl, which makes reducing it to an optional module feasible. Still, I've listed libssh2 (along with OpenSSL - long overdue) in the readme just in case some OS doesn't pull in the headers by default as a libcurl dependency. Also, fix some bugs: * fix missing CWD command in FTP * resolve directories even if they don't end in / * allow links without -> in dirlist
-rw-r--r--Makefile5
-rw-r--r--README.md12
-rw-r--r--adapter/format/dirlist2html.nim4
-rw-r--r--adapter/protocol/curlerrors.nim16
-rw-r--r--adapter/protocol/curlwrap.nim22
-rw-r--r--adapter/protocol/ftp.nim19
-rw-r--r--adapter/protocol/http.nim32
-rw-r--r--adapter/protocol/lcgi.nim6
-rw-r--r--adapter/protocol/lcgi_ssl.nim1
-rw-r--r--adapter/protocol/sftp.nim349
10 files changed, 246 insertions, 220 deletions
diff --git a/Makefile b/Makefile
index 5cafcd3b..c834a36f 100644
--- a/Makefile
+++ b/Makefile
@@ -99,15 +99,14 @@ twtstr = src/utils/twtstr.nim src/utils/charcategory.nim src/utils/map.nim \
dynstream = src/io/dynstream.nim src/io/dynstream_aux.c
lcgi = $(dynstream) $(twtstr) adapter/protocol/lcgi.nim
lcgi_ssl = $(lcgi) adapter/protocol/lcgi_ssl.nim
-curl = adapter/protocol/curl.nim adapter/protocol/curlerrors.nim
sandbox = src/utils/sandbox.nim $(chaseccomp)
$(OUTDIR_CGI_BIN)/man: $(twtstr)
-$(OUTDIR_CGI_BIN)/http: $(curl) $(sandbox)
+$(OUTDIR_CGI_BIN)/http: adapter/protocol/curl.nim $(sandbox)
$(OUTDIR_CGI_BIN)/about: res/chawan.html res/license.md
$(OUTDIR_CGI_BIN)/file: $(twtstr)
$(OUTDIR_CGI_BIN)/ftp: $(lcgi)
-$(OUTDIR_CGI_BIN)/sftp: $(curl) $(twtstr)
+$(OUTDIR_CGI_BIN)/sftp: $(lcgi) $(twtstr)
$(OUTDIR_CGI_BIN)/gopher: adapter/gophertypes.nim $(lcgi)
$(OUTDIR_CGI_BIN)/gemini: $(lcgi_ssl)
$(OUTDIR_CGI_BIN)/stbi: adapter/img/stbi.nim adapter/img/stb_image.c \
diff --git a/README.md b/README.md
index 48855e40..c573b5b7 100644
--- a/README.md
+++ b/README.md
@@ -22,14 +22,16 @@ Note: a POSIX-compliant operating system is required.
will not work. (You can check your Nim compiler's version using
`nim -v`.)
3. Install the following dependencies:
- * libcurl: <https://curl.se/libcurl/>
+ * [libcurl](https://curl.se/libcurl/)
+ * [OpenSSL](https://www.openssl.org/) (or
+ [LibreSSL](https://www.libressl.org/))
+ * [libssh2](https://libssh2.org/)
* pkg-config, pkgconf, or similar (must be found as "pkg-config" in your
`$PATH`)
- * GNU make. On systems where it is not the default make, use `gmake`
- in the following steps.
- * Recommended: a termcap library. e.g. ncurses comes with one.
+ * GNU make
+ * Recommended: a termcap library; e.g. ncurses comes with one
* TL;DR for Debian:
- `apt install libcurl4-openssl-dev pkg-config make ncurses-base`
+ `apt install libssh2-1-dev libcurl4-openssl-dev pkg-config make ncurses-base`
4. Download parts of Chawan found in other repositories: `make submodule`
5. Run `make` (without arguments).
6. Install using `make install` (e.g. `sudo make install`).
diff --git a/adapter/format/dirlist2html.nim b/adapter/format/dirlist2html.nim
index d658e2ac..9292b6ea 100644
--- a/adapter/format/dirlist2html.nim
+++ b/adapter/format/dirlist2html.nim
@@ -102,7 +102,9 @@ proc parseInput(f: File; items: var seq[DirlistItem]; maxw: var int) =
continue
case line[0]
of 'l': # link
- let linki = name.find(" -> ")
+ var linki = name.find(" -> ")
+ if linki == -1:
+ linki = name.len
let linkfrom = name.substr(0, linki - 1)
let linkto = name.substr(linki + 4) # you?
items.addItem(DirlistItem(
diff --git a/adapter/protocol/curlerrors.nim b/adapter/protocol/curlerrors.nim
deleted file mode 100644
index 8ad05936..00000000
--- a/adapter/protocol/curlerrors.nim
+++ /dev/null
@@ -1,16 +0,0 @@
-import curl
-
-func curlErrorToChaError*(res: CURLcode): string =
- return case res
- of CURLE_OK: ""
- of CURLE_URL_MALFORMAT: "InvalidURL" #TODO should never occur...
- of CURLE_COULDNT_CONNECT: "ConnectionRefused"
- of CURLE_COULDNT_RESOLVE_PROXY: "FailedToResolveProxy"
- of CURLE_COULDNT_RESOLVE_HOST: "FailedToResolveHost"
- of CURLE_PROXY: "ProxyRefusedToConnect"
- else: "InternalError"
-
-proc getCurlConnectionError*(res: CURLcode): string =
- let e = curlErrorToChaError(res)
- let msg = $curl_easy_strerror(res)
- return "Cha-Control: ConnectionError " & e & " " & msg & "\n"
diff --git a/adapter/protocol/curlwrap.nim b/adapter/protocol/curlwrap.nim
index 0f948542..5708a22a 100644
--- a/adapter/protocol/curlwrap.nim
+++ b/adapter/protocol/curlwrap.nim
@@ -1,23 +1 @@
import curl
-
-template setopt*(curl: CURL; opt: CURLoption; arg: typed) =
- discard curl_easy_setopt(curl, opt, arg)
-
-template setopt*(curl: CURL; opt: CURLoption; arg: string) =
- discard curl_easy_setopt(curl, opt, cstring(arg))
-
-template getinfo*(curl: CURL; info: CURLINFO; arg: typed) =
- discard curl_easy_getinfo(curl, info, arg)
-
-template set*(url: CURLU; part: CURLUPart; content: cstring; flags: cuint) =
- discard curl_url_set(url, part, content, flags)
-
-template set*(url: CURLU; part: CURLUPart; content: string; flags: cuint) =
- url.set(part, cstring(content), flags)
-
-template get*(url: CURLU; part: CURLUPart; flags: cuint): cstring =
- var outs: cstring
- if curl_url_get(url, part, addr outs, flags) == CURLUE_OK:
- outs
- else:
- nil
diff --git a/adapter/protocol/ftp.nim b/adapter/protocol/ftp.nim
index 10219443..c62fe61f 100644
--- a/adapter/protocol/ftp.nim
+++ b/adapter/protocol/ftp.nim
@@ -85,19 +85,11 @@ proc passiveMode(os, ps: PosixStream; host: string; ipv6: bool): PosixStream =
proc main() =
let os = newPosixStream(STDOUT_FILENO)
- var opath = getEnv("MAPPED_URI_PATH")
- if opath == "":
- opath = "/"
- let path = percentDecode(opath)
- let dirmode = path.len > 0 and path[^1] == '/'
let host = getEnv("MAPPED_URI_HOST")
let username = getEnv("MAPPED_URI_USERNAME")
let password = getEnv("MAPPED_URI_PASSWORD")
- var port = getEnv("MAPPED_URI_PORT")
- if port == "":
- port = "21"
+ let port = getEnvEmpty("MAPPED_URI_PORT", "21")
if getEnv("REQUEST_METHOD") != "GET":
- # fail
os.die("InvalidMethod")
var ipv6: bool
let ps = os.connectSocket(host, port, ipv6)
@@ -114,9 +106,12 @@ proc main() =
os.sdie(401, "Unauthorized", obuf)
discard os.sendCommand(ps, "TYPE", "I", obuf) # request raw data
let passive = os.passiveMode(ps, host, ipv6)
- if dirmode:
- if os.sendCommand(ps, "LIST", "", obuf) == 550:
- os.sdie(404, "Not found", obuf)
+ var path = percentDecode(getEnvEmpty("MAPPED_URI_PATH", "/"))
+ if os.sendCommand(ps, "CWD", path, obuf) == 250:
+ if path[^1] != '/':
+ os.sendDataLoop("Status: 301\nLocation: " & path & "/\n")
+ quit(0)
+ discard os.sendCommand(ps, "LIST", "", obuf)
let title = percentEncode("Index of " & path, ComponentPercentEncodeSet)
os.sendDataLoop("Content-Type: text/x-dirlist;title=" & title & "\n\n")
else:
diff --git a/adapter/protocol/http.nim b/adapter/protocol/http.nim
index e220597a..b374fa68 100644
--- a/adapter/protocol/http.nim
+++ b/adapter/protocol/http.nim
@@ -7,8 +7,36 @@ import std/strutils
import utils/sandbox
import curl
-import curlerrors
-import curlwrap
+
+template setopt(curl: CURL; opt: CURLoption; arg: typed) =
+ discard curl_easy_setopt(curl, opt, arg)
+
+template setopt(curl: CURL; opt: CURLoption; arg: string) =
+ discard curl_easy_setopt(curl, opt, cstring(arg))
+
+template getinfo(curl: CURL; info: CURLINFO; arg: typed) =
+ discard curl_easy_getinfo(curl, info, arg)
+
+template set(url: CURLU; part: CURLUPart; content: cstring; flags: cuint) =
+ discard curl_url_set(url, part, content, flags)
+
+template set(url: CURLU; part: CURLUPart; content: string; flags: cuint) =
+ url.set(part, cstring(content), flags)
+
+func curlErrorToChaError(res: CURLcode): string =
+ return case res
+ of CURLE_OK: ""
+ of CURLE_URL_MALFORMAT: "InvalidURL" #TODO should never occur...
+ of CURLE_COULDNT_CONNECT: "ConnectionRefused"
+ of CURLE_COULDNT_RESOLVE_PROXY: "FailedToResolveProxy"
+ of CURLE_COULDNT_RESOLVE_HOST: "FailedToResolveHost"
+ of CURLE_PROXY: "ProxyRefusedToConnect"
+ else: "InternalError"
+
+proc getCurlConnectionError(res: CURLcode): string =
+ let e = curlErrorToChaError(res)
+ let msg = $curl_easy_strerror(res)
+ return "Cha-Control: ConnectionError " & e & " " & msg & "\n"
type
EarlyHintState = enum
diff --git a/adapter/protocol/lcgi.nim b/adapter/protocol/lcgi.nim
index 590c63c8..c73926ec 100644
--- a/adapter/protocol/lcgi.nim
+++ b/adapter/protocol/lcgi.nim
@@ -200,3 +200,9 @@ proc connectSocket*(os: PosixStream; host, port: string; outIpv6: var bool):
proc connectSocket*(os: PosixStream; host, port: string): PosixStream =
var dummy = false
return os.connectSocket(host, port, dummy)
+
+proc getEnvEmpty*(name: string; fallback = ""): string =
+ let res = getEnv(name, fallback)
+ if res != "":
+ return res
+ return fallback
diff --git a/adapter/protocol/lcgi_ssl.nim b/adapter/protocol/lcgi_ssl.nim
index db9562c2..977336c7 100644
--- a/adapter/protocol/lcgi_ssl.nim
+++ b/adapter/protocol/lcgi_ssl.nim
@@ -6,7 +6,6 @@ export lcgi, dynstream, twtstr
const libssl = staticExec("pkg-config --libs --silence-errors libssl libcrypto")
-{.passc: libssl.}
{.passl: libssl.}
type
diff --git a/adapter/protocol/sftp.nim b/adapter/protocol/sftp.nim
index 038307e0..2182a574 100644
--- a/adapter/protocol/sftp.nim
+++ b/adapter/protocol/sftp.nim
@@ -1,74 +1,65 @@
import std/os
import std/strutils
-
-import curl
-import curlerrors
-import curlwrap
+import std/times
import utils/twtstr
-type FtpHandle = ref object
- curl: CURL
- buffer: string
- dirmode: bool
- base: string
- path: string
- statusline: bool
-
-proc printHeader(op: FtpHandle) =
- if op.dirmode:
- let title = percentEncode("Index of " & op.path,
- ComponentPercentEncodeSet)
- stdout.write("Content-Type: text/x-dirlist;title=" & title & "\n\n")
- else:
- stdout.write('\n')
-
-proc curlWriteHeader(p: cstring; size, nitems: csize_t; userdata: pointer):
- csize_t {.cdecl.} =
- var line = newString(nitems)
- if nitems > 0:
- copyMem(addr line[0], p, nitems)
- let op = cast[FtpHandle](userdata)
- if not op.statusline:
- if line.startsWith("150") or line.startsWith("125"):
- op.statusline = true
- var status: clong
- op.curl.getinfo(CURLINFO_RESPONSE_CODE, addr status)
- stdout.write("Status: " & $status & "\n")
- op.printHeader()
- return nitems
- elif line.startsWith("530"): # login incorrect
- op.statusline = true
- var status: clong
- op.curl.getinfo(CURLINFO_RESPONSE_CODE, addr status)
- # unauthorized (shim http)
- stdout.write("""
-Status: 401
-Content-Type: text/html
-
-<HTML>
-<HEAD>
-<TITLE>Unauthorized</TITLE>
-</HEAD>
-<BODY>
-<PRE>
-""" & htmlEscape(line) & """
-</PRE>
-</BODY>
-</HTML>
-""")
- return nitems
-
-# From the documentation: size is always 1.
-proc curlWriteBody(p: cstring; size, nmemb: csize_t; userdata: pointer):
- csize_t {.cdecl.} =
- let op = cast[FtpHandle](userdata)
- if not op.statusline:
- op.statusline = true
- op.printHeader()
- if nmemb > 0:
- return csize_t(stdout.writeBuffer(p, int(nmemb)))
- return nmemb
+import lcgi
+
+const libssh2 = staticExec("pkg-config --libs libssh2")
+
+{.passl: libssh2.}
+
+# libssh2 bindings
+
+type
+ LIBSSH2_SESSION {.importc, header: "<libssh2.h>", incompleteStruct.} = object
+ LIBSSH2_SFTP {.importc, header: "<libssh2_sftp.h>", incompleteStruct.} =
+ object
+ LIBSSH2_SFTP_HANDLE {.importc, header: "<libssh2_sftp.h>",
+ incompleteStruct.} = object
+
+ LIBSSH2_SFTP_ATTRIBUTES {.importc, header: "<libssh2_sftp.h>".} = object
+ flags: culong
+ filesize: uint64
+ uid: culong
+ gid: culong
+ permissions: culong
+ atime: culong
+ mtime: culong
+
+{.push importc, cdecl, header: "<libssh2.h>".}
+
+proc libssh2_init(flags: cint): cint
+proc libssh2_session_init(): ptr LIBSSH2_SESSION {.nodecl.}
+proc libssh2_session_handshake(session: ptr LIBSSH2_SESSION;
+ socket: cint): cint
+proc libssh2_userauth_password(session: ptr LIBSSH2_SESSION;
+ username: cstring; password: cstring): cint {.nodecl.}
+proc libssh2_userauth_publickey_fromfile(session: ptr LIBSSH2_SESSION;
+ username, publickey, privatekey, passphrase: cstring): cint {.nodecl.}
+proc libssh2_session_disconnect(session: ptr LIBSSH2_SESSION;
+ description: cstring): cint {.nodecl.}
+proc libssh2_session_free(session: ptr LIBSSH2_SESSION): cint
+proc libssh2_exit()
+
+{.push header: "<libssh2_sftp.h>".}
+proc libssh2_sftp_init(session: ptr LIBSSH2_SESSION): ptr LIBSSH2_SFTP
+proc libssh2_sftp_opendir(sftp: ptr LIBSSH2_SFTP; path: cstring):
+ ptr LIBSSH2_SFTP_HANDLE {.nodecl.}
+proc libssh2_sftp_readdir_ex(handle: ptr LIBSSH2_SFTP_HANDLE; buffer: ptr char;
+ buffer_maxlen: csize_t; longentry: ptr char; longentry_maxlen: csize_t;
+ attrs: var LIBSSH2_SFTP_ATTRIBUTES): int
+proc libssh2_sftp_readlink(sftp: ptr LIBSSH2_SFTP; path: cstring;
+ target: ptr char; target_len: cuint): cint
+proc libssh2_sftp_open(sftp: ptr LIBSSH2_SFTP; path: cstring; flags: culong;
+ mode: clong): ptr LIBSSH2_SFTP_HANDLE {.nodecl.}
+proc libssh2_sftp_read(handle: ptr LIBSSH2_SFTP_HANDLE; buffer: ptr char;
+ buffer_maxlen: csize_t): int
+proc libssh2_sftp_shutdown(sftp: ptr LIBSSH2_SFTP): cint
+{.pop.}
+
+{.pop.}
proc matchesPattern(s, pat: openArray[char]): bool =
var i = 0
@@ -91,11 +82,9 @@ proc matchesPattern(s: string; pats: openArray[string]): bool =
return true
return false
-proc parseSSHConfig(f: File; curl: CURL; host: string; idSet: var bool) =
+proc parseSSHConfig(f: File; host: string; pubKey, privKey: var string) =
var skipTillNext = false
var line: string
- var certificateFile = ""
- var identityFile = ""
while f.readLine(line):
var i = line.skipBlanks(0)
if i == line.len or line[i] == '#':
@@ -135,102 +124,146 @@ proc parseSSHConfig(f: File; curl: CURL; host: string; idSet: var bool) =
elif k == "IdentityFile":
if args.len != 1:
continue # error
- identityFile = expandTilde(args[0])
+ privKey = expandTilde(args[0])
elif k == "CertificateFile":
if args.len != 1:
continue # error
- certificateFile = expandTilde(args[0])
- if identityFile != "":
- curl.setopt(CURLOPT_SSH_PRIVATE_KEYFILE, identityFile)
- idSet = true
- if certificateFile != "":
- curl.setopt(CURLOPT_SSH_PUBLIC_KEYFILE, certificateFile)
+ pubKey = expandTilde(args[0])
f.close()
-proc main() =
- let curl = curl_easy_init()
- doAssert curl != nil
- var opath = getEnv("MAPPED_URI_PATH")
- if opath == "":
- opath = "/"
- let path = percentDecode(opath)
- let op = FtpHandle(
- curl: curl,
- dirmode: path.len > 0 and path[^1] == '/'
- )
- let url = curl_url()
- const flags = cuint(CURLU_PATH_AS_IS)
- let scheme = getEnv("MAPPED_URI_SCHEME")
- url.set(CURLUPART_SCHEME, scheme, flags)
- let username = getEnv("MAPPED_URI_USERNAME")
- if username != "":
- url.set(CURLUPART_USER, username, flags)
- let host = getEnv("MAPPED_URI_HOST")
- let password = getEnv("MAPPED_URI_PASSWORD")
- var idSet = false
- # Parse SSH config for sftp.
- let systemConfig = "/etc/ssh/ssh_config"
- if fileExists(systemConfig):
- var f: File
- if f.open(systemConfig):
- parseSSHConfig(f, curl, host, idSet)
- let userConfig = expandTilde("~/.ssh/config")
- if fileExists(userConfig):
+proc unauthorized(os: PosixStream; session: ptr LIBSSH2_SESSION) =
+ os.sendDataLoop("Status: 401\n")
+ quit(0)
+
+proc authenticate(os: PosixStream; session: ptr LIBSSH2_SESSION; host: string) =
+ let user = getEnv("MAPPED_URI_USERNAME")
+ let pass = getEnv("MAPPED_URI_PASSWORD")
+ let configs = ["/etc/ssh/ssh_config", expandTilde("~/.ssh/config")]
+ var pubKey = ""
+ var privKey = ""
+ for config in configs:
var f: File
- if f.open(userConfig):
- parseSSHConfig(f, curl, host, idSet)
- if idSet:
- curl.setopt(CURLOPT_KEYPASSWD, password)
- url.set(CURLUPART_PASSWORD, password, flags)
- url.set(CURLUPART_HOST, host, flags)
- let port = getEnv("MAPPED_URI_PORT")
- if port != "":
- url.set(CURLUPART_PORT, port, flags)
- # By default, cURL CWD's into relative paths, and an extra slash is
- # necessary to specify absolute paths.
- # This is incredibly confusing, and probably not what the user wanted.
- # So we work around it by adding the extra slash ourselves.
- #
- # But before that, we take the serialized URL without the path for
- # setting the base URL:
- url.set(CURLUPART_PATH, opath, flags)
- if op.dirmode:
- let surl = url.get(CURLUPART_URL, cuint(CURLU_PUNY2IDN))
- if surl == nil:
- stdout.write("Cha-Control: ConnectionError InvalidURL\n")
- curl_url_cleanup(url)
- curl_easy_cleanup(curl)
- return
- op.base = $surl
- op.path = path
- curl_free(surl)
- # Another hack: if password was set for the identity file, then clear it from
- # the URL.
- if idSet:
- url.set(CURLUPART_PASSWORD, nil, flags)
- # Set opts for the request
- curl.setopt(CURLOPT_CURLU, url)
- curl.setopt(CURLOPT_HEADERDATA, op)
- curl.setopt(CURLOPT_HEADERFUNCTION, curlWriteHeader)
- curl.setopt(CURLOPT_WRITEDATA, op)
- curl.setopt(CURLOPT_WRITEFUNCTION, curlWriteBody)
- curl.setopt(CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_SINGLECWD)
- curl.setopt(CURLOPT_NOSIGNAL, 1)
- let purl = getEnv("ALL_PROXY")
- if purl != "":
- curl.setopt(CURLOPT_PROXY, purl)
- if getEnv("REQUEST_METHOD") != "GET":
- # fail
- stdout.write("Cha-Control: ConnectionError InvalidMethod\n")
+ if f.open(config):
+ parseSSHConfig(f, host, pubKey, privKey)
+ if privKey == "":
+ if session.libssh2_userauth_password(cstring(user), cstring(pass)) != 0:
+ os.unauthorized(session)
else:
- let res = curl_easy_perform(curl)
- if res != CURLE_OK:
- if not op.statusline:
- if res == CURLE_LOGIN_DENIED:
- stdout.write("Status: 401\n")
+ if pubKey == "":
+ pubKey = privKey & ".pub"
+ if session.libssh2_userauth_publickey_fromfile(cstring(user),
+ cstring(pubKey), cstring(privKey), cstring(pass)) != 0:
+ os.unauthorized(session)
+
+const LIBSSH2_SFTP_ATTR_SIZE = 0x1
+const LIBSSH2_SFTP_ATTR_PERMISSIONS = 0x4
+const LIBSSH2_SFTP_ATTR_ACMODTIME = 0x8
+
+const LIBSSH2_FXF_READ = 0x00000001
+
+const LIBSSH2_SFTP_S_IFDIR = 0o040000
+const LIBSSH2_SFTP_S_IFLNK = 0o120000
+
+# The libssh2 documentation is horrid, so I'm mostly looking at the spec
+# here... it seems the server can either send a structured data field
+# ("status") or just a string? sshd seems to always do the latter,
+# but I'm also getting attrs... the example handles both... guess I'll
+# do the same, just to be sure.
+proc readDir(os: PosixStream; sftpSession: ptr LIBSSH2_SFTP;
+ handle: ptr LIBSSH2_SFTP_HANDLE; path: string) =
+ let title = percentEncode("Index of " & path, ComponentPercentEncodeSet)
+ os.sendDataLoop("Content-Type: text/x-dirlist;title=" & title & "\n\n")
+ var buffer {.noinit.}: array[512, char]
+ var longentry {.noinit.}: array[512, char]
+ while true:
+ var attrs: LIBSSH2_SFTP_ATTRIBUTES
+ let n = handle.libssh2_sftp_readdir_ex(addr buffer[0], csize_t(buffer.len),
+ addr longentry[0], csize_t(longentry.len), attrs)
+ if n <= 0:
+ break
+ var name = ""
+ for c in buffer.toOpenArray(0, n - 1):
+ name &= c
+ var buf = ""
+ for c in longentry:
+ if c == '\0':
+ break
+ buf &= c
+ if buf.len == 0:
+ if (attrs.flags and LIBSSH2_SFTP_ATTR_PERMISSIONS) != 0:
+ if (attrs.permissions and LIBSSH2_SFTP_S_IFDIR) != 0:
+ buf &= 'd'
+ elif (attrs.permissions and LIBSSH2_SFTP_S_IFLNK) != 0:
+ buf &= 'l'
else:
- stdout.write(getCurlConnectionError(res))
- curl_url_cleanup(url)
- curl_easy_cleanup(curl)
+ buf &= '-'
+ for i, c in "rwxrwxrwx":
+ if ((attrs.permissions shr (8 - i)) and 1) != 0:
+ buf &= c
+ else:
+ buf &= '-'
+ else:
+ buf &= "----------"
+ buf &= " 0 0 0 "
+ if (attrs.flags and LIBSSH2_SFTP_ATTR_SIZE) != 0:
+ buf &= $attrs.filesize
+ buf &= ' '
+ if (attrs.flags and LIBSSH2_SFTP_ATTR_ACMODTIME) != 0:
+ buf &= int64(attrs.mtime).fromUnix().local().format("MMM dd yyyy")
+ buf &= ' '
+ buf &= name
+ if (attrs.flags and LIBSSH2_SFTP_ATTR_PERMISSIONS) != 0 and
+ (attrs.permissions and LIBSSH2_SFTP_S_IFLNK) != 0 and
+ buf.find(" -> ") == -1:
+ let n = sftpSession.libssh2_sftp_readlink(cstring(path & name),
+ addr buffer[0], cuint(buffer.len))
+ if n > 0:
+ buf &= " -> "
+ for i in 0 ..< n:
+ buf &= buffer[i]
+ buf &= '\n'
+ os.sendDataLoop(buf)
+
+proc readFile(os: PosixStream; sftpSession: ptr LIBSSH2_SFTP; path: string) =
+ let handle = sftpSession.libssh2_sftp_open(cstring(path), LIBSSH2_FXF_READ, 0)
+ if handle == nil:
+ os.sendDataLoop("Status: 404\nContent-Type: text/html\n\n<h1>Not found")
+ quit(0)
+ os.sendDataLoop("\n")
+ var buffer {.noinit.}: array[4096, char]
+ while true:
+ let n = handle.libssh2_sftp_read(addr buffer[0], csize_t(buffer.len))
+ if n <= 0:
+ break
+ os.sendDataLoop(buffer.toOpenArray(0, n - 1))
+
+proc main() =
+ let os = newPosixStream(STDOUT_FILENO)
+ if getEnv("REQUEST_METHOD") != "GET":
+ os.die("InvalidMethod")
+ let host = getEnv("MAPPED_URI_HOST")
+ let port = getEnvEmpty("MAPPED_URI_PORT", "22")
+ let ps = os.connectSocket(host, port)
+ if libssh2_init(0) < 0:
+ os.die("InternalError")
+ let session = libssh2_session_init()
+ if session.libssh2_session_handshake(ps.fd) < 0:
+ os.die("InternalError", "handshake failed")
+ #TODO check known hosts file...
+ os.authenticate(session, host)
+ let sftpSession = libssh2_sftp_init(session)
+ let path = percentDecode(getEnvEmpty("MAPPED_URI_PATH", "/"))
+ let handle = sftpSession.libssh2_sftp_opendir(cstring(path))
+ if handle != nil:
+ if path[^1] != '/':
+ os.sendDataLoop("Status: 301\nLocation: " & path & "/\n")
+ quit(0)
+ os.readDir(sftpSession, handle, path)
+ else:
+ os.readFile(sftpSession, path)
+ discard sftpSession.libssh2_sftp_shutdown()
+ discard session.libssh2_session_disconnect("")
+ discard session.libssh2_session_free()
+ libssh2_exit()
main()