From 054ad8d430c2998c3aae970787eb8936e62889f6 Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Fri, 4 Nov 2022 14:57:51 -0400 Subject: [PATCH] Brighterscript rewrite --- bsconfig.json | 3 +- src/source/webserver/Demo.txt | 52 +++ src/source/webserver/HttpConnection.bs | 165 ++++++++++ src/source/webserver/HttpConnectionState.bs | 7 + src/source/webserver/HttpReply.bs | 309 ++++++++++++++++++ src/source/webserver/HttpReplySource.bs | 5 + src/source/webserver/HttpRequest.bs | 101 ++++++ src/source/webserver/HttpServer.bs | 137 ++++++++ src/source/webserver/HttpSettings.bs | 20 ++ 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 | 88 +---- 15 files changed, 804 insertions(+), 989 deletions(-) create mode 100644 src/source/webserver/Demo.txt create mode 100644 src/source/webserver/HttpConnection.bs create mode 100644 src/source/webserver/HttpConnectionState.bs create mode 100644 src/source/webserver/HttpReply.bs create mode 100644 src/source/webserver/HttpReplySource.bs create mode 100644 src/source/webserver/HttpRequest.bs create mode 100644 src/source/webserver/HttpServer.bs create mode 100644 src/source/webserver/HttpSettings.bs delete mode 100644 src/source/webserver/connection.brs delete mode 100644 src/source/webserver/main.brs delete mode 100644 src/source/webserver/reply.brs delete mode 100644 src/source/webserver/request.brs delete mode 100644 src/source/webserver/server.brs diff --git a/bsconfig.json b/bsconfig.json index 32dd123d..7b8a2180 100644 --- a/bsconfig.json +++ b/bsconfig.json @@ -6,7 +6,8 @@ "images/**/*.*", "meta/**/*.*", "components/**/*.*", - "!**/*.spec.bs" + "!**/*.spec.bs", + "www/**/*.*" ], "autoImportComponentScript": true, "createPackage": false, diff --git a/src/source/webserver/Demo.txt b/src/source/webserver/Demo.txt new file mode 100644 index 00000000..5a0b781e --- /dev/null +++ b/src/source/webserver/Demo.txt @@ -0,0 +1,52 @@ +' Ported from https://sourceforge.net/p/rokusdkexamples/code/HEAD/tree/trunk/rokusdkexamples-code/web_server/ + +' function Main(args as dynamic) +' m.msgPort = CreateObject("roMessagePort") + +' settings = new RokuYoutube.Http.HttpSettings(m.msgPort) + +' ' Root at www to get http://192.168.1.107:8888/index.html +' settings.WwwRoot = "pkg:/www" + +' print `Using settings: ${settings}` + +' server = new RokuYoutube.Http.HttpServer(settings) + +' m.running = true +' timeout = validint(settings.Timeout) +' timer = CreateObject("roTimespan") +' update = true + +' while (m.running) +' if update +' timer.mark() +' PrintServerStatus(server) +' update = false +' end if +' server.PreWait() +' msg = wait(timeout, settings.MessagePort) +' 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 PrintServerStatus(server as HttpServer) +' print("-------") +' print(server.stats()) +' connections = server.connections +' count=0 +' for each connID in connections +' conn = connections[connID] +' print (` - Client: ${conn.client}; Total sent: ${conn.total_sent}; ID: ${conn.id}`) +' count++ +' end for +' if count = 0 +' print(" No active connections") +' end if +' print("-------") +' end function \ No newline at end of file diff --git a/src/source/webserver/HttpConnection.bs b/src/source/webserver/HttpConnection.bs new file mode 100644 index 00000000..561f1b86 --- /dev/null +++ b/src/source/webserver/HttpConnection.bs @@ -0,0 +1,165 @@ +namespace RokuYoutube.Http + class HttpConnection + const BUFSIZE = 65536 + + private total_received = 0 + private total_sent = 0 + private id = "" + private close = true + private state = HttpConnectionState.INIT + + private settings = invalid as HttpSettings + + function new(settings as HttpSettings) + m.settings = settings + m.Reset() + end function + + function Reset() + ' re-initializes all instance members + m.socket = invalid + m.addr = invalid + m.Restart() + end function + + function Restart() + ' re-initializes members for next request-reply + m.last_active = CreateObject("roTimespan") + m.request = new HttpRequest() + m.header = invalid + m.reply = invalid + m.header_only = false + m.http_code = 0 + m.close = true + m.SetState(HttpConnectionState.INIT) + end function + + function Recycle() + info(m, "recycle") + m.Restart() + m.SetState(HttpConnectionState.RECV_REQUEST) ' ready for another + end function + + function Accepted(server as HttpServer, socket as object) + m.socket = socket + m.id = Stri(socket.getID()).trim() + m.SetState(HttpConnectionState.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 PollRequest(server as HttpServer) + if m.state <> HttpConnectionState.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 = new HttpReply(m.request, m.settings) + m.reply.Process() + m.SetState(HttpConnectionState.SEND_HEADER) + else + m.setState(HttpConnectionState.DONE) + m.close = true + err(m, "couldn't process request or reply, closing @" + m.client) + end if + else if m.request.buf.len() > m.settings.MaxRequestLength ' die if it's too long + ' TODO default_reply doesn't exist? + m.default_reply(413, "Request Entity Too Large", "Your request was dropped because it was too long.") + m.SetState(HttpConnectionState.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 = HttpConnectionState.SEND_HEADER then m.PollHeader(server) + + end function + + function PollHeader(server as HttpServer) as boolean + if m.state <> HttpConnectionState.SEND_HEADER errx(m, "illegal header state @" + m.client) + + sent = m.reply.SendHeader(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.DoneHeader() + if m.reply.header_only + m.SetState(HttpConnectionState.DONE) + else + m.SetState(HttpConnectionState.SEND_REPLY) + m.PollReply(server) + end if + end if + end function + + function PollReply(server as HttpServer) + if m.state <> HttpConnectionState.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(HttpConnectionState.DONE) + end function + + function CheckTimeout(timeout as integer) + if m.last_active.totalSeconds() > timeout + m.close = true + m.SetState(HttpConnectionState.DONE) + end if + end function + + function CheckResult(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(HttpConnectionState.DONE) + end if + return gotSome + end function + + function SetState(newState as HttpConnectionState) + if m.state <> newState + 'info(m,"state change" + Stri(m.state) + " ->" + Stri(newState)) + m.state = newState + end if + end function + + function 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 + end class +end namespace \ No newline at end of file diff --git a/src/source/webserver/HttpConnectionState.bs b/src/source/webserver/HttpConnectionState.bs new file mode 100644 index 00000000..2600deca --- /dev/null +++ b/src/source/webserver/HttpConnectionState.bs @@ -0,0 +1,7 @@ +enum HttpConnectionState + INIT = 0 ' initial state; shouldn't last long + RECV_REQUEST = 1 ' receiving request + SEND_HEADER = 2 ' sending generated header + SEND_REPLY = 3 ' sending reply + DONE = 4 ' reply sent, close or reuse as indicated +end enum \ No newline at end of file diff --git a/src/source/webserver/HttpReply.bs b/src/source/webserver/HttpReply.bs new file mode 100644 index 00000000..75fa137b --- /dev/null +++ b/src/source/webserver/HttpReply.bs @@ -0,0 +1,309 @@ +namespace RokuYoutube.Http + function GetHttpReplyId() + m.http_reply_id = validint(m.http_reply_id) + 1 + return m.http_reply_id + end function + + class HttpReply + private source = HttpReplySource.NONE + + ' members + private buf = invalid + private header = invalid + private path = invalid + private request = invalid + private id = 0 + ' copy-initializable members + private start = 0 + private length = 0 + private sent = 0 + private header_sent = 0 + private header_only = false + private buf_start = 0 + private http_code = 0 + private mimetype = "text/html" ' for errors + + private settings = invalid as HttpSettings + + function new(request as HttpRequest, settings as HttpSettings) + m.id = GetHttpReplyId() + m.settings = settings + m.Init(request) + end function + + function Init(request as HttpRequest) + m.buf = CreateObject("roByteArray") + m.request = request + end function + + function 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.ProcessGetOrHead() + else if method = "HEAD" + m.ProcessGetOrHead() + 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 ProcessGetOrHead() as Boolean + ' work out path of file being requested + req = m.request + uri = req.uri + decoded_uri = UrlUnescape(uri) + path = CreateObject("roPath", m.settings.WwwRoot + decoded_uri) + 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(m.settings.IndexName) + m.GenerateDirectoryListing() + 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 = HttpReplySource.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.GenerateHeader() + return true + end function + + function 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.GeneratedBy() + UnixNL() + buf = buf + "" + UnixNL() + + m.buf.fromasciistring(buf) + m.length = m.buf.count() + + m.GenerateHeader(true) + m.source = HttpReplySource.GENERATED + end function + + function Redirect(where as string) + m.location = where + message = "Moved to: " + where + "" + m.Default(301, message) + end function + + function Send(sock as object, bufsize as integer) as integer + sent = -1 + if m.source = HttpReplySource.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 SendHeader(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 + + function GenerateDirectoryListing() + 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 + "" + m.settings.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.GeneratedBy() + UnixNL() + listing = listing + "" + UnixNL() + listing = listing + "" + UnixNL() + + m.buf.FromAsciiString(listing) + m.length = m.buf.count() + + m.http_code = 200 + m.GenerateHeader() + m.source = HttpReplySource.GENERATED + return true + end function + + function GenerateHeader(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: " + m.settings.PackageName + 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" + m.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 Done() + return m.sent = m.length + end function + + function DoneHeader() + return m.header_sent = m.header_length + end function + + function Log(recent as integer, from as integer, total as integer) + info(m, "Sent" + Stri(recent) + " [" + m.MakeRange(from, recent, total) + "]") + end function + + function KeepAlive(close as boolean) as string + if close then base = "Connection: close" else base = "Keep-Alive: timeout=" + Stri(m.settings.Idletime).trim() + return base + end function + + function GeneratedBy() + return "generated by " + m.settings.PackageName + " on " + m.now + end function + + function MakeRange(start as integer, length as integer, total as integer) + return itostr(start) + "-" + itostr(start + length - 1) + "/" + itostr(total) + end function + + end class +end namespace diff --git a/src/source/webserver/HttpReplySource.bs b/src/source/webserver/HttpReplySource.bs new file mode 100644 index 00000000..f96b6a0c --- /dev/null +++ b/src/source/webserver/HttpReplySource.bs @@ -0,0 +1,5 @@ +enum HttpReplySource + NONE = 0 + GENERATED = 1 + FROMFILE = 2 +end enum \ No newline at end of file diff --git a/src/source/webserver/HttpRequest.bs b/src/source/webserver/HttpRequest.bs new file mode 100644 index 00000000..ff89f27e --- /dev/null +++ b/src/source/webserver/HttpRequest.bs @@ -0,0 +1,101 @@ +namespace RokuYoutube.Http + function GetHttpRequestId() + m.http_request_id = validint(m.http_request_id) + 1 + return m.http_request_id + end function + + class HttpRequest + const Unix2NewLine = UnixNL() + UnixNL() + const Windows2NewLine = WinNL() + WinNL() + + ' members + private method = invalid + private uri = invalid + private protocol = invalid + private buf = invalid + private fields = invalid + 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 + + function new() + m.id = GetHttpRequestId() + m.fields = CreateObject("roAssociativeArray") + end function + + function Add(incoming as string) + if isstr(m.buf) then m.buf = m.buf + incoming else m.buf = incoming + end function + + function IsComplete() as boolean + buf = m.buf + ' TODO check if Unix2NewLine is right + 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 + + 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()) + 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.ParseConnection(connection) + 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 ParseRange() + 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 hyphen < last + m.range_end = strtoi(range.right(last - hyphen)) + m.range_end_given = true + end if + end if + info(m, "range request begin" + Stri(m.range_begin) + " end" + Stri(m.range_end)) + end if + end function + + function ParseConnection(connection as HttpConnection) as boolean + connectionStr = m.fields.connection + if connectionStr <> invalid then connection.close = (lcase(connectionStr.trim()) = "close") + end function + + function Process(connection as HttpConnection) as boolean + return m.Parse(connection) + end function + end class +end namespace diff --git a/src/source/webserver/HttpServer.bs b/src/source/webserver/HttpServer.bs new file mode 100644 index 00000000..8a044afe --- /dev/null +++ b/src/source/webserver/HttpServer.bs @@ -0,0 +1,137 @@ +namespace RokuYoutube.Http + function InitGlobals() + MimeType() + HttpTitle() + end function + + class HttpServer + ' members + private connections = invalid + private sockin = invalid + private uptime = invalid + + ' initializable (copied) members + private num_requests = 0 + private total_in = 0 + private total_out = 0 + + private settings = invalid as HttpSettings + + function new(settings as HttpSettings) + m.settings = settings + InitGlobals() + m.Init() + end function + + function Init() + 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.settings.Port) + if not sockin.setAddress(addrin) then errx(m, "bind(port" + Stri(m.settings.Port) + ")", sockin.status()) + + ' listen on socket + if not sockin.listen(m.settings.MaxConnections) then errx(m, "listen()", sockin.status()) + + ' monitor socket + sockin.setMessagePort(m.settings.MessagePort)) + sockin.notifyReadable(true) + + m.sockin = sockin + + info(m, "listening on " + addrin.getAddress()) + end function + + function PreWait() + connections = m.connections + for each id in connections + conn = connections[id] + conn.CheckTimeout(m.settings.Timeout) + cs = conn.state + if cs = HttpConnectionState.DONE + conn.socket.notifyReadable(false) + conn.socket.notifyWritable(false) + else if cs = HttpConnectionState.RECV_REQUEST + conn.socket.notifyReadable(true) + conn.socket.notifyWritable(false) + else if cs = HttpConnectionState.SEND_HEADER or cs = HttpConnectionState.SEND_REPLY + conn.socket.notifyWritable(true) + conn.socket.notifyReadable(false) + else + errx(m, "invalid state") + end if + end for + end function + + function PostWait() + connections = m.connections + if m.sockin.isReadable() + conn = m.AcceptHttpConnection() + if conn <> invalid then connections[conn.id] = conn + end if + for each id in connections + conn = connections[id] + cs = conn.state + if cs = HttpConnectionState.RECV_REQUEST + if conn.socket.isReadable() then conn.PollRequest(m) + else if cs = HttpConnectionState.SEND_HEADER + if conn.socket.isWritable() then conn.PollHeader(m) + else if cs = HttpConnectionState.SEND_REPLY + if conn.socket.isWritable() then conn.PollReply(m) + else if cs = HttpConnectionState.DONE + ' handle with other connections that might transition to done + else + errx(m, "invalid state") + end if + cs = conn.state + if cs = HttpConnectionState.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 AcceptHttpConnection() as HttpConnection + sockin = m.sockin + socket = sockin.accept() + if not sockin.eOK() err(m, "accept()", sockin.status()) + if socket = invalid then return invalid + conn = new HttpConnection(m.settings) + conn.Accepted(m, socket) + return conn + end function + + function 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 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 + end class +end namespace \ No newline at end of file diff --git a/src/source/webserver/HttpSettings.bs b/src/source/webserver/HttpSettings.bs new file mode 100644 index 00000000..55c24d3f --- /dev/null +++ b/src/source/webserver/HttpSettings.bs @@ -0,0 +1,20 @@ +namespace RokuYoutube.Http + class HttpSettings + + PackageName = "Youtube for Roku" + Port = 8888 + MessagePort = invalid + MaxConnections = 3 + Timeout = 60 + MaxRequestLength = 4000 + Idletime = 60 + WwwRoot = "pkg:/" + IndexName = "index.html" + ServerName = "Roku Youtube Server" + + function new(messagePort) + m.MessagePort = messagePort + end function + + end class +end namespace \ No newline at end of file diff --git a/src/source/webserver/connection.brs b/src/source/webserver/connection.brs deleted file mode 100644 index 09580933..00000000 --- a/src/source/webserver/connection.brs +++ /dev/null @@ -1,207 +0,0 @@ -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 deleted file mode 100644 index 0560dd52..00000000 --- a/src/source/webserver/main.brs +++ /dev/null @@ -1,108 +0,0 @@ - ' 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 deleted file mode 100644 index 167ce946..00000000 --- a/src/source/webserver/reply.brs +++ /dev/null @@ -1,337 +0,0 @@ -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 deleted file mode 100644 index a28ab5b6..00000000 --- a/src/source/webserver/request.brs +++ /dev/null @@ -1,114 +0,0 @@ -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 deleted file mode 100644 index 11bd65cb..00000000 --- a/src/source/webserver/server.brs +++ /dev/null @@ -1,140 +0,0 @@ -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 index 3e8f1708..b1c5b0b2 100644 --- a/src/source/webserver/utils.brs +++ b/src/source/webserver/utils.brs @@ -1,27 +1,3 @@ -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 @@ -188,7 +164,9 @@ function MimeType(uri="" as String) as String js:"text/javascript", txt:"text/plain", asc:"text/plain", -' brs:"text/plain", ' for brightscript code + brs:"text/plain", + bs:"text/plain", + map:"text/plain", mpeg:"video/mpeg", mpe:"video/mpeg", mpg:"video/mpeg", @@ -208,7 +186,7 @@ function GetExtension(fn as String) as String if l.count()>0 then return l.GetTail() else return "" end function -function deduceType(val as String, force=invalid as Dynamic) as Dynamic +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 @@ -222,58 +200,4 @@ function deduceType(val as String, force=invalid as Dynamic) as Dynamic 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 +end function \ No newline at end of file