aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2024-10-12 17:02:31 +0200
committerbptato <nincsnevem662@gmail.com>2024-10-12 16:43:14 +0200
commit828716e78b5b1a9fea93c2839d89e189c1fcb252 (patch)
tree3e58703add34cb9c9e73c9c46864f2acb68d8a37
parent9e9a56516e1eca1b1eacc9fa4b1eef85e15e182c (diff)
downloadchawan-828716e78b5b1a9fea93c2839d89e189c1fcb252.tar.gz
dirlist: separate out into dirlist2html
Now the dirlist parser lives inside dirlist2html, and the file protocol just emulates FTP LIST.
-rw-r--r--Makefile11
-rw-r--r--adapter/format/ansi2html.nim2
-rw-r--r--adapter/format/dirlist2html.nim172
-rw-r--r--adapter/protocol/dirlist.nim60
-rw-r--r--adapter/protocol/file.nim83
-rw-r--r--adapter/protocol/ftp.nim91
-rw-r--r--adapter/protocol/sftp.nim91
-rw-r--r--res/mailcap1
8 files changed, 232 insertions, 279 deletions
diff --git a/Makefile b/Makefile
index a2cc9bf2..85dc38c5 100644
--- a/Makefile
+++ b/Makefile
@@ -50,6 +50,7 @@ all: $(OUTDIR_BIN)/cha $(OUTDIR_BIN)/mancha $(OUTDIR_CGI_BIN)/http \
$(OUTDIR_CGI_BIN)/gopher $(OUTDIR_LIBEXEC)/gopher2html \
$(OUTDIR_CGI_BIN)/cha-finger $(OUTDIR_CGI_BIN)/about \
$(OUTDIR_CGI_BIN)/file $(OUTDIR_CGI_BIN)/ftp $(OUTDIR_CGI_BIN)/sftp \
+ $(OUTDIR_LIBEXEC)/dirlist2html \
$(OUTDIR_CGI_BIN)/man $(OUTDIR_CGI_BIN)/spartan \
$(OUTDIR_CGI_BIN)/stbi $(OUTDIR_CGI_BIN)/jebp $(OUTDIR_CGI_BIN)/canvas \
$(OUTDIR_CGI_BIN)/sixel $(OUTDIR_CGI_BIN)/resize \
@@ -91,13 +92,14 @@ dynstream = src/io/dynstream.nim src/io/serversocket.nim
lcgi = $(dynstream) $(twtstr) adapter/protocol/lcgi.nim
lcgi_ssl = $(lcgi) adapter/protocol/lcgi_ssl.nim
curl = adapter/protocol/curl.nim adapter/protocol/curlerrors.nim
+
$(OUTDIR_CGI_BIN)/man: lib/monoucha/monoucha/jsregex.nim \
lib/monoucha/monoucha/libregexp.nim $(twtstr)
$(OUTDIR_CGI_BIN)/http: $(curl) src/utils/sandbox.nim
$(OUTDIR_CGI_BIN)/about: res/chawan.html res/license.md
-$(OUTDIR_CGI_BIN)/file: $(twtstr) adapter/protocol/dirlist.nim src/utils/strwidth.nim
-$(OUTDIR_CGI_BIN)/ftp: $(lcgi) adapter/protocol/dirlist.nim src/utils/strwidth.nim
-$(OUTDIR_CGI_BIN)/sftp: $(curl) $(twtstr) src/utils/strwidth.nim adapter/protocol/dirlist.nim
+$(OUTDIR_CGI_BIN)/file: $(twtstr)
+$(OUTDIR_CGI_BIN)/ftp: $(lcgi)
+$(OUTDIR_CGI_BIN)/sftp: $(curl) $(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 \
@@ -114,6 +116,7 @@ $(OUTDIR_LIBEXEC)/urlenc: $(twtstr)
$(OUTDIR_LIBEXEC)/gopher2html: adapter/gophertypes.nim $(twtstr)
$(OUTDIR_LIBEXEC)/ansi2html: src/types/color.nim src/io/poll.nim $(twtstr) $(dynstream)
$(OUTDIR_LIBEXEC)/md2html: $(twtstr)
+$(OUTDIR_LIBEXEC)/dirlist2html: $(twtstr) src/utils/strwidth.nim
$(OUTDIR_CGI_BIN)/%: adapter/protocol/%.nim
@mkdir -p "$(OUTDIR_CGI_BIN)"
@@ -169,7 +172,7 @@ manpage: $(manpages:%=doc/%)
protocols = http about file ftp sftp gopher gemini cha-finger man spartan stbi \
jebp sixel canvas resize
-converters = gopher2html md2html ansi2html gmi2html
+converters = gopher2html md2html ansi2html gmi2html dirlist2html
tools = urlenc
.PHONY: install
diff --git a/adapter/format/ansi2html.nim b/adapter/format/ansi2html.nim
index 6f54c3a1..28217b8d 100644
--- a/adapter/format/ansi2html.nim
+++ b/adapter/format/ansi2html.nim
@@ -353,7 +353,7 @@ proc processData(state: var State; buf: openArray[char]) =
else: state.putc(c)
proc usage() =
- stderr.write("Usage: ansihtml [-s] [-t title]\n")
+ stderr.write("Usage: ansi2html [-s] [-t title]\n")
quit(1)
proc main() =
diff --git a/adapter/format/dirlist2html.nim b/adapter/format/dirlist2html.nim
new file mode 100644
index 00000000..a64eec9a
--- /dev/null
+++ b/adapter/format/dirlist2html.nim
@@ -0,0 +1,172 @@
+import std/algorithm
+import std/options
+import std/os
+import std/strutils
+
+import utils/strwidth
+import utils/twtstr
+
+type DirlistItemType = enum
+ ditFile, ditLink, ditDir
+
+type DirlistItem = object
+ name: string
+ modified: string
+ case t: DirlistItemType
+ of ditLink:
+ linkto: string
+ of ditFile:
+ nsize: int
+ of ditDir:
+ discard
+
+type NameWidthTuple = tuple[name: string, width: int, item: ptr DirlistItem]
+
+func makeDirlist(items: seq[DirlistItem]): string =
+ var names: seq[NameWidthTuple] = @[]
+ var maxw = 20
+ for item in items:
+ var name = item.name
+ if item.t == ditLink:
+ name &= '@'
+ elif item.t == ditDir:
+ name &= '/'
+ let w = name.width()
+ maxw = max(w, maxw)
+ names.add((name, w, unsafeAddr item))
+ names.sort(proc(a, b: NameWidthTuple): int =
+ if a.item.t == ditDir and b.item.t != ditDir:
+ return -1
+ if a.item.t != ditDir and b.item.t == ditDir:
+ return 1
+ return cmp(a.name, b.name)
+ )
+ var outs = "<A HREF=\"../\">[Upper Directory]</A>\n"
+ for (name, width, itemp) in names.mitems:
+ let item = itemp[]
+ var path = percentEncode(item.name, PathPercentEncodeSet)
+ if item.t == ditLink:
+ if item.linkto.len > 0 and item.linkto[^1] == '/':
+ # If the target is a directory, treat it as a directory. (For FTP.)
+ path &= '/'
+ elif item.t == ditDir:
+ path &= '/'
+ var line = "<A HREF=\"" & path & "\">" & htmlEscape(name) & "</A>"
+ while width <= maxw:
+ if width mod 2 == 0:
+ line &= ' '
+ else:
+ line &= '.'
+ inc width
+ if line[^1] != ' ':
+ line &= ' '
+ line &= htmlEscape(item.modified)
+ if item.t == ditFile:
+ line &= ' ' & convertSize(item.nsize)
+ elif item.t == ditLink:
+ line &= " -> " & htmlEscape(item.linkto)
+ outs &= line & '\n'
+ return outs
+
+proc usage() =
+ stderr.write("Usage: dirlist2html [-t title]\n")
+ quit(1)
+
+proc main() =
+ # parse args
+ let H = paramCount()
+ var i = 1
+ var title = ""
+ while i <= H:
+ let s = paramStr(i)
+ if s == "":
+ inc i
+ if s[0] != '-':
+ usage()
+ for j in 1 ..< s.len:
+ case s[j]
+ of 't':
+ inc i
+ if i > H: usage()
+ title = paramStr(i).percentDecode()
+ else:
+ usage()
+ inc i
+ if title != "":
+ stdout.write("""
+<!DOCTYPE html>
+<head>
+<title>""" & title.htmlEscape() & """</title>
+</head>
+<body>
+<h1>""" & title.htmlEscape() & """</h1>
+<pre>""")
+ var items: seq[DirlistItem] = @[]
+ var line: string
+ while stdin.readLine(line):
+ if line.len == 0: continue
+ var i = 10 # permission
+ template skip_till_space =
+ while i < line.len and line[i] != ' ':
+ inc i
+ # link count
+ i = line.skipBlanks(i)
+ while i < line.len and line[i] in AsciiDigit:
+ inc i
+ # owner
+ i = line.skipBlanks(i)
+ skip_till_space
+ # group
+ i = line.skipBlanks(i)
+ while i < line.len and line[i] != ' ':
+ inc i
+ # size
+ i = line.skipBlanks(i)
+ var sizes = ""
+ while i < line.len and line[i] in AsciiDigit:
+ sizes &= line[i]
+ inc i
+ let nsize = parseInt64(sizes).get(-1)
+ # date
+ i = line.skipBlanks(i)
+ let datestarti = i
+ skip_till_space # m
+ i = line.skipBlanks(i)
+ skip_till_space # d
+ i = line.skipBlanks(i)
+ skip_till_space # y
+ let dates = line.substr(datestarti, i)
+ inc i
+ var j = line.len
+ if line[^1] == '\r':
+ dec j
+ let name = line.substr(i, j - 1)
+ if name == "." or name == "..": continue
+ case line[0]
+ of 'l': # link
+ let linki = name.find(" -> ")
+ let linkfrom = name.substr(0, linki - 1)
+ let linkto = name.substr(linki + 4) # you?
+ items.add(DirlistItem(
+ t: ditLink,
+ name: linkfrom,
+ modified: dates,
+ linkto: linkto
+ ))
+ of 'd': # directory
+ items.add(DirlistItem(
+ t: ditDir,
+ name: name,
+ modified: dates
+ ))
+ else: # file
+ items.add(DirlistItem(
+ t: ditFile,
+ name: name,
+ modified: dates,
+ nsize: int(nsize)
+ ))
+ stdout.write(makeDirlist(items))
+ stdout.write("</pre></body>")
+
+main()
diff --git a/adapter/protocol/dirlist.nim b/adapter/protocol/dirlist.nim
deleted file mode 100644
index 18c4a710..00000000
--- a/adapter/protocol/dirlist.nim
+++ /dev/null
@@ -1,60 +0,0 @@
-import algorithm
-
-import utils/strwidth
-import utils/twtstr
-
-type DirlistItemType* = enum
- ditFile, ditLink, ditDir
-
-type DirlistItem* = object
- name*: string
- modified*: string
- case t*: DirlistItemType
- of ditLink:
- linkto*: string
- of ditFile:
- nsize*: int
- of ditDir:
- discard
-
-type NameWidthTuple = tuple[name: string, width: int, item: ptr DirlistItem]
-
-func makeDirlist*(items: seq[DirlistItem]): string =
- var names: seq[NameWidthTuple]
- var maxw = 20
- for item in items:
- var name = item.name
- if item.t == ditLink:
- name &= '@'
- elif item.t == ditDir:
- name &= '/'
- let w = name.width()
- maxw = max(w, maxw)
- names.add((name, w, unsafeAddr item))
- names.sort(proc(a, b: NameWidthTuple): int = cmp(a.name, b.name))
- var outs = "<A HREF=\"../\">[Upper Directory]</A>\n"
- for (name, width, itemp) in names.mitems:
- let item = itemp[]
- var path = percentEncode(item.name, PathPercentEncodeSet)
- if item.t == ditLink:
- if item.linkto.len > 0 and item.linkto[^1] == '/':
- # If the target is a directory, treat it as a directory. (For FTP.)
- path &= '/'
- elif item.t == ditDir:
- path &= '/'
- var line = "<A HREF=\"" & path & "\">" & htmlEscape(name) & "</A>"
- while width <= maxw:
- if width mod 2 == 0:
- line &= ' '
- else:
- line &= '.'
- inc width
- if line[^1] != ' ':
- line &= ' '
- line &= htmlEscape(item.modified)
- if item.t == ditFile:
- line &= ' ' & convertSize(item.nsize)
- elif item.t == ditLink:
- line &= " -> " & htmlEscape(item.linkto)
- outs &= line & '\n'
- return outs
diff --git a/adapter/protocol/file.nim b/adapter/protocol/file.nim
index bf135180..9ae7fd8a 100644
--- a/adapter/protocol/file.nim
+++ b/adapter/protocol/file.nim
@@ -1,9 +1,6 @@
-import std/algorithm
import std/os
import std/times
-import dirlist
-
import utils/twtstr
proc loadDir(path, opath: string) =
@@ -13,56 +10,54 @@ proc loadDir(path, opath: string) =
var base = "file://" & opath
if base[^1] != '/': #TODO dos/windows
base &= '/'
- stdout.write("Content-Type: text/html\n\n")
- stdout.write("""
-<HTML>
-<HEAD>
-<BASE HREF="""" & base & """">
-<TITLE>Directory list of """ & path & """</TITLE>
-</HEAD>
-<BODY>
-<H1>Directory list of """ & path & """</H1>
-<PRE>
-""")
- var fs: seq[(PathComponent, string)]
+ let title = percentEncode("Directory list of " & path,
+ ComponentPercentEncodeSet)
+ stdout.write("Content-Type: text/x-dirlist;title=" & title & "\n\n")
for pc, file in walkDir(path, relative = true):
- fs.add((pc, file))
- fs.sort(cmp = proc(a, b: (PathComponent, string)): int = cmp(a[1], b[1]))
- var items: seq[DirlistItem]
- for (pc, file) in fs:
let fullpath = path / file
var info: FileInfo
try:
info = getFileInfo(fullpath, followSymlink = false)
except OSError:
continue
- let modified = $info.lastWriteTime.local().format("MMM/dd/yyyy HH:MM")
- case pc
- of pcDir:
- items.add(DirlistItem(
- t: ditDir,
- name: file,
- modified: modified
- ))
- of pcFile:
- items.add(DirlistItem(
- t: ditFile,
- name: file,
- modified: modified,
- nsize: int(info.size)
- ))
- of pcLinkToDir, pcLinkToFile:
+ const TypeMap = [
+ pcFile: '-',
+ pcLinkToFile: 'l',
+ pcDir: 'd',
+ pcLinkToDir: 'l'
+ ]
+ var line = $TypeMap[pc]
+ const PermMap = {
+ fpUserRead: 'r',
+ fpUserWrite: 'w',
+ fpUserExec: 'x',
+ fpGroupRead: 'r',
+ fpGroupWrite: 'w',
+ fpGroupExec: 'x',
+ fpOthersRead: 'r',
+ fpOthersWrite: 'w',
+ fpOthersExec: 'x'
+ }
+ for (perm, c) in PermMap:
+ if perm in info.permissions:
+ line &= c
+ else:
+ line &= '-'
+ line &= ' ' & $info.linkCount & ' '
+ line &= "0 " # owner, currently unused
+ line &= "0 " # group, currently unused
+ line &= $info.size & ' '
+ #TODO if new enough, send time instead of year
+ let modified = $info.lastWriteTime.local().format("MMM dd yyyy")
+ line &= $modified & ' '
+ if pc in {pcLinkToDir, pcLinkToFile}:
var target = expandSymlink(fullpath)
- if pc == pcLinkToDir:
+ if pc == pcLinkToDir and target.len == 0 or target[^1] != '/':
target &= '/'
- items.add(DirlistItem(
- t: ditLink,
- name: file,
- modified: modified,
- linkto: target
- ))
- stdout.write(makeDirlist(items))
- stdout.write("\n</PRE>\n</BODY>\n</HTML>\n")
+ line &= file & " -> " & target
+ else:
+ line &= file
+ stdout.writeLine(line)
proc loadFile(f: File) =
# No headers, we'll let the browser figure out the file type.
diff --git a/adapter/protocol/ftp.nim b/adapter/protocol/ftp.nim
index 986380d9..10219443 100644
--- a/adapter/protocol/ftp.nim
+++ b/adapter/protocol/ftp.nim
@@ -4,78 +4,9 @@ import std/posix
import std/strutils
import lcgi
-import dirlist
import utils/twtstr
-proc finish(buffer: string) =
- var items: seq[DirlistItem] = @[]
- for line in buffer.split('\n'):
- if line.len == 0: continue
- var i = 10 # permission
- template skip_till_space =
- while i < line.len and line[i] != ' ':
- inc i
- # link count
- i = line.skipBlanks(i)
- while i < line.len and line[i] in AsciiDigit:
- inc i
- # owner
- i = line.skipBlanks(i)
- skip_till_space
- # group
- i = line.skipBlanks(i)
- while i < line.len and line[i] != ' ':
- inc i
- # size
- i = line.skipBlanks(i)
- var sizes = ""
- while i < line.len and line[i] in AsciiDigit:
- sizes &= line[i]
- inc i
- let nsize = parseInt64(sizes).get(-1)
- # date
- i = line.skipBlanks(i)
- let datestarti = i
- skip_till_space # m
- i = line.skipBlanks(i)
- skip_till_space # d
- i = line.skipBlanks(i)
- skip_till_space # y
- let dates = line.substr(datestarti, i)
- inc i
- var j = line.len
- if line[^1] == '\r':
- dec j
- let name = line.substr(i, j - 1)
- if name == "." or name == "..": continue
- case line[0]
- of 'l': # link
- let linki = name.find(" -> ")
- let linkfrom = name.substr(0, linki - 1)
- let linkto = name.substr(linki + 4) # you?
- items.add(DirlistItem(
- t: ditLink,
- name: linkfrom,
- modified: dates,
- linkto: linkto
- ))
- of 'd': # directory
- items.add(DirlistItem(
- t: ditDir,
- name: name,
- modified: dates
- ))
- else: # file
- items.add(DirlistItem(
- t: ditFile,
- name: name,
- modified: dates,
- nsize: int(nsize)
- ))
- stdout.write(makeDirlist(items))
- stdout.write("\n</PRE>\n</BODY>\n</HTML>\n")
-
proc sendCommand(os, ps: PosixStream; cmd, param: string; outs: var string):
int32 =
if cmd != "":
@@ -186,23 +117,17 @@ proc main() =
if dirmode:
if os.sendCommand(ps, "LIST", "", obuf) == 550:
os.sdie(404, "Not found", obuf)
- os.sendDataLoop("""Content-Type: text/html
-
-<HTML>
-<BODY>
-<H1>Index of """ & htmlEscape(path) & """</H1>
-<PRE>""")
- let buffer = passive.recvAll()
- finish(buffer)
+ let title = percentEncode("Index of " & path, ComponentPercentEncodeSet)
+ os.sendDataLoop("Content-Type: text/x-dirlist;title=" & title & "\n\n")
else:
if os.sendCommand(ps, "RETR", path, obuf) == 550:
os.sdie(404, "Not found", obuf)
os.sendDataLoop("\n")
- var buffer {.noinit.}: array[4096, uint8]
- while true:
- let n = passive.recvData(buffer)
- if n == 0:
- break
- os.sendDataLoop(buffer.toOpenArray(0, n - 1))
+ var buffer {.noinit.}: array[4096, uint8]
+ while true:
+ let n = passive.recvData(buffer)
+ if n == 0:
+ break
+ os.sendDataLoop(buffer.toOpenArray(0, n - 1))
main()
diff --git a/adapter/protocol/sftp.nim b/adapter/protocol/sftp.nim
index a7dae913..82c52cd2 100644
--- a/adapter/protocol/sftp.nim
+++ b/adapter/protocol/sftp.nim
@@ -1,11 +1,9 @@
-import std/options
import std/os
import std/strutils
import curl
import curlerrors
import curlwrap
-import dirlist
import utils/twtstr
@@ -19,17 +17,9 @@ type FtpHandle = ref object
proc printHeader(op: FtpHandle) =
if op.dirmode:
- stdout.write("""Content-Type: text/html
-
-<HTML>
-<HEAD>
-<BASE HREF=""" & op.base & """>
-<TITLE>""" & op.path & """</TITLE>
-</HEAD>
-<BODY>
-<H1>Index of """ & htmlEscape(op.path) & """</H1>
-<PRE>
-""")
+ let title = percentEncode("Index of " & op.path,
+ ComponentPercentEncodeSet)
+ stdout.write("Content-Type: text/x-dirlist;title=" & title & "\n\n")
else:
stdout.write('\n')
@@ -77,80 +67,9 @@ proc curlWriteBody(p: cstring; size, nmemb: csize_t; userdata: pointer):
op.statusline = true
op.printHeader()
if nmemb > 0:
- if op.dirmode:
- let i = op.buffer.len
- op.buffer.setLen(op.buffer.len + int(nmemb))
- copyMem(addr op.buffer[i], p, nmemb)
- else:
- return csize_t(stdout.writeBuffer(p, int(nmemb)))
+ return csize_t(stdout.writeBuffer(p, int(nmemb)))
return nmemb
-proc finish(op: FtpHandle) =
- let op = op
- var items: seq[DirlistItem] = @[]
- for line in op.buffer.split('\n'):
- if line.len == 0: continue
- var i = 10 # permission
- template skip_till_space =
- while i < line.len and line[i] != ' ':
- inc i
- # link count
- i = line.skipBlanks(i)
- while i < line.len and line[i] in AsciiDigit:
- inc i
- # owner
- i = line.skipBlanks(i)
- skip_till_space
- # group
- i = line.skipBlanks(i)
- while i < line.len and line[i] != ' ':
- inc i
- # size
- i = line.skipBlanks(i)
- var sizes = ""
- while i < line.len and line[i] in AsciiDigit:
- sizes &= line[i]
- inc i
- let nsize = parseInt64(sizes).get(-1)
- # date
- i = line.skipBlanks(i)
- let datestarti = i
- skip_till_space # m
- i = line.skipBlanks(i)
- skip_till_space # d
- i = line.skipBlanks(i)
- skip_till_space # y
- let dates = line.substr(datestarti, i)
- inc i
- let name = line.substr(i)
- if name == "." or name == "..": continue
- case line[0]
- of 'l': # link
- let linki = name.find(" -> ")
- let linkfrom = name.substr(0, linki - 1)
- let linkto = name.substr(linki + 4) # you?
- items.add(DirlistItem(
- t: ditLink,
- name: linkfrom,
- modified: dates,
- linkto: linkto
- ))
- of 'd': # directory
- items.add(DirlistItem(
- t: ditDir,
- name: name,
- modified: dates
- ))
- else: # file
- items.add(DirlistItem(
- t: ditFile,
- name: name,
- modified: dates,
- nsize: int(nsize)
- ))
- stdout.write(makeDirlist(items))
- stdout.write("\n</PRE>\n</BODY>\n</HTML>\n")
-
proc matchesPattern(s, pat: openArray[char]): bool =
var i = 0
for j, c in pat:
@@ -310,8 +229,6 @@ proc main() =
stdout.write("Status: 401\n")
else:
stdout.write(getCurlConnectionError(res))
- elif op.dirmode:
- op.finish()
curl_url_cleanup(url)
curl_easy_cleanup(curl)
diff --git a/res/mailcap b/res/mailcap
index 56c6582e..5e473b11 100644
--- a/res/mailcap
+++ b/res/mailcap
@@ -4,3 +4,4 @@ text/gopher; "$CHA_LIBEXEC_DIR"/gopher2html -u "$MAILCAP_URL"; x-htmloutput
text/gemini; "$CHA_LIBEXEC_DIR"/gmi2html; x-htmloutput
text/markdown; "$CHA_LIBEXEC_DIR"/md2html; x-htmloutput
text/x-ansi; "$CHA_LIBEXEC_DIR"/ansi2html -st '%{title}'; x-htmloutput
+text/x-dirlist; "$CHA_LIBEXEC_DIR"/dirlist2html -t '%{title}'; x-htmloutput