Web-server refactor (#14)

* rename field

* Parse body support

* Changelog

* Parse query params

* Error handling for larger than content-length body
This commit is contained in:
Brahim Hadriche authored and GitHub committed 2022-11-26 17:25:40 -05:00
1 parent 3f5cb84696
commit 85209cb22e
9 files changed
+187 -75

No files matched your search

+4 -4
View File
@@ -79,9 +79,9 @@ namespace Http
' append to connection request
m.request.Add(rcvStr)
if m.request.IsComplete()
server.num_requests = validint(server.num_requests) + 1
if m.request.Process(m)
if m.request.ProcessNext(m)
if m.request.state = Http.HttpRequestState.DONE
server.num_requests = validint(server.num_requests) + 1
m.response = new HttpResponse(m.request, m.server, m.settings)
m.response.Process()
m.SetState(Http.HttpConnectionState.SEND_HEADER)
@@ -90,7 +90,7 @@ namespace Http
m.close = true
m.log.error("couldn't process request or response, closing @" + m.client)
end if
else if m.request.buf.len() > m.settings.MaxRequestLength ' die if it's too long
else if m.request.buffer.len() > m.settings.MaxRequestLength ' die if it's too long
m.response = new HttpResponse(m.request, m.server, m.settings)
m.response.Default(413, "Your request was dropped because it was too long.")
m.SetState(Http.HttpConnectionState.SEND_HEADER)
+158 -48
View File
@@ -1,3 +1,5 @@
import "pkg:/components/WebServer/HttpRequestState.bs"
namespace Http
function GetHttpRequestId() as integer
@@ -8,82 +10,172 @@ namespace Http
class HttpRequest
private log as log.Logger
Unix2NewLine = UnixNL() + UnixNL()
Windows2NewLine = WinNL() + WinNL()
' members
private method = invalid
private uri = invalid
private query = invalid
private protocol = invalid
private buf = invalid
private fields = invalid
private buffer = invalid
private buffer_index = 0
private headers = invalid
private body = invalid
private state = Http.HttpRequestState.INIT
private id = 0
' copied members
private range_begin = 0
private range_end = 0
private range_begin_given = false
private range_end_given = false
private ok = true
private ready_for_response = false
function new()
m.log = new log.Logger("HttpRequest")
m.id = Http.GetHttpRequestId()
m.fields = CreateObject("roAssociativeArray")
m.headers = CreateObject("roAssociativeArray")
end function
function Add(incoming as string)
if isstr(m.buf)
m.buf = m.buf + incoming
if isstr(m.buffer)
m.buffer = m.buffer + incoming
else
m.buf = incoming
m.buffer = incoming
end if
end function
function IsComplete() as boolean
' TODO: this function is correct only if request does not have a body
' Need read and process line by line
' Once there's an empty line, we've read all headers
' Check for Content-Length header, and read that amount of data
' If header is missing, error out
buf = m.buf
complete = isstr(buf) and (right(buf, 2) = m.Unix2NewLine) or (right(buf, 4) = m.Windows2NewLine)
'if complete then info(m,"header:"+UnixNL()+buf)
return complete
function ProcessNext(connection as HttpConnection) as boolean
if m.state = Http.HttpRequestState.DONE
return m.ready_for_response
end if
if m.state = Http.HttpRequestState.INIT
m.state = Http.HttpRequestState.READING_OPERATION
end if
if m.state = Http.HttpRequestState.READING_OPERATION
if m.ParseOperation()
m.ProcessOperation()
m.state = Http.HttpRequestState.READING_HEADERS
end if
end if
if m.state = Http.HttpRequestState.READING_HEADERS
if m.ParseHeaders()
m.ProcessHeaders(connection)
m.state = Http.HttpRequestState.READING_BODY
end if
end if
if m.state = Http.HttpRequestState.READING_BODY
if m.ParseBody()
m.state = Http.HttpRequestState.DONE
end if
end if
return m.ready_for_response
end function
function Parse(connection as HttpConnection) as boolean
lines = m.buf.tokenize(WinNL())
operation = lines.RemoveHead()
if operation <> invalid
parts = operation.tokenize(" ")
if parts.count() = 3
m.method = Ucase(parts.RemoveHead())
m.uri = parts.RemoveHead()
m.protocol = Ucase(parts.RemoveHead())
m.log.info(m.method + " '" + m.uri + "'")
for each line in lines
av = line.tokenize(": ")
if av.count() = 2
m.fields[av.GetHead()] = av.GetTail()
end if
end for
' interpret some fields if present
m.ParseRange()
m.ParseConnection(connection)
function ParseOperation() as boolean
if m.buffer_index <> 0
m.log.error(`invalid state: reading operation, but request is at index ${m.buffer_index}`)
m.ready_for_response = true
return false
end if
if m.buffer.len() = 0
return false
end if
operation = m.ReadHeaderLine()
if operation = invalid or operation = ""
m.log.error("empty request")
m.ready_for_response = true
return false
end if
parts = operation.tokenize(" ")
if parts.count() = 3
m.method = Ucase(parts[0])
m.uri = parts[1]
m.protocol = Ucase(parts[2])
m.log.info(m.method + " '" + m.uri + "'")
else
m.log.error("invalid request: " + operation)
m.ready_for_response = true
end if
return not m.ready_for_response
end function
function ParseHeaders() as boolean
line = m.ReadHeaderLine()
while line <> invalid and line <> ""
splitIndex = line.InStr(": ")
if splitIndex > 0
key = line.Left(splitIndex)
value = line.Mid(splitIndex + 2)
m.headers[key] = value
end if
line = m.ReadHeaderLine()
end while
' Unfinished line, we wait for the rest
if line = invalid
return false
end if
' Empty line, we're done with headers
if line = ""
return true
end if
return not m.ready_for_response
end function
function ParseBody() as boolean
data = m.ReadBufferToEnd()
if isstr(m.body)
m.body = m.body + data
else
m.body = data
end if
if m.headers["Content-Length"] = invalid
m.ready_for_response = true
if m.body.len() > 0
m.log.error("invalid request: request body found, but no Content-Length header")
return false
else
m.log.error("invalid request: " + operation)
m.ok = false
return true
end if
else
m.log.error("empty request")
m.ok = false
contentLength = m.headers["Content-Length"].toInt()
if not isstr(m.body)
return false
end if
if m.body.len() > contentLength
m.log.error("invalid request: request body is larger than Content-Length")
m.ready_for_response = true
return false
end if
m.ready_for_response = m.body.len() = contentLength
return m.ready_for_response
end if
return m.ok
end function
function ProcessHeaders(connection as HttpConnection)
m.ParseRange()
m.ParseConnection(connection)
end function
function ProcessOperation()
m.query = WebUtils.UrlQueryComponents(m.uri)
end function
function ParseRange()
range = m.fields.range
range = m.headers.range
if range <> invalid
endpoints = lcase(range).tokenize("=")
if endpoints.count() = 2 and endpoints.GetHead() = "bytes"
@@ -104,14 +196,32 @@ namespace Http
end function
function ParseConnection(connection as HttpConnection)
connectionStr = m.fields.connection
connectionStr = m.headers.connection
if connectionStr <> invalid
connection.close = (lcase(connectionStr.trim()) = "close")
end if
end function
function Process(connection as HttpConnection) as boolean
return m.Parse(connection)
function ReadHeaderLine() as dynamic
index = m.buffer.Instr(m.buffer_index, WinNL())
if index = -1
return invalid
end if
length = index - m.buffer_index
line = m.buffer.Mid(m.buffer_index, length)
m.buffer_index += length + 2 'WinNL().len() = 2
return line
end function
function ReadBufferToEnd() as dynamic
if m.buffer_index = m.buffer.len()
return ""
end if
data = m.buffer.Mid(m.buffer_index)
m.buffer_index += data.len()
return data
end function
end class
@@ -0,0 +1,11 @@
namespace Http
enum HttpRequestState
INIT = 0
READING_OPERATION = 1
READING_HEADERS = 2
READING_BODY = 3
DONE = 4
end enum
end namespace
+1 -6
View File
@@ -173,12 +173,7 @@ namespace Http
end function
function KeepAlive(close as boolean) as string
if close
base = "Connection: close"
else
base = "Keep-Alive: timeout=" + Stri(m.settings.Idletime).trim()
end if
return base
return close ? "Connection: close" : "Keep-Alive: timeout=" + Stri(m.settings.Idletime).trim()
end function
function Now() as string
+1 -1
View File
@@ -7,7 +7,7 @@ namespace Http
MessagePort = invalid
MaxConnections = 10
Timeout = 60 * 1000
MaxRequestLength = 4000
MaxRequestLength = 2097152
Idletime = 60
WwwRoot = "pkg:/"
IndexName = "index.html"
@@ -25,16 +25,15 @@ namespace Http
route = request.uri
if route.StartsWith("/api/command/play")
components = WebUtils.UrlQueryComponents(route)
if components["v"] = invalid
if request.query["v"] = invalid
response.Default(400, "Missing arg 'v'")
return true
end if
server.task.top.command = `play:${components["v"]}`
if components["redirect"] = "true"
server.task.top.command = `play:${request.query["v"]}`
if request.query["redirect"] = "true"
' 302 to prevent redirection to current host permanently
response.Redirect(`${InvidiousSettings.GetSelectedInstance()}/watch?v=${components["v"]}`, 302)
response.Redirect(`${InvidiousSettings.GetSelectedInstance()}/watch?v=${request.query["v"]}`, 302)
else
response.Default(204, "OK")
end if
@@ -15,11 +15,9 @@ namespace Http
return false
end if
components = WebUtils.UrlQueryComponents(route)
instances = []
if components.DoesExist("instances")
instances = components["instances"]
if request.query.DoesExist("instances")
instances = request.query["instances"]
if GetInterface(instances, "ifArray") = invalid
instances = [instances]
end if
@@ -46,11 +44,10 @@ namespace Http
return false
end if
components = WebUtils.UrlQueryComponents(route)
if components["token"] <> invalid and components["referer"] <> invalid
if request.query["token"] <> invalid and request.query["referer"] <> invalid
' Token is encoded twice for some reason
token = WebUtils.UrlUnescape(components["token"]).DecodeUriComponent()
referer = WebUtils.UrlUnescape(components["referer"])
token = WebUtils.UrlUnescape(request.query["token"]).DecodeUriComponent()
referer = WebUtils.UrlUnescape(request.query["referer"])
InvidiousSettings.SetAuthToken(token, referer)
server.task.top.login = true
end if
@@ -20,9 +20,8 @@ namespace Http
keys = ["app", "device", "invidious"]
components = WebUtils.UrlQueryComponents(route)
if components.DoesExist("key")
keys = components["key"]
if request.query.DoesExist("key")
keys = request.query["key"]
if GetInterface(keys, "ifArray") = invalid
keys = [keys]
end if