aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2024-03-02 02:10:22 +0100
committerbptato <nincsnevem662@gmail.com>2024-03-02 02:10:22 +0100
commitaafa670da29631be9d84c6090cf716291fd1bcbf (patch)
tree100cf718654e715df837fc21312a3ab6f1b33ccc
parent6e420cc768e86ae15215e3600a7c66b54f4b42ff (diff)
downloadchawan-aafa670da29631be9d84c6090cf716291fd1bcbf.tar.gz
posixstream: add readLine implementation
slightly more efficient, but more importantly does not choke on NUL and weird \r\n
-rw-r--r--src/io/posixstream.nim19
-rw-r--r--src/loader/cgi.nim10
2 files changed, 22 insertions, 7 deletions
diff --git a/src/io/posixstream.nim b/src/io/posixstream.nim
index 80407b27..6d2f145d 100644
--- a/src/io/posixstream.nim
+++ b/src/io/posixstream.nim
@@ -86,9 +86,25 @@ proc psReadData(s: Stream, buffer: pointer, len: int): int =
proc psWriteData(s: Stream, buffer: pointer, len: int) =
let s = PosixStream(s)
- #TODO assert len != 0 and s.blocking
+ assert len != 0 and s.blocking
discard s.sendData(buffer, len)
+proc psReadLine(s: Stream, line: var string): bool =
+ let s = PosixStream(s)
+ assert s.blocking
+ line = ""
+ var c: char
+ while true:
+ if s.recvData(addr c, 1) == 0:
+ return false
+ if c == '\r':
+ if s.recvData(addr c, 1) == 0:
+ return false
+ if c == '\n':
+ break
+ line &= c
+ true
+
proc psAtEnd(s: Stream): bool =
return PosixStream(s).isend
@@ -96,6 +112,7 @@ proc addStreamIface*(ps: PosixStream) =
ps.closeImpl = cast[typeof(ps.closeImpl)](psClose)
ps.readDataImpl = cast[typeof(ps.readDataImpl)](psReadData)
ps.writeDataImpl = cast[typeof(ps.writeDataImpl)](psWriteData)
+ ps.readLineImpl = cast[typeof(ps.readLineImpl)](psReadLine)
ps.atEndImpl = psAtEnd
proc newPosixStream*(fd: FileHandle): PosixStream =
diff --git a/src/loader/cgi.nim b/src/loader/cgi.nim
index c266c0f6..d30f8fd1 100644
--- a/src/loader/cgi.nim
+++ b/src/loader/cgi.nim
@@ -232,8 +232,8 @@ proc loadCGI*(handle: LoaderHandle, request: Request, cgiDir: seq[string],
# no data?
handle.sendResult(ERROR_CGI_NO_DATA)
return
- let line = ps.readLine()
- if line == "": #\r\n
+ var line: string
+ if not ps.readLine(line) or line == "": #\r\n
# no headers, body comes immediately
handle.sendResult(0) # success
else:
@@ -242,8 +242,7 @@ proc loadCGI*(handle: LoaderHandle, request: Request, cgiDir: seq[string],
return
var crlfFound = false
while not ps.atEnd and res == RESULT_CONTROL_CONTINUE:
- let line = ps.readLine()
- if line == "":
+ if not ps.readLine(line) or line == "": # \r\n
crlfFound = true
break
res = handle.handleControlLine(line, headers, status)
@@ -251,8 +250,7 @@ proc loadCGI*(handle: LoaderHandle, request: Request, cgiDir: seq[string],
return
if not crlfFound:
while not ps.atEnd:
- let line = ps.readLine()
- if line == "": #\r\n
+ if not ps.readLine(line) or line == "": # \r\n
break
handle.handleLine(line, headers)
handle.sendStatus(status)