aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2022-09-06 12:33:30 +0200
committerbptato <nincsnevem662@gmail.com>2022-09-06 13:39:26 +0200
commite38402dfa1bbc33db6b9d9736517eb45533d595c (patch)
tree9bbe6a589f1cba631198640bb167a664de69ca12 /src
parent3223a3364ae9f17dd2dc25bcbf2e644380db462f (diff)
downloadchawan-e38402dfa1bbc33db6b9d9736517eb45533d595c.tar.gz
Use unix domain sockets for IPC
Diffstat (limited to 'src')
-rw-r--r--src/bindings/curl.nim4
-rw-r--r--src/io/http.nim52
-rw-r--r--src/io/loader.nim126
-rw-r--r--src/io/request.nim99
-rw-r--r--src/io/serialize.nim1
-rw-r--r--src/io/socketstream.nim37
6 files changed, 195 insertions, 124 deletions
diff --git a/src/bindings/curl.nim b/src/bindings/curl.nim
index db120264..7c88f3f6 100644
--- a/src/bindings/curl.nim
+++ b/src/bindings/curl.nim
@@ -55,6 +55,7 @@ type
CURLOPT_FOLLOWLOCATION = CURLOPTTYPE_LONG + 52
CURLOPT_POSTFIELDSIZE = CURLOPTTYPE_LONG + 60
CURLOPT_HTTPGET = CURLOPTTYPE_LONG + 80
+ CURLOPT_CONNECT_ONLY = CURLOPTTYPE_LONG + 141
# Objectpoint
CURLOPT_WRITEDATA = CURLOPTTYPE_CBPOINT + 1
@@ -89,6 +90,9 @@ type
# Long
CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2
+ # Socket
+ CURLINFO_ACTIVESOCKET = CURLINFO_SOCKET + 44
+
CURLcode* {.size: sizeof(cint).} = enum
CURLE_OK = 0,
CURLE_UNSUPPORTED_PROTOCOL, # 1
diff --git a/src/io/http.nim b/src/io/http.nim
index cda70bf1..f8574790 100644
--- a/src/io/http.nim
+++ b/src/io/http.nim
@@ -1,7 +1,6 @@
import options
import streams
import strutils
-import tables
import bindings/curl
import io/request
@@ -10,12 +9,15 @@ import types/url
import utils/twtstr
type
- HeaderResult* = ref object
+ HeaderOpaque* = ref object
statusline: bool
headers: HeaderList
curl: CURL
- ostream: Stream
request: Request
+ ostream: Stream
+
+func newHeaderOpaque(curl: CURL, request: Request, ostream: Stream): HeaderOpaque =
+ HeaderOpaque(headers: newHeaderList(), curl: curl, ostream: ostream, request: request)
template setopt(curl: CURL, opt: CURLoption, arg: typed) =
discard curl_easy_setopt(curl, opt, arg)
@@ -31,31 +33,24 @@ proc curlWriteHeader(p: cstring, size: csize_t, nitems: csize_t, userdata: point
for i in 0..<nitems:
line[i] = p[i]
- let headers = cast[HeaderResult](userdata)
- if not headers.statusline:
- headers.statusline = true
- headers.ostream.swrite(int(CURLE_OK))
+ let op = cast[HeaderOpaque](userdata)
+ if not op.statusline:
+ op.statusline = true
+ op.ostream.swrite(int(CURLE_OK))
var status: int
- headers.curl.getinfo(CURLINFO_RESPONSE_CODE, addr status)
- headers.ostream.swrite(status)
+ op.curl.getinfo(CURLINFO_RESPONSE_CODE, addr status)
+ op.ostream.swrite(status)
return nitems
let k = line.until(':')
if k.len == line.len:
# empty line (last, before body) or invalid (=> error)
- headers.ostream.swrite(headers.headers.getOrDefault("Content-Type").until(';'))
- var urlp: cstring
- headers.curl.getinfo(CURLINFO_REDIRECT_URL, addr urlp)
- if "Location" in headers.headers.table:
- let location = headers.headers.table["Location"][0]
- headers.ostream.swrite(parseUrl(location, some(headers.request.url)))
- else:
- headers.ostream.swrite(none(Url))
+ op.ostream.swrite(op.headers)
return nitems
let v = line.substr(k.len + 1).strip()
- headers.headers.add(k, v)
+ op.headers.add(k, v)
return nitems
proc curlWriteBody(p: cstring, size: csize_t, nmemb: csize_t, userdata: pointer): csize_t {.cdecl.} =
@@ -64,14 +59,17 @@ proc curlWriteBody(p: cstring, size: csize_t, nmemb: csize_t, userdata: pointer)
s[i] = p[i]
let stream = cast[Stream](userdata)
if nmemb > 0:
- stream.swrite(s)
+ stream.write(s)
stream.flush()
return nmemb
proc loadHttp*(request: Request, ostream: Stream) =
let curl = curl_easy_init()
- if curl == nil: return # fail
+ if curl == nil:
+ ostream.swrite(-1)
+ ostream.flush()
+ return # fail
let surl = request.url.serialize()
curl.setopt(CURLOPT_URL, surl)
@@ -79,7 +77,14 @@ proc loadHttp*(request: Request, ostream: Stream) =
curl.setopt(CURLOPT_WRITEDATA, ostream)
curl.setopt(CURLOPT_WRITEFUNCTION, curlWriteBody)
- let headerres = HeaderResult(headers: newHeaderList(), curl: curl, ostream: ostream, request: request)
+ let headerres = curl.newHeaderOpaque(request, ostream)
+
+ GC_ref(headerres) # this could get unref'd before writeheader finishes
+ GC_ref(ostream) #TODO not sure about this one, but better safe than sorry
+ defer:
+ GC_unref(headerres)
+ GC_unref(ostream)
+
curl.setopt(CURLOPT_HEADERDATA, headerres)
curl.setopt(CURLOPT_HEADERFUNCTION, curlWriteHeader)
@@ -120,10 +125,7 @@ proc loadHttp*(request: Request, ostream: Stream) =
curl.setopt(CURLOPT_HTTPHEADER, slist)
let res = curl_easy_perform(curl)
- if res == CURLE_OK:
- ostream.swrite("")
- ostream.flush()
- else:
+ if res != CURLE_OK:
ostream.swrite(int(res))
ostream.flush()
diff --git a/src/io/loader.nim b/src/io/loader.nim
index 4a1e35e7..31b51930 100644
--- a/src/io/loader.nim
+++ b/src/io/loader.nim
@@ -1,30 +1,44 @@
+# A file loader server (?)
+# The idea here is that we receive requests with a socket, then respond to each
+# with a response (ideally a document.)
+# For now, the protocol looks like:
+# C: Request
+# S: res (0 => success, _ => error)
+# if success:
+# S: status code
+# S: headers
+# S: response body
+#
+# The body is passed to the stream as-is, so effectively nothing can follow it.
+
import options
import streams
import tables
+import net
+import os
when defined(posix):
import posix
import bindings/curl
import io/http
-import io/process
import io/request
import io/serialize
-import types/mime
+import io/socketstream
import types/url
+import utils/twtstr
-const DefaultHeaders = {
+const DefaultHeaders0 = {
"User-Agent": "chawan",
"Accept": "text/html,text/*;q=0.5",
"Accept-Language": "en;q=1.0",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
-}.toTable().newHeaderList()
+}.toTable()
+let DefaultHeaders = DefaultHeaders0.newHeaderList()
type FileLoader* = ref object
defaultHeaders*: HeaderList
- process*: int
- istream*: Stream
- ostream*: Stream
+ process*: Pid
proc loadFile(url: Url, ostream: Stream) =
when defined(windows) or defined(OS2) or defined(DOS):
@@ -33,13 +47,12 @@ proc loadFile(url: Url, ostream: Stream) =
let path = url.path.serialize_unicode()
let istream = newFileStream(path, fmRead)
if istream == nil:
- ostream.swrite(1)
+ ostream.swrite(-1) # error
ostream.flush()
else:
ostream.swrite(0)
ostream.swrite(200) # ok
- ostream.swrite(guessContentType(path))
- ostream.swrite(none(Url))
+ ostream.swrite(newHeaderList())
while not istream.atEnd:
const bufferSize = 4096
var buffer {.noinit.}: array[bufferSize, char]
@@ -47,13 +60,10 @@ proc loadFile(url: Url, ostream: Stream) =
let n = readData(istream, addr buffer[0], bufferSize)
if n == 0:
break
- ostream.swrite(n)
ostream.writeData(addr buffer[0], n)
ostream.flush()
if n < bufferSize:
break
- ostream.swrite("")
- ostream.flush()
proc loadResource(loader: FileLoader, request: Request, ostream: Stream) =
case request.url.scheme
@@ -61,14 +71,31 @@ proc loadResource(loader: FileLoader, request: Request, ostream: Stream) =
loadFile(request.url, ostream)
of "http", "https":
loadHttp(request, ostream)
+ else:
+ ostream.swrite(-1) # error
+ ostream.flush()
+
+const SocketDirectory = "/tmp/cha/"
+const SocketPathPrefix = SocketDirectory & "cha_sock_"
+func getSocketPath(pid: Pid): string =
+ SocketPathPrefix & $pid
proc runFileLoader(loader: FileLoader) =
if curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK:
- eprint "Failed to initialize libcurl."
- quit(1)
- let istream = newFileStream(stdin)
- let ostream = newFileStream(stdout)
+ raise newException(Defect, "Failed to initialize libcurl.")
+ let path = getSocketPath(getpid())
+ discard unlink(cstring(path))
+ createDir(SocketDirectory)
+ let sock = newSocket(Domain.AF_UNIX, SockType.SOCK_STREAM, Protocol.IPPROTO_IP)
+ bindUnix(sock, path)
+ listen(sock)
+ stdout.write(char(0u8))
+ stdout.flushFile()
while true:
+ var sock2: Socket
+ sock.accept(sock2)
+ let istream = newSocketStream(sock2, nil)
+ let ostream = newSocketStream(nil, sock2)
try:
let request = istream.readRequest()
for k, v in loader.defaultHeaders.table:
@@ -79,62 +106,57 @@ proc runFileLoader(loader: FileLoader) =
# End-of-file, quit.
# TODO this should be EOFError
break
- istream.close()
- ostream.close()
+ close(sock2)
curl_global_cleanup()
+ close(sock)
+ discard unlink(cstring(path))
quit(0)
-proc doRequest*(loader: FileLoader, request: Request): LoadResult =
- if loader.istream != nil:
- loader.istream.swrite(request)
- loader.istream.flush()
- loader.ostream.sread(result.res)
- if result.res == 0:
- loader.ostream.sread(result.status)
- loader.ostream.sread(result.contenttype)
- loader.ostream.sread(result.redirect)
- result.body = newReadableStream(loader.ostream)
- else:
- raise newException(Defect, "Error: no loader process")
+proc doRequest*(loader: FileLoader, request: Request): Response =
+ let sock = newSocket(Domain.AF_UNIX, SockType.SOCK_STREAM, Protocol.IPPROTO_IP)
+ let path = getSocketPath(loader.process)
+ connectUnix(sock, path)
+ let istream = newSocketStream(nil, sock)
+ let ostream = newSocketStream(sock, nil)
+ istream.swrite(request)
+ istream.flush()
+ ostream.sread(result.res)
+ if result.res == 0:
+ ostream.sread(result.status)
+ ostream.sread(result.headers)
+ if "Content-Type" in result.headers.table:
+ result.contenttype = result.headers.table["Content-Type"][0].until(';')
+ if "Location" in result.headers.table:
+ let location = result.headers.table["Location"][0]
+ result.redirect = parseUrl(location, some(request.url))
+ # Only a stream of the response body may arrive after this point.
+ result.body = ostream
proc newFileLoader*(defaultHeaders: HeaderList): FileLoader =
new(result)
result.defaultHeaders = defaultHeaders
when defined(posix):
- var pipefd_a: array[0..1, cint]
var pipefd_b: array[0..1, cint]
- if pipe(pipefd_a) == -1:
- eprint "Failed to open pipe."
- quit(1)
if pipe(pipefd_b) == -1:
- eprint "Failed to open pipe."
- quit(1)
- let pid = doFork()
- if pid == 0:
+ raise newException(Defect, "Failed to open pipe.")
+ let pid = fork()
+ if pid == -1:
+ raise newException(Defect, "Failed to fork network process")
+ elif pid == 0:
# child process
- let readfd = pipefd_a[0] # get read a
- discard close(pipefd_a[1]) # close write a
let writefd = pipefd_b[1] # get write b
discard close(pipefd_b[0]) # close read b
- discard dup2(readfd, stdin.getFileHandle())
discard dup2(writefd, stdout.getFileHandle())
result.runFileLoader()
else:
result.process = pid
- let writefd = pipefd_a[1] # get write a
- discard close(pipefd_a[0]) # close read a
let readfd = pipefd_b[0] # get read b
discard close(pipefd_b[1]) # close write b
var readf: File
- var writef: File
if not open(readf, FileHandle(readfd), fmRead):
- eprint "Failed to open output handle."
- quit(1)
- if not open(writef, FileHandle(writefd), fmWrite):
- eprint "Failed to open input handle."
- quit(1)
- result.ostream = newFileStream(readf)
- result.istream = newFileStream(writef)
+ raise newException(Defect, "Failed to open output handle.")
+ var n: uint8
+ assert newFileStream(readf).readUint8() == 0u8
proc newFileLoader*(): FileLoader =
newFileLoader(DefaultHeaders)
diff --git a/src/io/request.nim b/src/io/request.nim
index 789f92aa..7553bdb5 100644
--- a/src/io/request.nim
+++ b/src/io/request.nim
@@ -18,8 +18,8 @@ type
body*: Option[string]
multipart*: Option[MimeData]
- LoadResult* = object
- body*: ReadableStream
+ Response* = object
+ body*: Stream
res*: int
contenttype*: string
status*: int
@@ -31,7 +31,7 @@ type
buf: string
isend: bool
- HeaderList* = object
+ HeaderList* = ref object
table*: Table[string, seq[string]]
# Originally from the stdlib
@@ -52,52 +52,55 @@ iterator pairs*(headers: HeaderList): (string, string) =
for v in vs:
yield (k, v)
+proc rsReadData(s: Stream, buffer: pointer, bufLen: int): int =
+ var s = ReadableStream(s)
+ if s.atEnd:
+ return 0
+ while s.buf.len < bufLen:
+ var len: int
+ s.isource.read(len)
+ if len == 0:
+ result = s.buf.len
+ copyMem(buffer, addr(s.buf[0]), result)
+ s.buf = s.buf.substr(result)
+ s.isend = true
+ return
+ var nbuf: string
+ s.isource.readStr(len, nbuf)
+ s.buf &= nbuf
+ assert s.buf.len >= bufLen
+ result = bufLen
+ copyMem(buffer, addr(s.buf[0]), result)
+ s.buf = s.buf.substr(result)
+ if s.buf.len == 0:
+ var len: int
+ s.isource.read(len)
+ if len == 0:
+ s.isend = true
+ else:
+ s.isource.readStr(len, s.buf)
+
+proc rsAtEnd(s: Stream): bool =
+ ReadableStream(s).isend
+
+proc rsClose(s: Stream) = {.cast(tags: [WriteIOEffect]).}: #TODO TODO TODO ew.
+ var s = ReadableStream(s)
+ if s.isend: return
+ s.buf = ""
+ while true:
+ var len: int
+ s.isource.read(len)
+ if len == 0:
+ s.isend = true
+ break
+ s.isource.setPosition(s.isource.getPosition() + len)
+
proc newReadableStream*(isource: Stream): ReadableStream =
new(result)
result.isource = isource
- result.readDataImpl = (proc(s: Stream, buffer: pointer, bufLen: int): int =
- var s = ReadableStream(s)
- if s.atEnd:
- return 0
- while s.buf.len < bufLen:
- var len: int
- s.isource.read(len)
- if len == 0:
- result = s.buf.len
- copyMem(buffer, addr(s.buf[0]), result)
- s.buf = s.buf.substr(result)
- s.isend = true
- return
- var nbuf: string
- s.isource.readStr(len, nbuf)
- s.buf &= nbuf
- assert s.buf.len >= bufLen
- result = bufLen
- copyMem(buffer, addr(s.buf[0]), result)
- s.buf = s.buf.substr(result)
- if s.buf.len == 0:
- var len: int
- s.isource.read(len)
- if len == 0:
- s.isend = true
- else:
- s.isource.readStr(len, s.buf)
- )
- result.atEndImpl = (proc(s: Stream): bool =
- return ReadableStream(s).isend
- )
- result.closeImpl = (proc(s: Stream) = {.cast(tags: [WriteIOEffect]).}: #TODO TODO TODO ew.
- var s = ReadableStream(s)
- if s.isend: return
- s.buf = ""
- while true:
- var len: int
- s.isource.read(len)
- if len == 0:
- s.isend = true
- break
- s.isource.setPosition(s.isource.getPosition() + len)
- )
+ result.readDataImpl = rsReadData
+ result.atEndImpl = rsAtEnd
+ result.closeImpl = rsClose
var len: int
result.isource.read(len)
if len == 0:
@@ -106,9 +109,10 @@ proc newReadableStream*(isource: Stream): ReadableStream =
result.isource.readStr(len, result.buf)
func newHeaderList*(): HeaderList =
- discard
+ new(result)
func newHeaderList*(table: Table[string, string]): HeaderList =
+ new(result)
for k, v in table:
let k = k.toHeaderCase()
if k in result.table:
@@ -124,6 +128,7 @@ func newRequest*(url: Url,
new(result)
result.httpmethod = httpmethod
result.url = url
+ result.headers = newHeaderList()
for it in headers:
if it[1] != "": #TODO not sure if this is a good idea, options would probably work better
result.headers.table[it[0]] = @[it[1]]
diff --git a/src/io/serialize.nim b/src/io/serialize.nim
index 505eb8c9..932b82df 100644
--- a/src/io/serialize.nim
+++ b/src/io/serialize.nim
@@ -83,6 +83,7 @@ proc sread*(stream: Stream, url: var Url) =
url = parseUrl(s).get
proc sread*(stream: Stream, headers: var HeaderList) =
+ new(headers)
var len: int
stream.sread(len)
for i in 0..<len:
diff --git a/src/io/socketstream.nim b/src/io/socketstream.nim
new file mode 100644
index 00000000..73a00aa2
--- /dev/null
+++ b/src/io/socketstream.nim
@@ -0,0 +1,37 @@
+import net
+import streams
+
+type SocketStream* = ref object of Stream
+ isource: Socket
+ osource: Socket
+ isend: bool
+
+proc sockReadData(s: Stream, buffer: pointer, len: int): int =
+ let s = SocketStream(s)
+ result = s.isource.recv(buffer, len)
+ if result < 0:
+ raise newException(Defect, "Failed to read data")
+ elif result < len:
+ s.isend = true
+
+proc sockWriteData(s: Stream, buffer: pointer, len: int) =
+ discard SocketStream(s).osource.send(buffer, len)
+
+proc sockAtEnd(s: Stream): bool =
+ SocketStream(s).isend
+
+proc sockClose(s: Stream) = {.cast(tags: []).}: #...sigh
+ let s = SocketStream(s)
+ if s.isource != nil:
+ s.isource.close()
+ if s.osource != nil and s.isource != s.osource:
+ s.osource.close()
+
+func newSocketStream*(isource, osource: Socket): SocketStream =
+ new(result)
+ result.isource = isource
+ result.osource = osource
+ result.readDataImpl = sockReadData
+ result.writeDataImpl = sockWriteData
+ result.atEndImpl = sockAtEnd
+ result.closeImpl = sockClose