From 05d82b0006c132409259f02cf0b8925ebad067e6 Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Fri, 4 Nov 2022 10:45:10 -0400 Subject: [PATCH] add demo server --- src/config.xml | 8 + src/source/webserver/common/General.brs | 39 +++ src/source/webserver/common/StringUtils.brs | 117 +++++++ src/source/webserver/common/Types.brs | 139 ++++++++ src/source/webserver/connection.brs | 207 ++++++++++++ src/source/webserver/main.brs | 108 +++++++ src/source/webserver/reply.brs | 337 ++++++++++++++++++++ src/source/webserver/request.brs | 114 +++++++ src/source/webserver/server.brs | 140 ++++++++ src/source/webserver/utils.brs | 279 ++++++++++++++++ 10 files changed, 1488 insertions(+) create mode 100644 src/config.xml create mode 100644 src/source/webserver/common/General.brs create mode 100644 src/source/webserver/common/StringUtils.brs create mode 100644 src/source/webserver/common/Types.brs create mode 100644 src/source/webserver/connection.brs create mode 100644 src/source/webserver/main.brs create mode 100644 src/source/webserver/reply.brs create mode 100644 src/source/webserver/request.brs create mode 100644 src/source/webserver/server.brs create mode 100644 src/source/webserver/utils.brs diff --git a/src/config.xml b/src/config.xml new file mode 100644 index 00000000..a6fe0096 --- /dev/null +++ b/src/config.xml @@ -0,0 +1,8 @@ + + + text/plain + + + pkg:/ + + diff --git a/src/source/webserver/common/General.brs b/src/source/webserver/common/General.brs new file mode 100644 index 00000000..41cc4ed8 --- /dev/null +++ b/src/source/webserver/common/General.brs @@ -0,0 +1,39 @@ +REM This file has no dependencies on other common files. +REM +REM Functions in this file: +REM GetDeviceVersion +REM GetDeviceESN +REM IsHD +REM + +'****************************************************** +'Get our device version +'****************************************************** +Function GetDeviceVersion() + if m.softwareVersion = invalid OR m.softwareVersion = "" then + m.softwareVersion = CreateObject("roDeviceInfo").GetVersion() + end if + return m.softwareVersion +End Function + + +'****************************************************** +'Get our serial number +'****************************************************** +Function GetDeviceESN() + if m.serialNumber = invalid OR m.serialNumber = "" then + m.serialNumber = CreateObject("roDeviceInfo").GetDeviceUniqueId() + end if + return m.serialNumber +End Function + + +'****************************************************** +'Determine if the UI is displayed in SD or HD mode +'****************************************************** +Function IsHD() + di = CreateObject("roDeviceInfo") + if di.GetDisplayMode() = "720p" then return true + return false +End Function + diff --git a/src/source/webserver/common/StringUtils.brs b/src/source/webserver/common/StringUtils.brs new file mode 100644 index 00000000..08cb8493 --- /dev/null +++ b/src/source/webserver/common/StringUtils.brs @@ -0,0 +1,117 @@ +REM Functions in this file: +REM isnonemptystr +REM isnullorempty +REM strtobool +REM itostr +REM strTrim +REM strTokenize +REM strReplace +REM + +'****************************************************** +'isnonemptystr +' +'Determine if the given object supports the ifString interface +'and returns a string of non zero length +'****************************************************** +Function isnonemptystr(obj) + return ((obj <> invalid) AND (GetInterface(obj, "ifString") <> invalid) AND (Len(obj) > 0)) +End Function + + +'****************************************************** +'isnullorempty +' +'Determine if the given object is invalid or supports +'the ifString interface and returns a string of zero length +'****************************************************** +Function isnullorempty(obj) + return ((obj = invalid) OR (GetInterface(obj, "ifString") = invalid) OR (Len(obj) = 0)) +End Function + + +'****************************************************** +'strtobool +' +'Convert string to boolean safely. Don't crash +'Looks for certain string values +'****************************************************** +Function strtobool(obj As dynamic) As Boolean + if obj = invalid return false + if type(obj) <> "roString" and type(obj) <> "String" return false + o = strTrim(obj) + o = Lcase(o) + if o = "true" return true + if o = "t" return true + if o = "y" return true + if o = "1" return true + return false +End Function + +'****************************************************** +'booltostr +' +'Converts a boolean value to a cannonical string value +'****************************************************** +Function booltostr(bool As Boolean) As String + if bool = true then return "true" + return "false" +End Function + +'****************************************************** +'itostr +' +'Convert int to string. This is necessary because +'the builtin Stri(x) prepends whitespace +'****************************************************** +Function itostr(i As Integer) As String + str = Stri(i) + return strTrim(str) +End Function + + +'****************************************************** +'Trim a string +'****************************************************** +Function strTrim(str As String) As String + st=CreateObject("roString") + st.SetString(str) + return st.Trim() +End Function + + +'****************************************************** +'Tokenize a string. Return roList of strings +'****************************************************** +Function strTokenize(str As String, delim As String) As Object + st=CreateObject("roString") + st.SetString(str) + return st.Tokenize(delim) +End Function + + +'****************************************************** +'Replace substrings in a string. Return new string +'****************************************************** +Function strReplace(basestr As String, oldsub As String, newsub As String) As String + newstr = "" + + i = 1 + while i <= Len(basestr) + x = Instr(i, basestr, oldsub) + if x = 0 then + newstr = newstr + Mid(basestr, i) + exit while + endif + + if x > i then + newstr = newstr + Mid(basestr, i, x-i) + i = x + endif + + newstr = newstr + newsub + i = i + Len(oldsub) + end while + + return newstr +End Function diff --git a/src/source/webserver/common/Types.brs b/src/source/webserver/common/Types.brs new file mode 100644 index 00000000..ef534315 --- /dev/null +++ b/src/source/webserver/common/Types.brs @@ -0,0 +1,139 @@ +REM Functions in this file: +REM isxmlelement +REM islist +REM isint +REM isfunc +REM isstr +REM isbool +REM isfloat +REM validstr +REM validateParam +REM + +'****************************************************** +'isxmlelement +' +'Determine if the given object supports the ifXMLElement interface +'****************************************************** +Function isxmlelement(obj as dynamic) As Boolean + return obj <> invalid and GetInterface(obj, "ifXMLElement") <> invalid +End Function + + +'****************************************************** +'islist +' +'Determine if the given object supports the ifList interface +'****************************************************** +Function islist(obj as dynamic) As Boolean + return obj <> invalid and GetInterface(obj, "ifArray") <> invalid +End Function + + +'****************************************************** +'isint +' +'Determine if the given object supports the ifInt interface +'****************************************************** +Function isint(obj as dynamic) As Boolean + return obj <> invalid and GetInterface(obj, "ifInt") <> invalid +End Function + + +'****************************************************** +'isfunc +' +'Determine if the given object supports the function interface +'****************************************************** +Function isfunc(obj as dynamic) As Boolean + tf = type(obj) + return tf="Function" or tf="roFunction" +End Function + + +'****************************************************** +'isstr +' +'Determine if the given object supports the ifString interface +'****************************************************** +Function isstr(obj as dynamic) As Boolean + return obj <> invalid and GetInterface(obj, "ifString") <>invalid +End Function + + +'****************************************************** +'isbool +' +'Determine if the given object supports the ifBoolean interface +'****************************************************** +Function isbool(obj as dynamic) As Boolean + if obj = invalid return false + if GetInterface(obj, "ifBoolean") = invalid return false + return true +End Function + + +'****************************************************** +'isfloat +' +'Determine if the given object supports the ifFloat interface +'****************************************************** +Function isfloat(obj as dynamic) As Boolean + if obj = invalid return false + if GetInterface(obj, "ifFloat") = invalid return false + return true +End Function + + +'****************************************************** +' validstr +' +' always return a valid string. if the argument is +' invalid or not a string, return an empty string. +'****************************************************** +Function validstr(obj As Object) As String + if obj <> invalid and GetInterface(obj, "ifString") <> invalid + return obj + else + return "" + endif +End Function + + +'****************************************************** +' validint +' +' Always return a valid integer. If the argument is +' invalid or not an integer, return zero. +'****************************************************** +Function validint(obj As Dynamic) As Integer + if obj <> invalid and GetInterface(obj, "ifInt") <> invalid + return obj + else + return 0 + end if +End Function + + +'****************************************************** +'Validate parameter is the correct type +'****************************************************** +Function validateParam(param As Object, paramType As String,functionName As String, allowInvalid = false) As Boolean + if paramType = "roString" or paramType = "String" then + if type(param) = "roString" or type(param) = "String" then + return true + end if + else if type(param) = paramType then + return true + endif + + if allowInvalid = true then + if type(param) = invalid then + return true + endif + endif + + print "invalid parameter of type "; type(param); " for "; paramType; " in function "; functionName + return false +End Function + diff --git a/src/source/webserver/connection.brs b/src/source/webserver/connection.brs new file mode 100644 index 00000000..09580933 --- /dev/null +++ b/src/source/webserver/connection.brs @@ -0,0 +1,207 @@ +function ClassConnection() + ' initializes static members once + this = m.ClassConnection + if this=invalid + this = CreateObject("roAssociativeArray") + ' constants + this.class = "Connection" + this.INIT = 0 ' initial state; shouldn't last long + this.RECV_REQUEST = 1 ' receiving request + this.SEND_HEADER = 2 ' sending generated header + this.SEND_REPLY = 3 ' sending reply + this.DONE = 4 ' reply sent, close or reuse as indicated + this.BUFSIZE = 65536 + this.MAX_REQUEST_LENGTH = 4000 + ' copy-initializable members + this.total_received = 0 + this.total_sent = 0 + this.id = "" + this.close = true + this.state = this.INIT + ' functions + this.reset = connection_reset + this.restart = connection_restart + this.recycle = connection_recycle + this.accepted = connection_accepted + this.pollRequest = connection_poll_receive_request + this.pollHeader = connection_poll_send_header + this.pollReply = connection_poll_send_reply + this.checkTimeout = connection_check_timeout + this.checkResult = connection_check_result + this.setState = connection_set_state + this.log = connection_log + ' constructor + this.reset() + ' singleton + m.ClassConnection = this + end if + return this +end function + + ' --------------------------------------------------------------------------- + ' Allocate and initialize an empty connection. + ' +function InitConnection() + this = CreateObject("roAssociativeArray") + this.append(ClassConnection()) + this.reset() + return this +end function + + ' --------------------------------------------------------------------------- + ' Accept a connection from sockin and add it to the connection queue. + ' +function AcceptConnection(server as Object) + sockin = server.sockin + socket = sockin.accept() + if not sockin.eOK() err(m, "accept()",sockin.status()) + if socket=invalid then return invalid + this = InitConnection() + this.accepted(server,socket) + return this +end function + +function connection_reset() + ' re-initializes all instance members + m.socket = invalid + m.addr = invalid + m.restart() +end function + +function connection_restart() + ' re-initializes members for next request-reply + m.last_active = CreateObject("roTimespan") + m.request = InitRequest() + m.header = invalid + m.reply = invalid + m.header_only = false + m.http_code = 0 + m.close = true + m.setState(m.INIT) +end function + +function connection_recycle() + info(m,"recycle") + m.restart() + m.setState(m.RECV_REQUEST) ' ready for another +end function + +function connection_accepted(server as Object, socket as Object) + m.socket = socket + m.id = Stri(socket.getID()).trim() + m.setState(m.RECV_REQUEST) + m.client = m.socket.getReceivedFromAddress().getAddress() + + info(m,"accepted connection @" + m.client) + + ' try to read right away rather than going through another iteration + ' of the poll loop. + m.pollRequest(server) +end function + +function connection_check_result(byteCount as Integer, op as String) as Boolean + gotSome = false + if byteCount>0 + m.last_active.mark() + gotSome = true + else if m.socket.eOK() and not m.socket.eSuccess() + 'info(m,op + " would have blocked @"+m.client) + else + if m.socket.eSuccess() + info(m,op + " peer closed @"+m.client) + else + err(m,op + " transfer error @"+m.client,m.socket.status()) + end if + m.close = true + m.setState(m.DONE) + end if + return gotSome +end function + +function connection_poll_receive_request(server as Object) + if m.state<>m.RECV_REQUEST then errx(m,"illegal request state @"+m.client) + + rcvStr = m.socket.receiveStr(m.BUFSIZE) + received = rcvStr.len() + + if m.checkResult(received,"receive request") + m.total_received = m.total_received + received + server.total_in = server.total_in + received + end if + + ' 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) + m.reply = InitReply(m.request) + m.reply.process() + m.setState(m.SEND_HEADER) + else + m.setState(m.DONE) + m.close = true + err(m,"couldn't process request or reply, closing @"+m.client) + end if + else if m.request.buf.len() > m.MAX_REQUEST_LENGTH ' die if it's too long + m.default_reply(413, "Request Entity Too Large", "Your request was dropped because it was too long.") + m.setState(m.SEND_HEADER) + end if + + ' if we've moved on to the next state, try to send right away, instead of + ' going through another iteration of the poll loop. + ' + if m.state = m.SEND_HEADER then m.pollHeader(server) +end function + +function connection_poll_send_header(server as Object) as Boolean + if m.state<>m.SEND_HEADER errx(m,"illegal header state @"+m.client) + + sent = m.reply.sendHdr(m.socket,m.BUFSIZE) + + if m.checkResult(sent, "send header") + m.total_sent = m.total_sent + sent + server.total_out = server.total_out + sent + end if + + if m.reply.doneHdr() + if m.reply.header_only + m.setState(m.DONE) + else + m.setState(m.SEND_REPLY) + m.pollReply(server) + end if + end if +end function + +function connection_poll_send_reply(server as Object) + if m.state<>m.SEND_REPLY or m.reply.header_only then errx(m,"illegal reply state @"+m.client) + + sent = m.reply.send(m.socket,m.BUFSIZE) + if m.checkResult(sent,"send reply") + m.total_sent = m.total_sent + sent + server.total_out = server.total_out + sent + end if + if m.reply.done() then m.setState(m.DONE) +end function + +function connection_check_timeout(timeout as Integer) + if m.last_active.totalSeconds() > timeout + m.close = true + m.setState(m.DONE) + end if +end function + +function connection_set_state(newState as Integer) + if m.state<>newState + 'info(m,"state change" + Stri(m.state) + " ->" + Stri(newState)) + m.state = newState + end if +end function + +function connection_log() + if m.http_code <> 0 and isnonemptystr(m.method) + print m.last_active.totalSeconds(); " client:"; m.client; " meth:"; m.method; " uri:"; m.uri; " code:"; m.code; " sent:"; m.total_sent; " referer:"; m.referer; " user agent:"; m.user_agent + end if +end function + diff --git a/src/source/webserver/main.brs b/src/source/webserver/main.brs new file mode 100644 index 00000000..0560dd52 --- /dev/null +++ b/src/source/webserver/main.brs @@ -0,0 +1,108 @@ + ' Roku Streaming Player Web Server + ' This code was heavily influenced by darkhttpd/1.7 + ' The darkhttpd copyright notice is included below. + + ' + ' darkhttpd + ' copyright (c) 2003-2008 Emil Mikulic. + ' + ' Permission to use, copy, modify, and distribute this software for any + ' purpose with or without fee is hereby granted, provided that the + ' above copyright notice and this permission notice appear in all + ' copies. + ' + ' THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL + ' WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED + ' WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE + ' AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + ' DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + ' PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + ' TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + ' PERFORMANCE OF THIS SOFTWARE. + ' + + ' Adapted from C to Brightscript with mods by Roku, Inc. + ' + ' unimplemented options: daemonize, pidfile, logfile + + ' --------------------------------------------------------------------------- + ' example Main to show how the server might be embedded + ' in a more complex script that includes user interaction + ' +function TestServerMain() + + Init() ' set up defaults, read config file + + msgPort = CreateObject("roMessagePort") + SetGlobal("msgPort",msgPort) + + m.currentItem = 0 + + server = InitServer() + + updateStatus(server) + ' trivial main loop + m.running = true + timeout = validint(Global("timeout")) + timer = CreateObject("roTimespan") + update = true + while (m.running) + if update + timer.mark() + updateStatus(server) + update = false + end if + server.prewait() + msg = wait(timeout,msgPort) + tm = type(msg) + if tm="roSocketEvent" or msg=invalid + server.postwait() + end if + if timer.totalSeconds()>=5 then update = true + end while + + server.close() + +end function + +function Init() + ' set some global defaults + globals = CreateObject("roAssociativeArray") + globals.pkgname = "Roku RSP WebServer" + globals.maxRequestLength = 4000 + globals.idletime = 60 + globals.wwwroot = "pkg:/" + globals.index_name = "index.html" + globals.serverName = "Roku Streaming Player" + globals.timeout = 5 * 1000 ' in milliseconds + ' defaults before config file override + AddGlobals(globals) + MimeType() + HttpTitle() + ' might override some of above + GetXMLConfig("config.xml",m) +end function + +function updateStatus(server as Object) + print(server.stats()) + connArray = [] + connections = server.connections + for each connID in connections + conn = connections[connID] + connItem = { + shortDescriptionLine1: conn.client + shortDescriptionLine2: itostr(conn.total_sent) + title : conn.id + HDPosterUrl : "pkg:/images/Connection.png" + SDPosterUrl : "pkg:/images/Connection.png" + contentType: "movie" + } + connArray.push(connItem) + end for + print(connArray) + cae = connArray.count()-1 + if (cae<0) + print("No active connections" + UnixNL() + server.stats()) + end if +end function + diff --git a/src/source/webserver/reply.brs b/src/source/webserver/reply.brs new file mode 100644 index 00000000..167ce946 --- /dev/null +++ b/src/source/webserver/reply.brs @@ -0,0 +1,337 @@ +function ClassReply() + this = m.ClassReply + if this=invalid + this = CreateObject("roAssociativeArray") + ' constants + this.class = "Reply" + this.GENERATED = 1 + this.FROMFILE = 2 + this.source = 0 + ' members + this.buf = invalid + this.header = invalid + this.path = invalid + this.request = invalid + this.id = 0 + ' copy-initializable members + this.start = 0 + this.length = 0 + this.sent = 0 + this.header_sent = 0 + this.header_only = false + this.buf_start = 0 + this.http_code = 0 + this.mimetype = "text/html" ' for errors + ' functions + this.init = reply_init + this.process = reply_process + this.get = reply_process_get + this.default = reply_default + this.redirect = reply_redirect + this.send = reply_send + this.sendHdr = reply_send_header + this.genDir = reply_generate_directory_listing + this.genHdr = reply_generate_header + this.done = reply_done + this.doneHdr = reply_done_header + this.log = reply_log + ' html lines + this.keepAlive = reply_keep_alive + this.genBy = reply_generated_by + ' singleton + m.ClassReply = this + end if + this.id = this.id + 1 + return this +end function + +function InitReply(request as Object) as Object + this = CreateObject("roAssociativeArray") + this.append(ClassReply()) + this.init(request) + return this +end function + +function reply_init(request) + m.buf = CreateObject("roByteArray") + m.request = request +end function + +function reply_send(sock as Object, bufsize as Integer) as Integer + sent = -1 + if m.source=m.FROMFILE + if m.start+m.sent>=m.buf_start+m.buf.count() + m.buf_start = m.start+m.sent + m.buf.ReadFile(m.path,m.buf_start,bufsize) + info(m,"Read" + Stri(m.buf.count()) + " bytes from source file @" + itostr(m.buf_start)) + end if + end if + buf_pos = m.start + m.sent - m.buf_start + buf_remaining = m.buf.count() - buf_pos + if buf_remaining=0 then info(m,"source buf is empty") + req_remaining = m.length - m.sent + if buf_remaining>req_remaining then buf_remaining = req_remaining + sent = sock.send(m.buf, buf_pos, buf_remaining) + m.log(sent, m.buf_start+buf_pos, m.length) + if sent>0 then m.sent = m.sent + sent + return sent +end function + +function reply_send_header(sock as Object, bufsize as Integer) as Integer + if m.header_sent=0 + sent = sock.sendStr(m.header) + else + sent = sock.sendStr(m.header.mid(m.header_sent)) + end if + m.log(sent, m.header_sent, m.header_length) + if sent>0 then m.header_sent = m.header_sent + sent + return sent +end function + + ' --------------------------------------------------------------------------- + ' A default reply for any (erroneous) occasion. + ' +function reply_default(errcode as Integer, reason as String) + errname = HttpTitle(errcode) + + buf = "" + Stri(errcode).trim() + " " + errname + "" + UnixNL() + buf = buf + "

" + errname + "

" + UnixNL() + buf = buf + reason + UnixNL() + buf = buf + "
" + UnixNL() + buf = buf + m.genBy() + UnixNL() + buf = buf + "" + UnixNL() + + m.buf.fromasciistring(buf) + m.length = m.buf.count() + + m.genHdr(true) + m.source = m.GENERATED +end function + +function reply_redirect(where as String) + m.location = where + message = "Moved to: " + where + "" + m.default(301,message) +end function + +function reply_keep_alive(close as Boolean) as String + if close then base = "Connection: close" else base = "Keep-Alive: timeout=" + Stri(Global("idletime")).trim() + return base +end function + +function reply_generate_header(close=false as Boolean) + code = m.http_code + title = HttpTitle(code) + m.header = "HTTP/1.1" + Stri(code) + " " + title + WinNL() + m.header = m.header + "Date: " + m.now + WinNL() + m.header = m.header + "Server: " + Global("pkgname") + WinNL() + if isstr(m.location) then m.header = m.header + "Location: " + m.location + WinNL() + m.header = m.header + m.keepAlive(close) + WinNL() + m.header = m.header + "Content-Length:" + Stri(m.length) + WinNL() + if code=206 then m.header = m.header + "Content-Range: bytes" + makeRange(m.start,m.length,m.filelength) + WinNL() + m.header = m.header + "Content-Type: " + m.mimetype + WinNL() + m.header = m.header + "Accept-Ranges: bytes" + WinNL() + m.header = m.header + WinNL() + m.header_length = m.header.len() +end function + +function reply_generated_by() + return "generated by " + Global("pkgname") + " on " + m.now +end function + +function reply_generate_directory_listing() as Boolean + fs = CreateObject("roFilesystem") + dirList = fs.GetDirectoryListing(m.path) + if dirList=invalid + m.default(500,"Couldn't list directory") + return false + end if + + ' for tabbed alignment of file sizes + maxlen = 0 + for each item in dirList + il = item.len() + if maxlen < il maxlen = il + end for + + listing = "" + UnixNL() + listing = listing + "" + UnixNL() + listing = listing + "" + Global("serverName") + "" + UnixNL() + listing = listing + "" + UnixNL() + listing = listing + "" + UnixNL() + listing = listing + "

" + URLUnescape(m.request.uri) + "

" + UnixNL() + listing = listing + "
" + UnixNL()
+
+    dir = m.path.getString()
+    if dir.len()>0 and dir.right(1)<>"/" then dir = dir + "/"
+    uriDir = m.request.uri
+    if  uriDir.len()>0 and uriDir.right(1)<>"/" then uriDir = uriDir + "/"
+
+    for each item in dirList
+        if item.left(1)<>"."
+            indicator = invalid
+            stat = fs.stat(dir + item)
+            if stat<> invalid
+                if stat.doesexist("type") and stat.type="directory"
+                    indicator = "/"
+                else if stat.doesexist("size")
+                    indicator = string(maxlen-item.len()," ") + Stri(stat.size)
+                end if
+            end if
+            if indicator<>invalid
+                uri = uriDir + item
+                safe_url = uri ' UrlEncode(uri) ' too much encoding
+                listing = listing + "" + item
+                listing = listing + indicator
+                listing = listing + "" + UnixNL()
+            else
+                warn(m,"insufficient stat info to include '" + dir + item + "'")
+            end if
+        end if
+    end for
+
+    listing = listing + "
" + UnixNL() + listing = listing + "
" + UnixNL() + + listing = listing + m.genBy() + UnixNL() + listing = listing + "" + UnixNL() + listing = listing + "" + UnixNL() + + m.buf.FromAsciiString(listing) + m.length = m.buf.count() + + m.http_code = 200 + m.genHdr() + m.source = m.GENERATED + return true +end function + + ' --------------------------------------------------------------------------- + ' Process a GET/HEAD reply + ' +function reply_process_get() as Boolean + ' work out path of file being requested + req = m.request + uri = req.uri + decoded_uri = UrlUnescape(uri) + path = CreateObject("roPath","pkg:/"+decoded_uri) + print(Global("wwwroot")+decoded_uri) + print(path) + fs = CreateObject("roFilesystem") + + ' make sure it's safe + if not path.isValid() + m.default(400, "You requested an invalid URI: " + uri) + return false + else if not fs.exists(path) + m.default(404, "The URI you requested (" + uri + ") was not found.") + return false + end if + + stat = fs.stat(path) + if stat=invalid + m.default(500, "fstat() failed.") + return false + end if + m.path = path + + if stat.type="directory" + m.mimetype = MimeType(Global("index_name")) + m.genDir() + return true + else if stat.type="file" + m.mimetype = MimeType(decoded_uri) + m.fileLength = stat.size + info(m,"uri="+uri+", target="+path+", content-type="+m.mimetype+", content-length="+Stri(m.fileLength).trim()) + else + m.default(403, "Not a regular file.") + return false + end if + + m.source = m.FROMFILE + m.lastmod = Now() ' stat.mtime (mod date not yet available) + fileFinish = m.fileLength - 1 + + ' check for If-Modified-Since, may not have to send */ + if_mod_since = req.fields["If-Modified-Since"] + if if_mod_since<>invalid + reqDate = date_rfc1123(if_mod_since) + if reqDate<>invalid and reqDate.toSeconds() >= m.lastMod.toSeconds() + m.header_only = true + lastMod = rfc1123_date(m.lastMod) + info(m,"not modified since " + lastMod) + m.default(304, "not modified since " + lastMod) + return true + end if + end if + + if req.range_begin_given or req.range_end_given + if req.range_begin_given and req.range_end_given + ' 100-200 + start = req.range_begin + finish = req.range_end + ' clamp finish to fileFinish + if finish>fileFinish then finish = fileFinish + else if req.range_begin_given and not req.range_end_given + ' 100- :: yields 100 to end + start = req.range_begin + finish = fileFinish + else if not req.range_begin_given and req.range_end_given + ' -200 :: yields last 200 + finish = fileFinish + start = finish - req.range_end + 1 + ' check for wrapping + if start>finish start = 0 + else + errx(1, "internal error - range start/finish logic inconsistency") + end if + + m.start = start + m.length = finish - start + 1 + m.http_code = 206 + + info(m,"sending range " + makeRange(start,m.length,m.fileLength)) + else ' no range stuff + m.length = m.fileLength + m.http_code = 200 + end if + + m.genHdr() + return true +end function + + ' --------------------------------------------------------------------------- + ' Process a reply: build the header and the reply + ' +function reply_process() + m.now = rfc1123_date(Now()) + method = m.request.method + if method="" + m.default(400, "You sent a request that the server couldn't understand.") + else if method="GET" + m.get() + else if method="HEAD" + m.get() + m.header_only = true + else if method="OPTIONS" or method="POST" or method="PUT" or method="DELETE" or method="TRACE" or method="CONNECT" + m.default(501, "The method you specified ("+method+") is not implemented.") + else + m.default(400, method+" is not a valid HTTP/1.1 method.") + end if +end function + +function reply_done() as Boolean + return m.sent=m.length +end function + +function reply_done_header() as Boolean + return m.header_sent=m.header_length +end function + +function makeRange(start as Integer, length as Integer, total as Integer) + return itostr(start) + "-" + itostr(start+length-1) + "/" + itostr(total) +end function + +function reply_log(recent as Integer,from as Integer, total as Integer) + info( m, "Sent" + Stri(recent) + " [" + makeRange(from,recent,total) +"]" ) +end function diff --git a/src/source/webserver/request.brs b/src/source/webserver/request.brs new file mode 100644 index 00000000..a28ab5b6 --- /dev/null +++ b/src/source/webserver/request.brs @@ -0,0 +1,114 @@ +function ClassRequest() + this = m.ClassRequest + if this=invalid + this = CreateObject("roAssociativeArray") + ' constants + this.class = "Request" + this.unix2NL = UnixNL() + UnixNL() + this.win2NL = WinNL() + WinNL() + ' members + this.method = invalid + this.uri = invalid + this.protocol = invalid + this.buf = invalid + this.fields = invalid + this.id = 0 + ' copied members + this.range_begin = 0 + this.range_end = 0 + this.range_begin_given = false + this.range_end_given = false + this.ok = true + ' functions + this.add = request_add + this.isComplete = request_is_complete + this.parse = request_parse + this.parseRange = request_parse_range + this.parseConn = request_parse_connection + this.process = request_process + ' singleton + m.ClassRequest = this + end if + this.id = this.id + 1 + return this +end function + +function InitRequest() as Dynamic + this = CreateObject("roAssociativeArray") + this.append(ClassRequest()) + this.fields = CreateObject("roAssociativeArray") + return this +end function + +function request_add(incoming as String) + if isstr(m.buf) then m.buf = m.buf + incoming else m.buf = incoming +end function + +function request_is_complete() as Boolean + buf = m.buf + complete = isstr(buf) and (right(buf,2)=m.unix2NL) or (right(buf,4)=m.win2NL) + 'if complete then info(m,"header:"+UnixNL()+buf) + return complete +end function + +function request_parse(conn as Object) 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()) + info(m,m.method + " '" + m.uri + "'") + for each line in lines + av = line.tokenize(": ") + if av.count()=2 then m.fields[av.GetHead()] = av.GetTail() + end for + ' interpret some fields if present + m.parseRange() + m.parseConn(conn) + else + err(m,"invalid request: "+operation) + m.ok = false + end if + else + err(m,"empty request") + m.ok = false + end if + return m.ok +end function + +function request_parse_range() + range = m.fields.range + if range<>invalid + endpoints = lcase(range).tokenize("=") + if endpoints.count()=2 and endpoints.GetHead()="bytes" + range = endpoints.GetTail().Trim() + hyphen = range.instr("-") + if hyphen>0 + m.range_begin = strtoi(range.left(hyphen)) + m.range_begin_given = true + end if + last = range.len()-1 + if hypheninvalid then conn.close = (lcase(connection.trim())= "close") +end function + + ' --------------------------------------------------------------------------- + ' Process a request + ' +function request_process(conn as Object) as Boolean + return m.parse(conn) +end function + diff --git a/src/source/webserver/server.brs b/src/source/webserver/server.brs new file mode 100644 index 00000000..11bd65cb --- /dev/null +++ b/src/source/webserver/server.brs @@ -0,0 +1,140 @@ +function ClassServer() as Object + this = m.ClassServer + if this=invalid + this = CreateObject("roAssociativeArray") + ' constants + this.class = "Server" + ' members + this.connections = invalid + this.sockin = invalid + 'this.wwwroot = invalid ' global for now + this.uptime = invalid + ' initializable (copied) members + this.port = 8888 + this.max_connections = 3 + this.num_requests = 0 + this.timeout = 60 + this.total_in = 0 + this.total_out = 0 + ' functions + this.init = server_init + this.preWait = server_prewait + this.postWait = server_postwait + this.close = server_close + this.stats = server_stats + ' singleton + m.ClassServer = this + end if + return this +end function + +function InitServer(params=invalid as Dynamic) as Object + this = CreateObject("roAssociativeArray") + this.append(ClassServer()) + this.init(params) + return this +end function + +function server_init(params as Dynamic) + if params<>invalid then m.append(params) + + m.uptime = CreateObject("roTimespan") + m.connections = CreateObject("roAssociativeArray") + + ' create incoming socket + sockin = CreateObject("roStreamSocket") + if sockin=invalid then errx(m, "socket()") + + ' reuse address + if not sockin.setReuseAddr(true) then errx(m, "setsockopt(SO_REUSEADDR)",sockin.status()) + + ' bind socket + addrin = CreateObject("roSocketAddress") + addrin.setPort(m.port) + if not sockin.setAddress(addrin) then errx(m, "bind(port"+ Stri(m.port) +")",sockin.status()) + + ' listen on socket + if not sockin.listen(m.max_connections) then errx(m, "listen()",sockin.status()) + + ' monitor socket + sockin.setMessagePort(Global("msgPort")) + sockin.notifyReadable(true) + + m.sockin = sockin + + info(m,"listening on "+addrin.getAddress()) +end function + +function server_prewait() + connections = m.connections + for each id in connections + conn = connections[id] + conn.checkTimeout(m.timeout) + cs = conn.state + if cs=conn.DONE + conn.socket.notifyReadable(false) + conn.socket.notifyWritable(false) + else if cs=conn.RECV_REQUEST + conn.socket.notifyReadable(true) + conn.socket.notifyWritable(false) + else if cs=conn.SEND_HEADER or cs=conn.SEND_REPLY + conn.socket.notifyWritable(true) + conn.socket.notifyReadable(false) + else + errx(m, "invalid state") + end if + end for +end function + +function server_postwait() + connections = m.connections + if m.sockin.isReadable() + conn = AcceptConnection(m) + if conn<>invalid then connections[conn.id] = conn + end if + for each id in connections + conn = connections[id] + cs = conn.state + if cs=conn.RECV_REQUEST + if conn.socket.isReadable() then conn.pollRequest(m) + else if cs=conn.SEND_HEADER + if conn.socket.isWritable() then conn.pollHeader(m) + else if cs=conn.SEND_REPLY + if conn.socket.isWritable() then conn.pollReply(m) + else if cs=conn.DONE + ' handle with other connections that might transition to done + else + errx(m, "invalid state") + end if + cs = conn.state + if cs=conn.DONE + if conn.close + conn.socket.close() + connections.delete(id) + else + conn.recycle() + conn.pollRequest(m) + end if + end if + end for +end function + +function server_close() + ' close all the sockets + m.sockin.close() + connections = m.connections + for each id in connections + conn = connections[id] + conn.socket.close() + end for + ' final stats + info(m,UnixNL()+m.stats()) +end function + +function server_stats() as String + stats = " Uptime" + Stri(m.uptime.totalSeconds()) + " secs" + UnixNL() + stats = stats + " Requests" + Stri(m.num_requests) + UnixNL() + stats = stats + " Bytes" + Stri(m.total_in) + " in," + Stri(m.total_out) + " out" + return stats +end function + diff --git a/src/source/webserver/utils.brs b/src/source/webserver/utils.brs new file mode 100644 index 00000000..3e8f1708 --- /dev/null +++ b/src/source/webserver/utils.brs @@ -0,0 +1,279 @@ +function Global(name="" as String) as Dynamic + this = m.globals + if this=invalid + this = CreateObject("roAssociativeArray") + m.globals = this + end if + return this[name] +end function + +function SetGlobal(name as String, value as Dynamic) + Global() + m.globals[name] = value +end function + +function IncrGlobal(name as String, amount as Integer) + old = validint(Global(name)) + SetGlobal(name,old+amount) +end function + +function AddGlobals(aa as Object) + Global() + m.globals.append(aa) +end function + +function min(a as Integer, b as Integer) as Integer + if ainvalid then tag = tag + class + if isint(id) + tag = tag +"[" + itostr(id) + "]" + else if isstr(id) + tag = tag +"[" + id + "]" + end if + end if + print tag; "."; level; ": "; + if code<>0 then print "*"; Stri(code).trim(); "* "; + print message +end function + +function info(obj as Object, message as String, code=0 as Integer) + dbg(obj, "info", message, code) +end function + +function warn(obj as Object, message as String, code=0 as Integer) + dbg(obj, "warning", message, code) +end function + +function err(obj as Object, message as String, code=0 as Integer) + dbg(obj, "error", message, code) +end function + +function errx(obj as Object, message as String, code=0 as Integer) + dbg(obj, "fatal", message, code) + stop +end function + +function UnixNL() + return chr(10) +end function + +function WinNL() + return chr(13) + chr(10) +end function + +function Quote() + return chr(34) +end function + +function rfc1123_date(when as Object) + wd = when.getWeekday().left(3) + dom = Stri(when.getDayOfMonth()).trim() + mon = Ucase(MonthStr(when.getMonth()).left(3)) + yr = Stri(when.getYear()).trim() + hr = Stri(when.getHours()).trim() + mn = Stri(when.getMinutes()).trim() + sc = Stri(when.getSeconds()).trim() + date = wd+", "+dom+" "+mon+" "+yr+" "+hr+":"+mn+":"+sc+" GMT" + return date +end function + +function date_rfc1123(when as String) + date = CreateObject("roDateTime") + parts = when.tokenize(", ") + if parts.count()=8 + iso8601 = parts.GetIndex(3) + "-" + monthNum(parts.GetIndex(2)) + "-" + parts.GetIndex(1) + " " + parts.GetIndex(4) + ":" + parts.GetIndex(5) + ":" + parts.GetIndex(6) + date.fromISO8601String(iso8601) + end if + return date +end function + +function monthNum(mStr as String) + mm = m.Month2Num + if mm=invalid + mm = {jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12} + m.Month2Num = mm + end if + return validint(mm[lcase(mStr.left(3))]) +end function + +function monthStr(mNum as Integer) + ma = m.Num2Month + if ma=invalid + ma = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"] + m.Num2Month = ma + end if + return validstr(ma[mNum-1]) +end function + +function HttpTitle(code=0 as Integer) as String + hcm = m.HttpTitles + if hcm=invalid + hcm = {n200:"OK",n206:"Partial Content"} + hcm.append({n301:"Moved Permanently",n304:"Not Modified"}) + hcm.append({n400:"Bad Request",n403:"Forbidden",n404:"Not Found",n413:"Request Entity Too Large"}) + hcm.append({n500:"Internal Server Error",n501:"Not Implemented"}) + m.HttpTitles = hcm + end if + return validstr(hcm["n"+Stri(code).trim()]) +end function + +function Now() as Object + this = m.now + if this = invalid + this = CreateObject("roDateTime") + m.now = this + end if + this.mark() + return this +end function + +function UrlEncode(url as String) as String + ue = m.UrlEncoder + if ue = invalid + ue = CreateObject("roUrlTransfer") + m.UrlEncoder = ue + end if + return ue.UrlEncode(url) +end function + +function UrlEscape(url as String) as String + ue = m.UrlEncoder + if ue = invalid + ue = CreateObject("roUrlTransfer") + m.UrlEncoder = ue + end if + return ue.escape(url) +end function + +function UrlUnescape(url as String) as String + ue = m.UrlEncoder + if ue = invalid + ue = CreateObject("roUrlTransfer") + m.UrlEncoder = ue + end if + return ue.unescape(url) +end function + +function MimeType(uri="" as String) as String + map = m.MimeTypes + if map = invalid + map = { + ' Default mimetype mappings + ogg:"application/ogg", + pdf:"application/pdf", + xsl:"application/xml", + xml:"application/xml", + dtd:"application/xml-dtd", + xslt:"application/xslt+xml", + zip:"application/zip", + mp2:"audio/mpeg", + mp3:"audio/mpeg", + mpga:"audio/mpeg", + gif:"image/gif", + jpeg:"image/jpeg", + jpe:"image/jpeg", + jpg:"image/jpeg", + png:"image/png", + css:"text/css", + html:"text/html", + js:"text/javascript", + txt:"text/plain", + asc:"text/plain", +' brs:"text/plain", ' for brightscript code + mpeg:"video/mpeg", + mpe:"video/mpeg", + mpg:"video/mpeg", + qt:"video/quicktime", + mov:"video/quicktime", + avi:"video/x-msvideo", + default:"application/octet-stream" + } + m.MimeTypes = map + end if + ext = GetExtension(uri) + if map.doesexist(ext) then return map[ext] else return map.default +end function + +function GetExtension(fn as String) as String + l = fn.tokenize(".") + if l.count()>0 then return l.GetTail() else return "" +end function + +function deduceType(val as String, force=invalid as Dynamic) as Dynamic + if isstr(force) + tforce = lcase(force) + if tforce.right(6)="string" then return val + if tforce.left(3)="int" then return strtoi(val) + if tforce.left(4)="bool" then return (lcase(val)="true" or strtoi(val)=1) + end if + tval = lcase(val) + if tval="false" then return false + if tval="true" then return true + if tval="0" then return 0 + tval = strtoi(val) + if tval<>0 then return tval + return val +end function + +function XMLToAA(xml as Object, aa as Object) as Boolean + if lcase(type(xml))<>"roxmlelement" + print "XMLToAA: "; type(xml); " is not roXMLElement" + return false + end if + name = xml.GetName() + body = xml.GetBody() + etype = lcase(type(body)) + if isstr(name) + if etype = "roxmllist" + node = aa[name] + ' create only if doesn't exist + if lcase(type(node))<>"roassociativearray" + node= CreateObject("roAssociativeArray") + aa[name] = node + end if + for each elem in body + XMLtoAA(elem,node) + end for + else if etype.right(6)="string" + attr = xml.GetAttributes() + ftype = attr.type + val = deduceType(body,ftype) + aa[name] = val + else + print "XMLToAA: Unexpected element type "; type(body) + end if + end if + return true +end function + +function GetXMLConfig(file as String, config as Object) + ' could be called very early as part of global setup, + ' so be sure not to use anything that relies on that setup. + configTxt = ReadAsciiFile("pkg:/"+file) + if configTxt<>invalid and GetInterface(configTxt,"ifString")<>invalid + xml = CreateObject("roXmlElement") + if xml.Parse(configTxt) + print "GetXMLConfig: config '"; xml.GetName(); "'" + sections = xml.GetBody() + if islist(sections) + for each section in sections + XMLToAA(section,config) + end for + end if + else + print "GetXMLConfig: couldn't parse config text:" + print configTxt + end if + else + print "GetXMLConfig: no file "; file + end if +end function