增加高压空闲调节
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2024 Jean-Christophe Bos (jczic.bos@gmail.com)
|
||||
"""
|
||||
|
||||
print()
|
||||
print(' -------------------------')
|
||||
print(' - Python MicroWebSrv2 -')
|
||||
print(' - version 2.1.0 -')
|
||||
print(' - by JC`zic -')
|
||||
print(' -------------------------')
|
||||
print()
|
||||
|
||||
from .libs.XAsyncSockets import *
|
||||
from .libs.urlUtils import *
|
||||
from .webRoute import *
|
||||
from .microWebSrv2 import *
|
||||
@@ -0,0 +1,416 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from . import *
|
||||
from .httpResponse import HttpResponse
|
||||
from binascii import a2b_base64
|
||||
import json
|
||||
|
||||
# ============================================================================
|
||||
# ===( HttpRequest )==========================================================
|
||||
# ============================================================================
|
||||
|
||||
class HttpRequest :
|
||||
|
||||
MAX_RECV_HEADER_LINES = 100
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, microWebSrv2, xasCli) :
|
||||
self._mws2 = microWebSrv2
|
||||
self._xasCli = xasCli
|
||||
self._waitForRecvRequest()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _recvLine(self, onRecv) :
|
||||
self._xasCli.AsyncRecvLine(onLineRecv=onRecv, timeoutSec=self._mws2._timeoutSec)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _waitForRecvRequest(self) :
|
||||
self._httpVer = ''
|
||||
self._method = ''
|
||||
self._path = ''
|
||||
self._headers = { }
|
||||
self._content = None
|
||||
self._response = HttpResponse(self._mws2, self)
|
||||
self._recvLine(self._onFirstLineRecv)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onFirstLineRecv(self, xasCli, line, arg) :
|
||||
try :
|
||||
elements = line.strip().split()
|
||||
if len(elements) == 3 :
|
||||
self._httpVer = elements[2].upper()
|
||||
self._method = elements[0].upper()
|
||||
elements = elements[1].split('?', 1)
|
||||
self._path = UrlUtils.UnquotePlus(elements[0])
|
||||
self._queryString = (elements[1] if len(elements) > 1 else '')
|
||||
self._queryParams = { }
|
||||
if self._queryString :
|
||||
elements = self._queryString.split('&')
|
||||
for s in elements :
|
||||
p = s.split('=', 1)
|
||||
if len(p) > 0 :
|
||||
v = (UrlUtils.Unquote(p[1]) if len(p) > 1 else '')
|
||||
self._queryParams[UrlUtils.Unquote(p[0])] = v
|
||||
self._recvLine(self._onHeaderLineRecv)
|
||||
else :
|
||||
self._response.ReturnBadRequest()
|
||||
except :
|
||||
self._response.ReturnBadRequest()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onHeaderLineRecv(self, xasCli, line, arg) :
|
||||
try :
|
||||
elements = line.strip().split(':', 1)
|
||||
if len(elements) == 2 :
|
||||
if len(self._headers) < HttpRequest.MAX_RECV_HEADER_LINES :
|
||||
self._headers[elements[0].strip().lower()] = elements[1].strip()
|
||||
self._recvLine(self._onHeaderLineRecv)
|
||||
else :
|
||||
self._response.ReturnEntityTooLarge()
|
||||
elif len(elements) == 1 and len(elements[0]) == 0 :
|
||||
self._processRequest()
|
||||
else :
|
||||
self._response.ReturnBadRequest()
|
||||
except :
|
||||
self._response.ReturnBadRequest()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processRequest(self) :
|
||||
if not self._processRequestModules() :
|
||||
if not self.IsUpgrade :
|
||||
if not self._processRequestRoutes() :
|
||||
if self._method in ('GET', 'HEAD') :
|
||||
filename = self._mws2.ResolvePhysicalPath(self._path)
|
||||
if filename :
|
||||
ct = self._mws2.GetMimeTypeFromFilename(filename)
|
||||
if ct :
|
||||
self._response.AllowCaching = True
|
||||
self._response.ContentType = ct
|
||||
self._response.ReturnFile(filename)
|
||||
else :
|
||||
self._response.ReturnForbidden()
|
||||
else :
|
||||
self._response.ReturnNotFound()
|
||||
elif self._method == 'OPTIONS' :
|
||||
if self._mws2.CORSAllowAll :
|
||||
self._response.SetHeader( 'Access-Control-Allow-Methods', '*' )
|
||||
self._response.SetHeader( 'Access-Control-Allow-Headers', '*' )
|
||||
self._response.SetHeader( 'Access-Control-Allow-Credentials', 'true' )
|
||||
self._response.SetHeader( 'Access-Control-Max-Age', '86400' )
|
||||
self._response.ReturnOk()
|
||||
else :
|
||||
self._response.ReturnMethodNotAllowed()
|
||||
else :
|
||||
self._response.ReturnNotImplemented()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processRequestModules(self) :
|
||||
for modName, modInstance in self._mws2._modules.items() :
|
||||
try :
|
||||
modInstance.OnRequest(self._mws2, self)
|
||||
if self._response.HeadersSent :
|
||||
return True
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception in request handler of module "%s" (%s).'
|
||||
% (modName, ex),
|
||||
self._mws2.ERROR )
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processRequestRoutes(self) :
|
||||
self._routeResult = ResolveRoute(self._method, self._path)
|
||||
if self._routeResult :
|
||||
cntLen = self.ContentLength
|
||||
if not cntLen :
|
||||
self._routeRequest()
|
||||
elif self._method != 'GET' and self._method != 'HEAD' :
|
||||
if cntLen <= self._mws2._maxContentLen :
|
||||
def onContentRecv(xasCli, content, arg) :
|
||||
self._content = content
|
||||
self._routeRequest()
|
||||
self._content = None
|
||||
try :
|
||||
self._xasCli.AsyncRecvData( size = cntLen,
|
||||
onDataRecv = onContentRecv,
|
||||
timeoutSec = self._mws2._timeoutSec )
|
||||
except :
|
||||
self._mws2.Log( 'Not enough memory to read a content of %s bytes.' % cntLen,
|
||||
self._mws2.ERROR )
|
||||
self._response.ReturnServiceUnavailable()
|
||||
else :
|
||||
self._response.ReturnEntityTooLarge()
|
||||
else :
|
||||
self._response.ReturnBadRequest()
|
||||
return True
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _routeRequest(self) :
|
||||
try :
|
||||
currentResp = self._response
|
||||
if self._routeResult.Args :
|
||||
self._routeResult.Handler(self._mws2, self, self._routeResult.Args)
|
||||
else :
|
||||
self._routeResult.Handler(self._mws2, self)
|
||||
if not currentResp.HeadersSent :
|
||||
self._mws2.Log( 'No response was sent from route %s.'
|
||||
% self._routeResult,
|
||||
self._mws2.WARNING )
|
||||
currentResp.ReturnNotImplemented()
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from route %s: %s'
|
||||
% (self._routeResult, ex),
|
||||
self._mws2.ERROR )
|
||||
currentResp.ReturnInternalServerError()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetPostedURLEncodedForm(self) :
|
||||
res = { }
|
||||
if self.ContentType.lower() == 'application/x-www-form-urlencoded' :
|
||||
try :
|
||||
elements = bytes(self._content).decode('UTF-8').split('&')
|
||||
for s in elements :
|
||||
p = s.split('=', 1)
|
||||
if len(p) > 0 :
|
||||
v = (UrlUtils.UnquotePlus(p[1]) if len(p) > 1 else '')
|
||||
res[UrlUtils.UnquotePlus(p[0])] = v
|
||||
except :
|
||||
pass
|
||||
return res
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetPostedJSONObject(self) :
|
||||
if self.ContentType.lower() == 'application/json' :
|
||||
try :
|
||||
s = bytes(self._content).decode('UTF-8')
|
||||
return json.loads(s)
|
||||
except :
|
||||
pass
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetHeader(self, name) :
|
||||
if not isinstance(name, str) or len(name) == 0 :
|
||||
raise ValueError('"name" must be a not empty string.')
|
||||
return self._headers.get(name.lower(), '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def CheckBasicAuth(self, username, password) :
|
||||
if not isinstance(username, str) :
|
||||
raise ValueError('"username" must be a string.')
|
||||
if not isinstance(password, str) :
|
||||
raise ValueError('"password" must be a string.')
|
||||
auth = self.Authorization
|
||||
if auth :
|
||||
try :
|
||||
auth = auth.split()
|
||||
if len(auth) == 2 and auth[0].lower() == 'basic' :
|
||||
auth = a2b_base64(auth[1].encode()).decode()
|
||||
auth = auth.split(':')
|
||||
return ( auth[0].lower() == username.lower() and \
|
||||
auth[1] == password )
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def CheckBearerAuth(self, token) :
|
||||
if not isinstance(token, str) :
|
||||
raise ValueError('"token" must be a string.')
|
||||
auth = self.Authorization
|
||||
if auth :
|
||||
try :
|
||||
auth = auth.split()
|
||||
return ( len(auth) == 2 and \
|
||||
auth[0].lower() == 'bearer' and \
|
||||
auth[1] == token )
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def UserAddress(self) :
|
||||
return self._xasCli.CliAddr
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsSSL(self) :
|
||||
return self._xasCli.IsSSL
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def HttpVer(self) :
|
||||
return self._httpVer
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Method(self) :
|
||||
return self._method
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Path(self) :
|
||||
return self._path
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def QueryString(self) :
|
||||
return self._queryString
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def QueryParams(self) :
|
||||
return self._queryParams
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Host(self) :
|
||||
return self._headers.get('host', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Accept(self) :
|
||||
s = self._headers.get('accept', None)
|
||||
if s :
|
||||
return [x.strip() for x in s.split(',')]
|
||||
return [ ]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def AcceptEncodings(self) :
|
||||
s = self._headers.get('accept-encoding', None)
|
||||
if s :
|
||||
return [x.strip() for x in s.split(',')]
|
||||
return [ ]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def AcceptLanguages(self) :
|
||||
s = self._headers.get('accept-language', None)
|
||||
if s :
|
||||
return [x.strip() for x in s.split(',')]
|
||||
return [ ]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Cookies(self) :
|
||||
s = self._headers.get('cookie', None)
|
||||
if s :
|
||||
return [x.strip() for x in s.split(';')]
|
||||
return [ ]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def CacheControl(self) :
|
||||
return self._headers.get('cache-control', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Referer(self) :
|
||||
return self._headers.get('referer', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ContentType(self) :
|
||||
return self._headers.get('content-type', '').split(';', 1)[0].strip()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ContentLength(self) :
|
||||
try :
|
||||
return int(self._headers.get('content-length', 0))
|
||||
except :
|
||||
return 0
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def UserAgent(self) :
|
||||
return self._headers.get('user-agent', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Authorization(self) :
|
||||
return self._headers.get('authorization', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Origin(self) :
|
||||
return self._headers.get('origin', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsKeepAlive(self) :
|
||||
return ('keep-alive' in self._headers.get('connection', '').lower())
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsUpgrade(self) :
|
||||
return ('upgrade' in self._headers.get('connection', '').lower())
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Upgrade(self) :
|
||||
return self._headers.get('upgrade', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Content(self) :
|
||||
return self._content
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Response(self) :
|
||||
return self._response
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def XAsyncTCPClient(self) :
|
||||
return self._xasCli
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,550 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from os import stat
|
||||
import json
|
||||
|
||||
# ============================================================================
|
||||
# ===( HttpResponse )=========================================================
|
||||
# ============================================================================
|
||||
|
||||
class HttpResponse :
|
||||
|
||||
_RESPONSE_CODES = {
|
||||
100: ( 'Continue',
|
||||
'Request received, please continue.' ),
|
||||
101: ( 'Switching Protocols',
|
||||
'Switching to new protocol; obey Upgrade header.' ),
|
||||
200: ( 'OK',
|
||||
'Request fulfilled, document follows.' ),
|
||||
201: ( 'Created',
|
||||
'Document created, URL follows' ),
|
||||
202: ( 'Accepted',
|
||||
'Request accepted, processing continues off-line.' ),
|
||||
203: ( 'Non-Authoritative Information',
|
||||
'Request fulfilled from cache' ),
|
||||
204: ( 'No Content',
|
||||
'Request fulfilled, nothing follows.' ),
|
||||
205: ( 'Reset Content',
|
||||
'Clear input form for further input.' ),
|
||||
206: ( 'Partial Content',
|
||||
'Partial content follows.' ),
|
||||
300: ( 'Multiple Choices',
|
||||
'Object has several resources -- see URI list.' ),
|
||||
301: ( 'Moved Permanently',
|
||||
'Object moved permanently -- see URI list.' ),
|
||||
302: ( 'Found',
|
||||
'Object moved temporarily -- see URI list.' ),
|
||||
303: ( 'See Other',
|
||||
'Object moved -- see Method and URL list.' ),
|
||||
304: ( 'Not Modified',
|
||||
'Document has not changed since given time.' ),
|
||||
305: ( 'Use Proxy',
|
||||
'You must use proxy specified in Location to access this resource.' ),
|
||||
307: ( 'Temporary Redirect',
|
||||
'Object moved temporarily -- see URI list.' ),
|
||||
400: ( 'Bad Request',
|
||||
'Bad request syntax or unsupported method.' ),
|
||||
401: ( 'Unauthorized',
|
||||
'No permission -- see authorization schemes.' ),
|
||||
402: ( 'Payment Required',
|
||||
'No payment -- see charging schemes.' ),
|
||||
403: ( 'Forbidden',
|
||||
'Request forbidden -- authorization will not help.' ),
|
||||
404: ( 'Not Found',
|
||||
'Nothing matches the given URI.' ),
|
||||
405: ( 'Method Not Allowed',
|
||||
'Specified method is invalid for this resource.' ),
|
||||
406: ( 'Not Acceptable',
|
||||
'URI not available in preferred format.' ),
|
||||
407: ( 'Proxy Authentication Required',
|
||||
'You must authenticate with this proxy before proceeding.' ),
|
||||
408: ( 'Request Timeout',
|
||||
'Request timed out; try again later.' ),
|
||||
409: ( 'Conflict',
|
||||
'Request conflict.' ),
|
||||
410: ( 'Gone',
|
||||
'URI no longer exists and has been permanently removed.' ),
|
||||
411: ( 'Length Required',
|
||||
'Client must specify Content-Length.' ),
|
||||
412: ( 'Precondition Failed',
|
||||
'Precondition in headers is false.' ),
|
||||
413: ( 'Request Entity Too Large',
|
||||
'Entity is too large.' ),
|
||||
414: ( 'Request-URI Too Long',
|
||||
'URI is too long.' ),
|
||||
415: ( 'Unsupported Media Type',
|
||||
'Entity body in unsupported format.' ),
|
||||
416: ( 'Requested Range Not Satisfiable',
|
||||
'Cannot satisfy request range.' ),
|
||||
417: ( 'Expectation Failed',
|
||||
'Expect condition could not be satisfied.' ),
|
||||
500: ( 'Internal Server Error',
|
||||
'Server got itself in trouble.' ),
|
||||
501: ( 'Not Implemented',
|
||||
'Server does not support this operation.' ),
|
||||
502: ( 'Bad Gateway',
|
||||
'Invalid responses from another server/proxy.' ),
|
||||
503: ( 'Service Unavailable',
|
||||
'The server cannot process the request due to a high load.' ),
|
||||
504: ( 'Gateway Timeout',
|
||||
'The gateway server did not receive a timely response.' ),
|
||||
505: ( 'HTTP Version Not Supported',
|
||||
'Cannot fulfill request.' )
|
||||
}
|
||||
|
||||
_CODE_CONTENT_TMPL = """\
|
||||
<html>
|
||||
<head>
|
||||
<title>MicroWebSrv2</title>
|
||||
</head>
|
||||
<body style="font-family: Verdana; background-color: Black; color: White;">
|
||||
<h2>MicroWebSrv2 - [%(code)d] %(reason)s</h2>
|
||||
%(message)s
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, microWebSrv2, request) :
|
||||
self._mws2 = microWebSrv2
|
||||
self._request = request
|
||||
self._xasCli = request.XAsyncTCPClient
|
||||
self._headers = { }
|
||||
self._allowCaching = False
|
||||
self._acAllowOrigin = None
|
||||
self._contentType = None
|
||||
self._contentCharset = None
|
||||
self._contentLength = 0
|
||||
self._stream = None
|
||||
self._sendingBuf = None
|
||||
self._hdrSent = False
|
||||
self._onSent = None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetHeader(self, name, value) :
|
||||
if not isinstance(name, str) or len(name) == 0 :
|
||||
raise ValueError('"name" must be a not empty string.')
|
||||
if value is None :
|
||||
raise ValueError('"value" cannot be None.')
|
||||
self._headers[name] = str(value)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onDataSent(self, xasCli, arg) :
|
||||
if self._stream :
|
||||
try :
|
||||
n = self._stream.readinto(self._sendingBuf)
|
||||
if n < len(self._sendingBuf) :
|
||||
self._stream.close()
|
||||
self._stream = None
|
||||
self._sendingBuf = self._sendingBuf[:n]
|
||||
except :
|
||||
self._xasCli.Close()
|
||||
self._mws2.Log( 'Stream cannot be read for request "%s".'
|
||||
% self._request._path,
|
||||
self._mws2.ERROR )
|
||||
return
|
||||
if self._sendingBuf :
|
||||
if self._contentLength :
|
||||
self._xasCli.AsyncSendSendingBuffer( size = len(self._sendingBuf),
|
||||
onDataSent = self._onDataSent )
|
||||
if not self._stream :
|
||||
self._sendingBuf = None
|
||||
else :
|
||||
def onChunkHdrSent(xasCli, arg) :
|
||||
def onChunkDataSent(xasCli, arg) :
|
||||
def onLastChunkSent(xasCli, arg) :
|
||||
self._xasCli.AsyncSendData(b'0\r\n\r\n', onDataSent=self._onDataSent)
|
||||
if self._stream :
|
||||
onDataSent = self._onDataSent
|
||||
else :
|
||||
self._sendingBuf = None
|
||||
onDataSent = onLastChunkSent
|
||||
self._xasCli.AsyncSendData(b'\r\n', onDataSent=onDataSent)
|
||||
self._xasCli.AsyncSendSendingBuffer( size = len(self._sendingBuf),
|
||||
onDataSent = onChunkDataSent )
|
||||
data = ('%x\r\n' % len(self._sendingBuf)).encode()
|
||||
self._xasCli.AsyncSendData(data, onDataSent=onChunkHdrSent)
|
||||
else :
|
||||
self._xasCli.OnClosed = None
|
||||
if self._keepAlive :
|
||||
self._request._waitForRecvRequest()
|
||||
else :
|
||||
self._xasCli.Close()
|
||||
if self._onSent :
|
||||
try :
|
||||
self._onSent(self._mws2, self)
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from "Response.OnSent" handler: %s' % ex,
|
||||
self._mws2.ERROR )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onClosed(self, xasCli, closedReason) :
|
||||
if self._stream :
|
||||
try :
|
||||
self._stream.close()
|
||||
except :
|
||||
pass
|
||||
self._stream = None
|
||||
self._sendingBuf = None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _makeBaseResponseHdr(self, code) :
|
||||
reason = self._RESPONSE_CODES.get(code, ('Unknown reason', ))[0]
|
||||
self._mws2.Log( 'From %s:%s %s%s %s >> [%s] %s'
|
||||
% ( self._xasCli.CliAddr[0],
|
||||
self._xasCli.CliAddr[1],
|
||||
('SSL-' if self.IsSSL else ''),
|
||||
self._request._method,
|
||||
self._request._path,
|
||||
code,
|
||||
reason ),
|
||||
self._mws2.DEBUG )
|
||||
if self._mws2.AllowAllOrigins :
|
||||
self._acAllowOrigin = self._request.Origin
|
||||
if self._acAllowOrigin :
|
||||
self.SetHeader('Access-Control-Allow-Origin', self._acAllowOrigin)
|
||||
self.SetHeader('Server', 'MicroWebSrv2 by JC`zic')
|
||||
hdr = ''
|
||||
for n in self._headers :
|
||||
hdr += '%s: %s\r\n' % (n, self._headers[n])
|
||||
resp = 'HTTP/1.1 %s %s\r\n%s\r\n' % (code, reason, hdr)
|
||||
return resp.encode('ISO-8859-1')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _makeResponseHdr(self, code) :
|
||||
if code >= 200 and code < 300 :
|
||||
self._keepAlive = self._request.IsKeepAlive
|
||||
else :
|
||||
self._keepAlive = False
|
||||
if self._keepAlive :
|
||||
self.SetHeader('Connection', 'Keep-Alive')
|
||||
self.SetHeader('Keep-Alive', 'timeout=%s' % self._mws2._timeoutSec)
|
||||
else :
|
||||
self.SetHeader('Connection', 'Close')
|
||||
if self._allowCaching :
|
||||
self.SetHeader('Cache-Control', 'public, max-age=31536000')
|
||||
else :
|
||||
self.SetHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
|
||||
if self._contentType :
|
||||
ct = self._contentType
|
||||
if self._contentCharset :
|
||||
ct += '; charset=%s' % self._contentCharset
|
||||
self.SetHeader('Content-Type', ct)
|
||||
if self._contentLength :
|
||||
self.SetHeader('Content-Length', self._contentLength)
|
||||
return self._makeBaseResponseHdr(code)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SwitchingProtocols(self, upgrade) :
|
||||
if not isinstance(upgrade, str) or len(upgrade) == 0 :
|
||||
raise ValueError('"upgrade" must be a not empty string.')
|
||||
if self._hdrSent :
|
||||
self._mws2.Log( 'Response headers already sent for request "%s".'
|
||||
% self._request._path,
|
||||
self._mws2.WARNING )
|
||||
return
|
||||
self.SetHeader('Connection', 'Upgrade')
|
||||
self.SetHeader('Upgrade', upgrade)
|
||||
data = self._makeBaseResponseHdr(101)
|
||||
self._xasCli.AsyncSendData(data)
|
||||
self._hdrSent = True
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnStream(self, code, stream) :
|
||||
if not isinstance(code, int) or code <= 0 :
|
||||
raise ValueError('"code" must be a positive integer.')
|
||||
if not hasattr(stream, 'readinto') or not hasattr(stream, 'close') :
|
||||
raise ValueError('"stream" must be a readable buffer protocol object.')
|
||||
if self._hdrSent :
|
||||
self._mws2.Log( 'Response headers already sent for request "%s".'
|
||||
% self._request._path,
|
||||
self._mws2.WARNING )
|
||||
try :
|
||||
stream.close()
|
||||
except :
|
||||
pass
|
||||
return
|
||||
if self._request._method != 'HEAD' :
|
||||
self._stream = stream
|
||||
self._sendingBuf = memoryview(self._xasCli.SendingBuffer)
|
||||
self._xasCli.OnClosed = self._onClosed
|
||||
else :
|
||||
try :
|
||||
stream.close()
|
||||
except :
|
||||
pass
|
||||
if not self._contentType :
|
||||
self._contentType = 'application/octet-stream'
|
||||
if not self._contentLength :
|
||||
self.SetHeader('Transfer-Encoding', 'chunked')
|
||||
data = self._makeResponseHdr(code)
|
||||
self._xasCli.AsyncSendData(data, onDataSent=self._onDataSent)
|
||||
self._hdrSent = True
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def Return(self, code, content=None) :
|
||||
if not isinstance(code, int) or code <= 0 :
|
||||
raise ValueError('"code" must be a positive integer.')
|
||||
if self._hdrSent :
|
||||
self._mws2.Log( 'Response headers already sent for request "%s".'
|
||||
% self._request._path,
|
||||
self._mws2.WARNING )
|
||||
return
|
||||
if not content :
|
||||
respCode = self._RESPONSE_CODES.get(code, ('Unknown reason', ''))
|
||||
self._contentType = 'text/html'
|
||||
content = self._CODE_CONTENT_TMPL % { 'code' : code,
|
||||
'reason' : respCode[0],
|
||||
'message' : respCode[1] }
|
||||
if isinstance(content, str) :
|
||||
content = content.encode('UTF-8')
|
||||
if not self._contentType :
|
||||
self._contentType = 'text/html'
|
||||
self._contentCharset = 'UTF-8'
|
||||
elif not self._contentType :
|
||||
self._contentType = 'application/octet-stream'
|
||||
self._contentLength = len(content)
|
||||
data = self._makeResponseHdr(code)
|
||||
if self._request._method != 'HEAD' :
|
||||
data += bytes(content)
|
||||
self._xasCli.AsyncSendData(data, onDataSent=self._onDataSent)
|
||||
self._hdrSent = True
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnJSON(self, code, obj) :
|
||||
if not isinstance(code, int) or code <= 0 :
|
||||
raise ValueError('"code" must be a positive integer.')
|
||||
self._contentType = 'application/json'
|
||||
try :
|
||||
content = json.dumps(obj)
|
||||
except :
|
||||
raise ValueError('"obj" cannot be converted into JSON format.')
|
||||
self.Return(code, content)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnOk(self, content=None) :
|
||||
self.Return(200, content)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnOkJSON(self, obj) :
|
||||
self.ReturnJSON(200, obj)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnFile(self, filename, attachmentName=None) :
|
||||
if not isinstance(filename, str) or len(filename) == 0 :
|
||||
raise ValueError('"filename" must be a not empty string.')
|
||||
if attachmentName is not None and not isinstance(attachmentName, str) :
|
||||
raise ValueError('"attachmentName" must be a string or None.')
|
||||
try :
|
||||
size = stat(filename)[6]
|
||||
except :
|
||||
self.ReturnNotFound()
|
||||
return
|
||||
try :
|
||||
file = open(filename, 'rb')
|
||||
except :
|
||||
self.ReturnForbidden()
|
||||
return
|
||||
if attachmentName :
|
||||
cd = 'attachment; filename="%s"' % attachmentName.replace('"', "'")
|
||||
self.SetHeader('Content-Disposition', cd)
|
||||
if not self._contentType :
|
||||
self._contentType = self._mws2.GetMimeTypeFromFilename(filename)
|
||||
self._contentLength = size
|
||||
self.ReturnStream(200, file)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnNotModified(self) :
|
||||
self.Return(304)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnRedirect(self, location) :
|
||||
if not isinstance(location, str) or len(location) == 0 :
|
||||
raise ValueError('"location" must be a not empty string.')
|
||||
self.SetHeader('Location', location)
|
||||
self.Return(307)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnBadRequest(self) :
|
||||
self.Return(400)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnUnauthorized(self, typeName, realm=None) :
|
||||
if not isinstance(typeName, str) or len(typeName) == 0 :
|
||||
raise ValueError('"typeName" must be a not empty string.')
|
||||
if realm is not None and not isinstance(realm, str) :
|
||||
raise ValueError('"realm" must be a string or None.')
|
||||
wwwAuth = typeName
|
||||
if realm :
|
||||
wwwAuth += (' realm="%s"' % realm.replace('"', "'")) if realm else ''
|
||||
self.SetHeader('WWW-Authenticate', wwwAuth)
|
||||
self.Return(401)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnForbidden(self) :
|
||||
self.Return(403)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnNotFound(self) :
|
||||
if self._mws2._notFoundURL :
|
||||
self.ReturnRedirect(self._mws2._notFoundURL)
|
||||
else :
|
||||
self.Return(404)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnMethodNotAllowed(self) :
|
||||
self.Return(405)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnEntityTooLarge(self) :
|
||||
self.Return(413)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnInternalServerError(self) :
|
||||
self.Return(500)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnNotImplemented(self) :
|
||||
self.Return(501)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnServiceUnavailable(self) :
|
||||
self.Return(503)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnBasicAuthRequired(self) :
|
||||
self.ReturnUnauthorized('Basic')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnBearerAuthRequired(self) :
|
||||
self.ReturnUnauthorized('Bearer')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Request(self) :
|
||||
return self._request
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def UserAddress(self) :
|
||||
return self._xasCli.CliAddr
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsSSL(self) :
|
||||
return self._xasCli.IsSSL
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def AllowCaching(self) :
|
||||
return self._allowCaching
|
||||
|
||||
@AllowCaching.setter
|
||||
def AllowCaching(self, value) :
|
||||
if not isinstance(value, bool) :
|
||||
raise ValueError('"AllowCaching" must be a boolean.')
|
||||
self._allowCaching = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def AccessControlAllowOrigin(self) :
|
||||
return self._acAllowOrigin
|
||||
|
||||
@AccessControlAllowOrigin.setter
|
||||
def AccessControlAllowOrigin(self, value) :
|
||||
if value is not None and not isinstance(value, str) :
|
||||
raise ValueError('"AccessControlAllowOrigin" must be a string or None.')
|
||||
self._acAllowOrigin = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ContentType(self) :
|
||||
return self._contentType
|
||||
|
||||
@ContentType.setter
|
||||
def ContentType(self, value) :
|
||||
if value is not None and not isinstance(value, str) :
|
||||
raise ValueError('"ContentType" must be a string or None.')
|
||||
self._contentType = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ContentCharset(self) :
|
||||
return self._contentCharset
|
||||
|
||||
@ContentCharset.setter
|
||||
def ContentCharset(self, value) :
|
||||
if value is not None and not isinstance(value, str) :
|
||||
raise ValueError('"ContentCharset" must be a string or None.')
|
||||
self._contentCharset = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ContentLength(self) :
|
||||
return self._contentLength
|
||||
|
||||
@ContentLength.setter
|
||||
def ContentLength(self, value) :
|
||||
if not isinstance(value, int) or value < 0 :
|
||||
raise ValueError('"ContentLength" must be a positive integer or zero.')
|
||||
self._contentLength = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def HeadersSent(self) :
|
||||
return self._hdrSent
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnSent(self) :
|
||||
return self._onSent
|
||||
|
||||
@OnSent.setter
|
||||
def OnSent(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnSent" must be a function.')
|
||||
self._onSent = value
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,218 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
class UrlUtils :
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def Quote(s, safe='/') :
|
||||
r = ''
|
||||
for c in str(s) :
|
||||
if (c >= 'a' and c <= 'z') or \
|
||||
(c >= '0' and c <= '9') or \
|
||||
(c >= 'A' and c <= 'Z') or \
|
||||
(c in '.-_') or (c in safe) :
|
||||
r += c
|
||||
else :
|
||||
for b in c.encode('UTF-8') :
|
||||
r += '%%%02X' % b
|
||||
return r
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def UrlEncode(s) :
|
||||
return UrlUtils.Quote(s, ';/?:@&=+$,')
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def Unquote(s) :
|
||||
r = str(s).split('%')
|
||||
try :
|
||||
b = r[0].encode()
|
||||
for i in range(1, len(r)) :
|
||||
try :
|
||||
b += bytes([int(r[i][:2], 16)]) + r[i][2:].encode()
|
||||
except :
|
||||
b += b'%' + r[i].encode()
|
||||
return b.decode('UTF-8')
|
||||
except :
|
||||
return str(s)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def UnquotePlus(s) :
|
||||
return UrlUtils.Unquote(str(s).replace('+', ' '))
|
||||
|
||||
# ============================================================================
|
||||
# ===( Class Url )============================================================
|
||||
# ============================================================================
|
||||
|
||||
class Url :
|
||||
|
||||
def __init__(self, url='') :
|
||||
self.URL = url
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __repr__(self) :
|
||||
return self.URL if self.URL is not None else ''
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def IsHttps(self) :
|
||||
return (self._proto == 'https')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def URL(self) :
|
||||
host = self.Host
|
||||
if host != '' :
|
||||
proto = self.Proto
|
||||
port = self.Port
|
||||
if ( proto == 'http' and port == 80 ) or \
|
||||
( proto == 'https' and port == 443 ) :
|
||||
port = ''
|
||||
else :
|
||||
port = ':' + str(port)
|
||||
url = proto + '://' + host + port + self.Path
|
||||
url = UrlUtils.UrlEncode(url)
|
||||
qs = self.QueryString
|
||||
if qs != '' :
|
||||
return url + '?' + qs
|
||||
return url
|
||||
return None
|
||||
|
||||
@URL.setter
|
||||
def URL(self, value) :
|
||||
try :
|
||||
s = str(value)
|
||||
if '://' in s :
|
||||
proto, s = s.split('://', 1)
|
||||
else :
|
||||
proto = 'http'
|
||||
except :
|
||||
raise ValueError('URL error (%s)' % value)
|
||||
self.Proto = proto
|
||||
if '/' in s :
|
||||
host, path = s.split('/', 1)
|
||||
elif '?' in s :
|
||||
host, path = s.split('?', 1)
|
||||
path = '?' + path
|
||||
else :
|
||||
host = s
|
||||
path = ''
|
||||
if ':' in host :
|
||||
try :
|
||||
host, port = host.split(':')
|
||||
self.Port = port
|
||||
except :
|
||||
raise ValueError('URL host:port error (%s)' % host)
|
||||
self.Host = host
|
||||
self._queryParams = { }
|
||||
self.Path = path
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Proto(self) :
|
||||
return self._proto
|
||||
|
||||
@Proto.setter
|
||||
def Proto(self, value) :
|
||||
value = str(value).lower()
|
||||
if value == 'http' :
|
||||
self._port = 80
|
||||
elif value == 'https' :
|
||||
self._port = 443
|
||||
else :
|
||||
raise ValueError('Unsupported URL protocol (%s)' % value)
|
||||
self._proto = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Host(self) :
|
||||
return self._host
|
||||
|
||||
@Host.setter
|
||||
def Host(self, value) :
|
||||
self._host = UrlUtils.UnquotePlus(value)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Port(self) :
|
||||
return self._port
|
||||
|
||||
@Port.setter
|
||||
def Port(self, value) :
|
||||
try :
|
||||
p = int(value)
|
||||
except :
|
||||
raise ValueError('Port must be an integer value')
|
||||
if p <= 0 or p >= 65536 :
|
||||
raise ValueError('Port must be greater than 0 and less than 65536')
|
||||
self._port = p
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Path(self) :
|
||||
return self._path
|
||||
|
||||
@Path.setter
|
||||
def Path(self, value) :
|
||||
x = value.split('?', 1)
|
||||
if len(x[0]) > 0 :
|
||||
if x[0][0] != '/' :
|
||||
x[0] = '/' + x[0]
|
||||
self._path = UrlUtils.UnquotePlus(x[0])
|
||||
else :
|
||||
self._path = '/'
|
||||
if len(x) == 2 :
|
||||
self.QueryString = x[1]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def QueryString(self) :
|
||||
r = ''
|
||||
for param in self._queryParams :
|
||||
if param != '' :
|
||||
if r != '' :
|
||||
r += '&'
|
||||
r += UrlUtils.Quote(param) + '=' + UrlUtils.Quote(self._queryParams[param])
|
||||
return r
|
||||
|
||||
@QueryString.setter
|
||||
def QueryString(self, value) :
|
||||
self._queryParams = { }
|
||||
for x in value.split('&') :
|
||||
param = x.split('=', 1)
|
||||
if param[0] != '' :
|
||||
value = UrlUtils.Unquote(param[1]) if len(param) > 1 else ''
|
||||
self._queryParams[UrlUtils.Unquote(param[0])] = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def QueryParams(self) :
|
||||
return self._queryParams
|
||||
|
||||
@QueryParams.setter
|
||||
def QueryParams(self, value) :
|
||||
if not isinstance(value, dict) :
|
||||
raise ValueError('QueryParams must be a dict')
|
||||
self._queryParams = value
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,544 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from . import *
|
||||
from .httpRequest import HttpRequest
|
||||
from os import stat
|
||||
from sys import implementation
|
||||
from _thread import stack_size
|
||||
|
||||
# ============================================================================
|
||||
# ===( MicroWebSrv2 )=========================================================
|
||||
# ============================================================================
|
||||
|
||||
class MicroWebSrv2Exception(Exception) :
|
||||
pass
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
class MicroWebSrv2 :
|
||||
|
||||
_DEFAULT_PAGES = [
|
||||
"index.html",
|
||||
"index.htm",
|
||||
"default.html",
|
||||
"default.htm"
|
||||
]
|
||||
|
||||
_MIME_TYPES = {
|
||||
".txt" : "text/plain",
|
||||
".htm" : "text/html",
|
||||
".html" : "text/html",
|
||||
".css" : "text/css",
|
||||
".csv" : "text/csv",
|
||||
".js" : "application/javascript",
|
||||
".xml" : "application/xml",
|
||||
".xhtml" : "application/xhtml+xml",
|
||||
".json" : "application/json",
|
||||
".zip" : "application/zip",
|
||||
".pdf" : "application/pdf",
|
||||
".ts" : "application/typescript",
|
||||
".woff" : "font/woff",
|
||||
".woff2" : "font/woff2",
|
||||
".ttf" : "font/ttf",
|
||||
".otf" : "font/otf",
|
||||
".jpg" : "image/jpeg",
|
||||
".jpeg" : "image/jpeg",
|
||||
".png" : "image/png",
|
||||
".gif" : "image/gif",
|
||||
".svg" : "image/svg+xml",
|
||||
".ico" : "image/x-icon"
|
||||
}
|
||||
|
||||
_HTML_ESCAPE_CHARS = {
|
||||
"&" : "&",
|
||||
'"' : """,
|
||||
"'" : "'",
|
||||
">" : ">",
|
||||
"<" : "<"
|
||||
}
|
||||
|
||||
_STAT_MODE_DIR = 1 << 14
|
||||
|
||||
DEBUG = 0x00
|
||||
INFO = 0x01
|
||||
WARNING = 0x02
|
||||
ERROR = 0x03
|
||||
MSG_TYPE_STR = {
|
||||
DEBUG : 'DEBUG',
|
||||
INFO : 'INFO',
|
||||
WARNING : 'WARNING',
|
||||
ERROR : 'ERROR'
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
_modules = { }
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self) :
|
||||
self._backlog = None
|
||||
self._slotsCount = None
|
||||
self._slotsSize = None
|
||||
self._keepAlloc = None
|
||||
self._maxContentLen = None
|
||||
self._bindAddr = ('0.0.0.0', 80)
|
||||
self._sslContext = None
|
||||
self._rootPath = 'www'
|
||||
self._timeoutSec = 2
|
||||
self._notFoundURL = None
|
||||
self._allowAllOrigins = False
|
||||
self._corsAllowAll = False
|
||||
self._onLogging = None
|
||||
self._xasSrv = None
|
||||
self._xasPool = None
|
||||
self.SetNormalConfig()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _physPathExists(physPath) :
|
||||
try :
|
||||
stat(physPath)
|
||||
return True
|
||||
except :
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _physPathIsDir(physPath) :
|
||||
return (stat(physPath)[0] & MicroWebSrv2._STAT_MODE_DIR != 0)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def LoadModule(modName) :
|
||||
if not isinstance(modName, str) or len(modName) == 0 :
|
||||
raise ValueError('"modName" must be a not empty string.')
|
||||
if modName in MicroWebSrv2._modules :
|
||||
raise MicroWebSrv2Exception('Module "%s" is already loaded.' % modName)
|
||||
try :
|
||||
modPath = MicroWebSrv2.__module__.split('microWebSrv2')[0] \
|
||||
+ ('mods.%s' % modName)
|
||||
print('loadmod',modPath)
|
||||
module = getattr(__import__(modPath).mods, modName)
|
||||
modClass = getattr(module, modName)
|
||||
if type(modClass) is not type :
|
||||
raise Exception
|
||||
modInstance = modClass()
|
||||
MicroWebSrv2._modules[modName] = modInstance
|
||||
return modInstance
|
||||
except :
|
||||
raise MicroWebSrv2Exception('Cannot load module "%s".' % modName)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def HTMLEscape(s) :
|
||||
if not isinstance(s, str) :
|
||||
raise ValueError('"s" must be a string.')
|
||||
return ''.join(MicroWebSrv2._HTML_ESCAPE_CHARS.get(c, c) for c in s)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def AddDefaultPage(filename) :
|
||||
if not isinstance(filename, str) or len(filename) == 0 :
|
||||
raise ValueError('"filename" must be a not empty string.')
|
||||
MicroWebSrv2._DEFAULT_PAGES.append(filename)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def AddMimeType(ext, mimeType) :
|
||||
if not isinstance(ext, str) or len(ext) == 0 :
|
||||
raise ValueError('"ext" must be a not empty string.')
|
||||
if not isinstance(mimeType, str) or len(mimeType) == 0 :
|
||||
raise ValueError('"mimeType" must be a not empty string.')
|
||||
MicroWebSrv2._MIME_TYPES[ext.lower()] = mimeType.lower()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def GetMimeTypeFromFilename(filename) :
|
||||
filename = filename.lower()
|
||||
for ext in MicroWebSrv2._MIME_TYPES :
|
||||
if filename.endswith(ext) :
|
||||
return MicroWebSrv2._MIME_TYPES[ext]
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def StartInPool(self, asyncSocketsPool) :
|
||||
if not isinstance(asyncSocketsPool, XAsyncSocketsPool) :
|
||||
raise ValueError('"asyncSocketsPool" must be a XAsyncSocketsPool class.')
|
||||
if self._xasSrv :
|
||||
raise MicroWebSrv2Exception('Server is already running.')
|
||||
try :
|
||||
xBufSlots = XBufferSlots( slotsCount = self._slotsCount,
|
||||
slotsSize = self._slotsSize,
|
||||
keepAlloc = self._keepAlloc )
|
||||
except :
|
||||
raise MicroWebSrv2Exception('Not enough memory to allocate slots.')
|
||||
try :
|
||||
self._xasSrv = XAsyncTCPServer.Create( asyncSocketsPool = asyncSocketsPool,
|
||||
srvAddr = self._bindAddr,
|
||||
srvBacklog = self._backlog,
|
||||
bufSlots = xBufSlots )
|
||||
except :
|
||||
raise MicroWebSrv2Exception('Cannot bind server on %s:%s.' % self._bindAddr)
|
||||
self._xasSrv.OnClientAccepted = self._onSrvClientAccepted
|
||||
self._xasSrv.OnClosed = self._onSrvClosed
|
||||
self.Log('Server listening on %s:%s.' % self._bindAddr, MicroWebSrv2.INFO)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def StartManaged(self, parllProcCount=1, procStackSize=0) :
|
||||
if not isinstance(parllProcCount, int) or parllProcCount < 0 :
|
||||
raise ValueError('"parllProcCount" must be a positive integer or zero.')
|
||||
if not isinstance(procStackSize, int) or procStackSize < 0 :
|
||||
raise ValueError('"procStackSize" must be a positive integer or zero.')
|
||||
if self._xasSrv :
|
||||
raise MicroWebSrv2Exception('Server is already running.')
|
||||
if procStackSize == 0 and implementation.name == 'micropython' :
|
||||
procStackSize = 8*1024
|
||||
try :
|
||||
saveStackSize = stack_size(procStackSize)
|
||||
except Exception as ex :
|
||||
raise ValueError('"procStackSize" of %s is not correct (%s).' % (procStackSize, ex))
|
||||
self._xasPool = XAsyncSocketsPool()
|
||||
try :
|
||||
self.StartInPool(self._xasPool)
|
||||
try :
|
||||
self.Log('Starts the managed pool to wait for I/O events.', MicroWebSrv2.INFO)
|
||||
self._xasPool.AsyncWaitEvents(threadsCount=parllProcCount)
|
||||
except :
|
||||
raise MicroWebSrv2Exception('Not enough memory to start %s parallel processes.' % parllProcCount)
|
||||
except Exception as ex :
|
||||
self.Stop()
|
||||
raise ex
|
||||
finally :
|
||||
try :
|
||||
stack_size(saveStackSize)
|
||||
except :
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def Stop(self) :
|
||||
if self._xasSrv :
|
||||
self._xasSrv.Close()
|
||||
self._xasSrv = None
|
||||
if self._xasPool :
|
||||
self.Log('Stops the managed pool.', MicroWebSrv2.INFO)
|
||||
self._xasPool.StopWaitEvents()
|
||||
self._xasPool = None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def Log(self, msg, msgType) :
|
||||
if self._onLogging :
|
||||
try :
|
||||
self._onLogging(self, str(msg), msgType)
|
||||
return
|
||||
except Exception as ex :
|
||||
msgType = MicroWebSrv2.ERROR
|
||||
msg = 'Exception raised from "OnLoggin" handler: %s' % ex
|
||||
t = MicroWebSrv2.MSG_TYPE_STR.get(msgType, None)
|
||||
if t :
|
||||
print('MWS2-%s> %s' % (t, msg))
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ResolvePhysicalPath(self, urlPath) :
|
||||
if not isinstance(urlPath, str) or len(urlPath) == 0 :
|
||||
raise ValueError('"urlPath" must be a not empty string.')
|
||||
try :
|
||||
physPath = self._rootPath + urlPath.replace('..', '/')
|
||||
if physPath.endswith('/') :
|
||||
physPath = physPath[:-1]
|
||||
if MicroWebSrv2._physPathIsDir(physPath) :
|
||||
for filename in MicroWebSrv2._DEFAULT_PAGES :
|
||||
p = physPath + '/' + filename
|
||||
if MicroWebSrv2._physPathExists(p) :
|
||||
return p
|
||||
return physPath
|
||||
except :
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onSrvClientAccepted(self, xAsyncTCPServer, xAsyncTCPClient) :
|
||||
if self._sslContext :
|
||||
try :
|
||||
xAsyncTCPClient.StartSSLContext( sslContext = self._sslContext,
|
||||
serverSide = True )
|
||||
except :
|
||||
self.Log( 'SSL connection failed from %s:%s.'
|
||||
% xAsyncTCPClient.CliAddr,
|
||||
MicroWebSrv2.DEBUG )
|
||||
xAsyncTCPClient.Close()
|
||||
return
|
||||
HttpRequest(self, xAsyncTCPClient)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onSrvClosed(self, xAsyncTCPServer, closedReason) :
|
||||
self.Log('Server %s:%s closed.' % self._bindAddr, MicroWebSrv2.INFO)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _validateChangeConf(self, name='Configuration') :
|
||||
if self._xasSrv :
|
||||
raise MicroWebSrv2Exception('%s cannot be changed while the server is running.' % name)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def EnableSSL(self, certFile, keyFile, caFile=None) :
|
||||
import ssl
|
||||
if not hasattr(ssl, 'SSLContext') :
|
||||
raise MicroWebSrv2Exception('Unable to use SSL (implementation not supported).')
|
||||
if not isinstance(certFile, str) or len(certFile) == 0 :
|
||||
raise ValueError('"certFile" must be a not empty string.')
|
||||
if not isinstance(keyFile, str) or len(keyFile) == 0 :
|
||||
raise ValueError('"keyFile" must be a not empty string.')
|
||||
if caFile is not None and not isinstance(caFile, str) :
|
||||
raise ValueError('"caFile" must be a string or None.')
|
||||
self._validateChangeConf()
|
||||
try :
|
||||
ctx = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH,
|
||||
cafile = caFile )
|
||||
except :
|
||||
raise ValueError('"caFile" must indicate a valid PEM file.')
|
||||
try :
|
||||
ctx.load_cert_chain(certfile=certFile, keyfile=keyFile)
|
||||
except :
|
||||
raise ValueError('"certFile" and "keyFile" must indicate the valid certificate and key files.')
|
||||
self._sslContext = ctx
|
||||
if self._bindAddr[1] == 80 :
|
||||
self._bindAddr = (self._bindAddr[0], 443)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def DisableSSL(self) :
|
||||
self._validateChangeConf()
|
||||
self._sslContext = None
|
||||
if self._bindAddr[1] == 443 :
|
||||
self._bindAddr = (self._bindAddr[0], 80)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetEmbeddedConfig(self) :
|
||||
self._validateChangeConf()
|
||||
self._backlog = 8
|
||||
self._slotsCount = 16
|
||||
self._slotsSize = 1024
|
||||
self._keepAlloc = True
|
||||
self._maxContentLen = 16*1024
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetLightConfig(self) :
|
||||
self._validateChangeConf()
|
||||
self._backlog = 64
|
||||
self._slotsCount = 128
|
||||
self._slotsSize = 1024
|
||||
self._keepAlloc = True
|
||||
self._maxContentLen = 512*1024
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetNormalConfig(self) :
|
||||
self._validateChangeConf()
|
||||
self._backlog = 256
|
||||
self._slotsCount = 512
|
||||
self._slotsSize = 4*1024
|
||||
self._keepAlloc = True
|
||||
self._maxContentLen = 2*1024*1024
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetLargeConfig(self) :
|
||||
self._validateChangeConf()
|
||||
self._backlog = 512
|
||||
self._slotsCount = 2048
|
||||
self._slotsSize = 16*1024
|
||||
self._keepAlloc = True
|
||||
self._maxContentLen = 8*1024*1024
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsRunning(self) :
|
||||
return ( self._xasPool is not None and \
|
||||
self._xasPool.WaitEventsProcessing and \
|
||||
self._xasSrv is not None )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ConnQueueCapacity(self) :
|
||||
return self._backlog
|
||||
|
||||
@ConnQueueCapacity.setter
|
||||
def ConnQueueCapacity(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"ConnQueueCapacity" must be a positive integer.')
|
||||
self._validateChangeConf('"ConnQueueCapacity"')
|
||||
self._backlog = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def BufferSlotsCount(self) :
|
||||
return self._slotsCount
|
||||
|
||||
@BufferSlotsCount.setter
|
||||
def BufferSlotsCount(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"BufferSlotsCount" must be a positive integer.')
|
||||
self._validateChangeConf('"BufferSlotsCount"')
|
||||
self._slotsCount = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def BufferSlotSize(self) :
|
||||
return self._slotsSize
|
||||
|
||||
@BufferSlotSize.setter
|
||||
def BufferSlotSize(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"BufferSlotSize" must be a positive integer.')
|
||||
self._validateChangeConf('"BufferSlotSize"')
|
||||
self._slotsSize = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def KeepAllocBufferSlots(self) :
|
||||
return self._keepAlloc
|
||||
|
||||
@KeepAllocBufferSlots.setter
|
||||
def KeepAllocBufferSlots(self, value) :
|
||||
if not isinstance(value, bool) :
|
||||
raise ValueError('"KeepAllocBufferSlots" must be a boolean.')
|
||||
self._validateChangeConf('"KeepAllocBufferSlots"')
|
||||
self._keepAlloc = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def MaxRequestContentLength(self) :
|
||||
return self._maxContentLen
|
||||
|
||||
@MaxRequestContentLength.setter
|
||||
def MaxRequestContentLength(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"MaxRequestContentLength" must be a positive integer.')
|
||||
self._maxContentLen = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def BindAddress(self) :
|
||||
return self._bindAddr
|
||||
|
||||
@BindAddress.setter
|
||||
def BindAddress(self, value) :
|
||||
if not value or len(value) != 2 or \
|
||||
not isinstance(value[0], str) or \
|
||||
not isinstance(value[1], int) :
|
||||
raise ValueError('"BindAddress" must be a tuple of (ipAddr, tcpPort).')
|
||||
if value[1] < 1 or value[1] > 65535 :
|
||||
raise ValueError('"BindAddress" has an incorrect port number.')
|
||||
self._validateChangeConf('"BindAddress"')
|
||||
self._bindAddr = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsSSLEnabled(self) :
|
||||
return (self._sslContext is not None)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def RootPath(self) :
|
||||
return self._rootPath
|
||||
|
||||
@RootPath.setter
|
||||
def RootPath(self, value) :
|
||||
if not isinstance(value, str) or len(value) == 0 :
|
||||
raise ValueError('"RootPath" must be a not empty string.')
|
||||
self._validateChangeConf('"RootPath"')
|
||||
self._rootPath = (value[:-1] if value.endswith('/') else value)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def RequestsTimeoutSec(self) :
|
||||
return self._timeoutSec
|
||||
|
||||
@RequestsTimeoutSec.setter
|
||||
def RequestsTimeoutSec(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"RequestsTimeoutSec" must be a positive integer.')
|
||||
self._timeoutSec = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def NotFoundURL(self) :
|
||||
return self._notFoundURL
|
||||
|
||||
@NotFoundURL.setter
|
||||
def NotFoundURL(self, value) :
|
||||
if value is not None and not isinstance(value, str) :
|
||||
raise ValueError('"NotFoundURL" must be a string or None.')
|
||||
self._notFoundURL = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def AllowAllOrigins(self) :
|
||||
return self._allowAllOrigins
|
||||
|
||||
@AllowAllOrigins.setter
|
||||
def AllowAllOrigins(self, value) :
|
||||
if not isinstance(value, bool) :
|
||||
raise ValueError('"AllowAllOrigins" must be a boolean.')
|
||||
self._allowAllOrigins = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def CORSAllowAll(self) :
|
||||
return self._corsAllowAll
|
||||
|
||||
@CORSAllowAll.setter
|
||||
def CORSAllowAll(self, value) :
|
||||
if not isinstance(value, bool) :
|
||||
raise ValueError('"CORSAllowAll" must be a boolean.')
|
||||
self._corsAllowAll = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnLogging(self) :
|
||||
return self._onLogging
|
||||
|
||||
@OnLogging.setter
|
||||
def OnLogging(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnLogging" must be a function.')
|
||||
self._onLogging = value
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,394 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from os import stat
|
||||
import re
|
||||
|
||||
# ============================================================================
|
||||
# ===( MicroWebSrv2 : PyhtmlTemplate Module )=================================
|
||||
# ============================================================================
|
||||
|
||||
class PyhtmlTemplate :
|
||||
|
||||
_CODE_CONTENT_DEBUG = """\
|
||||
<html>
|
||||
<head>
|
||||
<title>MicroWebSrv2</title>
|
||||
</head>
|
||||
<body style="font-family: Verdana; background-color: Black; color: White;">
|
||||
<h2>MicroWebSrv2 - [500] Internal Server Error</h2>
|
||||
<div style="margin: 20px;">
|
||||
<h3>PyhtmlTemplate Module Debug</h3>
|
||||
<div style="padding: 15px; background-color: Crimson;">
|
||||
Exception in %(path)s<br />
|
||||
%(message)s
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self) :
|
||||
self._showDebug = False
|
||||
self._pyGlobalVars = { }
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def OnRequest(self, microWebSrv2, request) :
|
||||
if (request.Method == 'GET' or request.Method == 'HEAD') and \
|
||||
request.Path.lower().endswith('.pyhtml') :
|
||||
filepath = microWebSrv2.ResolvePhysicalPath(request.Path)
|
||||
self.ReturnTemplate(microWebSrv2, request, filepath)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnTemplate(self, microWebSrv2, request, filepath):
|
||||
if not filepath:
|
||||
request.Response.ReturnNotFound()
|
||||
return
|
||||
|
||||
try :
|
||||
with open(filepath, 'r') as file :
|
||||
code = file.read()
|
||||
except :
|
||||
request.Response.ReturnForbidden()
|
||||
return
|
||||
|
||||
try :
|
||||
self._pyGlobalVars['Request'] = request
|
||||
codeTemplate = CodeTemplate(code, microWebSrv2.HTMLEscape)
|
||||
content = codeTemplate.Execute(self._pyGlobalVars, None)
|
||||
request.Response.ReturnOk(content)
|
||||
|
||||
except Exception as ex :
|
||||
microWebSrv2.Log( 'Exception raised from pyhtml template file "%s": %s' % (filepath, ex),
|
||||
microWebSrv2.ERROR )
|
||||
if self._showDebug :
|
||||
request.Response.Return( 500,
|
||||
PyhtmlTemplate._CODE_CONTENT_DEBUG
|
||||
% { 'path' : filepath,
|
||||
'message' : ex } )
|
||||
else :
|
||||
request.Response.ReturnInternalServerError()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetGlobalVar(self, globalVarName, globalVar) :
|
||||
if not isinstance(globalVarName, str) or len(globalVarName) == 0 :
|
||||
raise ValueError('"globalVarName" must be a not empty string.')
|
||||
self._pyGlobalVars[globalVarName] = globalVar
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetGlobalVar(self, globalVarName) :
|
||||
if not isinstance(globalVarName, str) or len(globalVarName) == 0 :
|
||||
raise ValueError('"globalVarName" must be a not empty string.')
|
||||
try :
|
||||
return self._pyGlobalVars[globalVarName]
|
||||
except :
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ShowDebug(self) :
|
||||
return self._showDebug
|
||||
|
||||
@ShowDebug.setter
|
||||
def ShowDebug(self, value) :
|
||||
if not isinstance(value, bool) :
|
||||
raise ValueError('"ShowDebug" must be a boolean.')
|
||||
self._showDebug = value
|
||||
|
||||
# ============================================================================
|
||||
# ===( CodeTemplate )=========================================================
|
||||
# ============================================================================
|
||||
|
||||
class CodeTemplateException(Exception) :
|
||||
pass
|
||||
|
||||
class CodeTemplate :
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
TOKEN_OPEN = '{{'
|
||||
TOKEN_CLOSE = '}}'
|
||||
TOKEN_OPEN_LEN = len(TOKEN_OPEN)
|
||||
TOKEN_CLOSE_LEN = len(TOKEN_CLOSE)
|
||||
|
||||
INSTRUCTION_PYTHON = 'py'
|
||||
INSTRUCTION_IF = 'if'
|
||||
INSTRUCTION_ELIF = 'elif'
|
||||
INSTRUCTION_ELSE = 'else'
|
||||
INSTRUCTION_FOR = 'for'
|
||||
INSTRUCTION_END = 'end'
|
||||
|
||||
RE_IDENTIFIER = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, code, escapeStrFunc=None) :
|
||||
self._code = code
|
||||
self._escapeStrFunc = escapeStrFunc
|
||||
self._pos = 0
|
||||
self._endPos = len(code)-1
|
||||
self._line = 1
|
||||
self._pyGlobalVars = { }
|
||||
self._pyLocalVars = { }
|
||||
self._rendered = ''
|
||||
self._instructions = {
|
||||
CodeTemplate.INSTRUCTION_PYTHON : self._processInstructionPYTHON,
|
||||
CodeTemplate.INSTRUCTION_IF : self._processInstructionIF,
|
||||
CodeTemplate.INSTRUCTION_ELIF : self._processInstructionELIF,
|
||||
CodeTemplate.INSTRUCTION_ELSE : self._processInstructionELSE,
|
||||
CodeTemplate.INSTRUCTION_FOR : self._processInstructionFOR,
|
||||
CodeTemplate.INSTRUCTION_END : self._processInstructionEND
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def Validate(self, pyGlobalVars=None, pyLocalVars=None) :
|
||||
try :
|
||||
self._parseCode(pyGlobalVars, pyLocalVars, execute=False)
|
||||
return None
|
||||
except Exception as ex :
|
||||
return str(ex)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def Execute(self, pyGlobalVars=None, pyLocalVars=None) :
|
||||
try :
|
||||
self._parseCode(pyGlobalVars, pyLocalVars, execute=True)
|
||||
return self._rendered
|
||||
except Exception as ex :
|
||||
raise CodeTemplateException(str(ex))
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _parseCode(self, pyGlobalVars, pyLocalVars, execute) :
|
||||
self._pos = 0
|
||||
self._line = 1
|
||||
self._pyGlobalVars = (pyGlobalVars if isinstance(pyGlobalVars, dict) else { })
|
||||
self._pyLocalVars = (pyLocalVars if isinstance(pyLocalVars, dict) else { })
|
||||
self._rendered = ''
|
||||
self._pyGlobalVars['print'] = self._renderingPrint
|
||||
newTokenToProcess = self._parseBloc(execute)
|
||||
if newTokenToProcess is not None :
|
||||
raise CodeTemplateException( '"%s" instruction is not valid here (line %s)'
|
||||
% (newTokenToProcess, self._line) )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _parseBloc(self, execute) :
|
||||
while True :
|
||||
idx = self._code.find(CodeTemplate.TOKEN_OPEN, self._pos)
|
||||
end = (idx < 0)
|
||||
if end :
|
||||
idx = self._endPos+1
|
||||
code = self._code[self._pos:idx]
|
||||
self._line += code.count('\n')
|
||||
if execute :
|
||||
self._rendered += code
|
||||
if end :
|
||||
self._pos = idx
|
||||
return None
|
||||
self._pos = idx + CodeTemplate.TOKEN_OPEN_LEN
|
||||
idx = self._code.find(CodeTemplate.TOKEN_CLOSE, self._pos)
|
||||
if idx < 0 :
|
||||
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_CLOSE)
|
||||
tokenContent = self._code[self._pos:idx].strip()
|
||||
self._line += tokenContent.count('\n')
|
||||
self._pos = idx + CodeTemplate.TOKEN_CLOSE_LEN
|
||||
newTokenToProcess = self._processToken(tokenContent, execute)
|
||||
if newTokenToProcess is not None :
|
||||
return newTokenToProcess
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _renderingPrint(self, s) :
|
||||
self._rendered += str(s)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processToken(self, tokenContent, execute) :
|
||||
parts = tokenContent.split(' ', 1)
|
||||
instructName = parts[0].strip()
|
||||
instructBody = parts[1].strip() if len(parts) > 1 else None
|
||||
if len(instructName) == 0 :
|
||||
raise CodeTemplateException( '"%s %s" : instruction is missing (line %s)'
|
||||
% (CodeTemplate.TOKEN_OPEN, CodeTemplate.TOKEN_CLOSE, self._line) )
|
||||
newTokenToProcess = None
|
||||
if instructName in self._instructions :
|
||||
newTokenToProcess = self._instructions[instructName](instructBody, execute)
|
||||
elif execute :
|
||||
try :
|
||||
ret = eval( tokenContent,
|
||||
self._pyGlobalVars,
|
||||
self._pyLocalVars )
|
||||
if ret is not None :
|
||||
if (self._escapeStrFunc is not None) :
|
||||
self._rendered += self._escapeStrFunc(str(ret))
|
||||
else :
|
||||
self._rendered += str(ret)
|
||||
except Exception as ex :
|
||||
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
|
||||
return newTokenToProcess
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionPYTHON(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_PYTHON, self._line) )
|
||||
idx = self._code.find(CodeTemplate.TOKEN_OPEN, self._pos)
|
||||
if idx < 0 :
|
||||
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_OPEN)
|
||||
pyCode = self._code[self._pos:idx]
|
||||
self._line += pyCode.count('\n')
|
||||
self._pos = idx + CodeTemplate.TOKEN_OPEN_LEN
|
||||
idx = self._code.find(CodeTemplate.TOKEN_CLOSE, self._pos)
|
||||
if idx < 0 :
|
||||
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_CLOSE)
|
||||
tokenContent = self._code[self._pos:idx].strip()
|
||||
self._line += tokenContent.count('\n')
|
||||
self._pos = idx + CodeTemplate.TOKEN_CLOSE_LEN
|
||||
if tokenContent != CodeTemplate.INSTRUCTION_END :
|
||||
raise CodeTemplateException( '"%s" is a bad instruction in a python bloc (line %s)'
|
||||
% (tokenContent, self._line) )
|
||||
if execute :
|
||||
lines = pyCode.split('\n')
|
||||
indent = ''
|
||||
for line in lines :
|
||||
if len(line.strip()) > 0 :
|
||||
for c in line :
|
||||
if c == ' ' or c == '\t' :
|
||||
indent += c
|
||||
else :
|
||||
break
|
||||
break
|
||||
indentLen = len(indent)
|
||||
for i in range(len(lines)) :
|
||||
if lines[i].startswith(indent) :
|
||||
lines[i] = lines[i][indentLen:] + '\n'
|
||||
else :
|
||||
lines[i] += '\n'
|
||||
pyCode = ''.join(lines)
|
||||
try :
|
||||
exec(pyCode, self._pyGlobalVars, self._pyLocalVars)
|
||||
except Exception as ex :
|
||||
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionIF(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
if execute :
|
||||
try :
|
||||
if (' ' not in instructionBody) and \
|
||||
('=' not in instructionBody) and \
|
||||
('<' not in instructionBody) and \
|
||||
('>' not in instructionBody) and \
|
||||
(instructionBody not in self._pyGlobalVars) and \
|
||||
(instructionBody not in self._pyLocalVars):
|
||||
result = False
|
||||
else:
|
||||
result = bool(eval(instructionBody, self._pyGlobalVars, self._pyLocalVars))
|
||||
except Exception as ex :
|
||||
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
|
||||
else :
|
||||
result = False
|
||||
newTokenToProcess = self._parseBloc(execute and result)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
elif newTokenToProcess == CodeTemplate.INSTRUCTION_ELSE :
|
||||
newTokenToProcess = self._parseBloc(execute and not result)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
raise CodeTemplateException( '"%s" instruction waited (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
elif newTokenToProcess == CodeTemplate.INSTRUCTION_ELIF :
|
||||
self._processInstructionIF(self._elifInstructionBody, execute and not result)
|
||||
return None
|
||||
raise CodeTemplateException( '"%s" instruction waited (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_IF, self._line) )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionELIF(self, instructionBody, execute) :
|
||||
if instructionBody is None :
|
||||
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_ELIF, self._line) )
|
||||
self._elifInstructionBody = instructionBody
|
||||
return CodeTemplate.INSTRUCTION_ELIF
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionELSE(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_ELSE, self._line) )
|
||||
return CodeTemplate.INSTRUCTION_ELSE
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionFOR(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
parts = instructionBody.split(' ', 1)
|
||||
identifier = parts[0].strip()
|
||||
if CodeTemplate.RE_IDENTIFIER.match(identifier) is not None and len(parts) > 1 :
|
||||
parts = parts[1].strip().split(' ', 1)
|
||||
if parts[0] == 'in' and len(parts) > 1 :
|
||||
expression = parts[1].strip()
|
||||
newTokenToProcess = None
|
||||
beforePos = self._pos
|
||||
if execute :
|
||||
try :
|
||||
result = eval(expression, self._pyGlobalVars, self._pyLocalVars)
|
||||
except :
|
||||
raise CodeTemplateException('%s (line %s)' % (str(expression), self._line))
|
||||
if execute and len(result) > 0 :
|
||||
for x in result :
|
||||
self._pyLocalVars[identifier] = x
|
||||
self._pos = beforePos
|
||||
newTokenToProcess = self._parseBloc(True)
|
||||
if newTokenToProcess != CodeTemplate.INSTRUCTION_END :
|
||||
break
|
||||
else :
|
||||
newTokenToProcess = self._parseBloc(False)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
raise CodeTemplateException( '"%s" instruction waited (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
raise CodeTemplateException( '"%s %s" is an invalid syntax'
|
||||
% (CodeTemplate.INSTRUCTION_FOR, instructionBody) )
|
||||
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_FOR, self._line) )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionEND(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
return CodeTemplate.INSTRUCTION_END
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,477 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from hashlib import sha1
|
||||
from binascii import b2a_base64
|
||||
from struct import pack
|
||||
|
||||
# ============================================================================
|
||||
# ===( MicroWebSrv2 : WebSockets Module )=====================================
|
||||
# ============================================================================
|
||||
|
||||
class WebSockets :
|
||||
|
||||
_PROTOCOL_VERSION = 13
|
||||
_HANDSHAKE_SIGN = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self) :
|
||||
self._onWebSocketProtocol = None
|
||||
self._onWebSocketAccepted = None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def OnRequest(self, microWebSrv2, request) :
|
||||
if request.IsUpgrade and request.Upgrade.lower() == 'websocket' :
|
||||
ver = request.GetHeader('Sec-Websocket-Version')
|
||||
if ver == str(WebSockets._PROTOCOL_VERSION) :
|
||||
response = request.Response
|
||||
key = request.GetHeader('Sec-Websocket-Key')
|
||||
if key :
|
||||
try :
|
||||
key += WebSockets._HANDSHAKE_SIGN
|
||||
sec = sha1(key.encode()).digest()
|
||||
sec = b2a_base64(sec).decode().strip()
|
||||
protocols = request.GetHeader('Sec-WebSocket-Protocol')
|
||||
response.SetHeader('Sec-WebSocket-Accept', sec)
|
||||
if protocols and self._onWebSocketProtocol :
|
||||
protocols = [x.strip() for x in protocols.split(',')]
|
||||
try :
|
||||
proto = self._onWebSocketProtocol(microWebSrv2, protocols)
|
||||
except Exception as ex :
|
||||
microWebSrv2.Log( 'Exception raised from "WebSockets.OnWebSocketProtocol" handler: %s' % ex,
|
||||
microWebSrv2.ERROR )
|
||||
raise ex
|
||||
if proto in protocols :
|
||||
response.SetHeader('Sec-WebSocket-Protocol', proto)
|
||||
response.SwitchingProtocols('websocket')
|
||||
WebSocket(self, microWebSrv2, request)
|
||||
except :
|
||||
response.ReturnInternalServerError()
|
||||
else :
|
||||
response.ReturnBadRequest()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnWebSocketProtocol(self) :
|
||||
return self._onWebSocketProtocol
|
||||
|
||||
@OnWebSocketProtocol.setter
|
||||
def OnWebSocketProtocol(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnWebSocketProtocol" must be a function.')
|
||||
self._onWebSocketProtocol = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnWebSocketAccepted(self) :
|
||||
return self._onWebSocketAccepted
|
||||
|
||||
@OnWebSocketAccepted.setter
|
||||
def OnWebSocketAccepted(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnWebSocketAccepted" must be a function.')
|
||||
self._onWebSocketAccepted = value
|
||||
|
||||
# ============================================================================
|
||||
# ===( WebSocket )============================================================
|
||||
# ============================================================================
|
||||
|
||||
class WebSocket :
|
||||
|
||||
_OP_FRAME_CONT = 0x00
|
||||
_OP_FRAME_TEXT = 0x01
|
||||
_OP_FRAME_BIN = 0x02
|
||||
_OP_FRAME_CLOSE = 0x08
|
||||
_OP_FRAME_PING = 0x09
|
||||
_OP_FRAME_PONG = 0x0A
|
||||
|
||||
_MSG_TYPE_TEXT = 0x01
|
||||
_MSG_TYPE_BIN = 0x02
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, wsMod, mws2, request) :
|
||||
|
||||
self._mws2 = mws2
|
||||
self._request = request
|
||||
self._xasCli = request.XAsyncTCPClient
|
||||
self._currentMsgType = None
|
||||
self._currentMsgData = None
|
||||
self._isClosed = False
|
||||
self._waitFrameTimeoutSec = 300
|
||||
self._maxRecvMsgLen = mws2.MaxRequestContentLength
|
||||
self._onTextMsg = None
|
||||
self._onBinMsg = None
|
||||
self._onClosed = None
|
||||
|
||||
onWSAccepted = wsMod.OnWebSocketAccepted
|
||||
|
||||
self._mws2.Log( '%sWebSocket %s from %s:%s.'
|
||||
% ( ('SSL-' if request.IsSSL else ''),
|
||||
'accepted' if onWSAccepted else 'denied',
|
||||
self._xasCli.CliAddr[0],
|
||||
self._xasCli.CliAddr[1] ),
|
||||
self._mws2.INFO )
|
||||
|
||||
if not onWSAccepted :
|
||||
self._close(1001, 'Going away...')
|
||||
return
|
||||
|
||||
self._xasCli.OnClosed = self._onXAsCliClosed
|
||||
|
||||
try :
|
||||
onWSAccepted(self._mws2, self)
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from "WebSockets.OnWebSocketAccepted" handler: %s' % ex,
|
||||
self._mws2.ERROR )
|
||||
self._close(1011, 'Unexpected error')
|
||||
return
|
||||
|
||||
self._waitFrame()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _recvData(self, onRecv, size=None) :
|
||||
self._xasCli.AsyncRecvData( size = size,
|
||||
onDataRecv = onRecv,
|
||||
timeoutSec = self._mws2.RequestsTimeoutSec )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onXAsCliClosed(self, xasCli, closedReason) :
|
||||
self._isClosed = True
|
||||
if self._onClosed :
|
||||
try :
|
||||
self._onClosed(self)
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from "WebSocket.OnClosed" handler: %s' % ex,
|
||||
self._mws2.ERROR )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _waitFrame(self) :
|
||||
|
||||
def onHdrStartingRecv(xasCli, data, arg) :
|
||||
|
||||
fin = data[0] & 0x80 > 0
|
||||
opcode = data[0] & 0x0F
|
||||
masked = data[1] & 0x80 > 0
|
||||
length = data[1] & 0x7F
|
||||
|
||||
# Control frame ?
|
||||
isCtrlFrame = ( opcode != WebSocket._OP_FRAME_TEXT and \
|
||||
opcode != WebSocket._OP_FRAME_BIN and \
|
||||
opcode != WebSocket._OP_FRAME_CONT )
|
||||
|
||||
if ( isCtrlFrame and not fin ) \
|
||||
or \
|
||||
( opcode == WebSocket._OP_FRAME_CONT and \
|
||||
not self._currentMsgType ) \
|
||||
or \
|
||||
( self._currentMsgType and \
|
||||
( opcode == WebSocket._OP_FRAME_TEXT or \
|
||||
opcode == WebSocket._OP_FRAME_BIN ) ) :
|
||||
# Bad frame in the context,
|
||||
self._close(1002, 'Protocol error (bad frame in the context)')
|
||||
return
|
||||
|
||||
def endOfHeader(dataLen, maskingKey) :
|
||||
|
||||
def onPayloadDataRecv(xasCli, data, arg) :
|
||||
|
||||
if maskingKey :
|
||||
for i in range(dataLen) :
|
||||
data[i] ^= maskingKey[i%4]
|
||||
|
||||
if self._currentMsgData :
|
||||
try :
|
||||
self._currentMsgData += data
|
||||
except :
|
||||
# Frame is too large for memory allocation,
|
||||
self._close(1009, 'Frame is too large to be processed')
|
||||
return
|
||||
else :
|
||||
self._currentMsgData = data
|
||||
|
||||
if fin :
|
||||
# Frame is fully received,
|
||||
if self._currentMsgType == WebSocket._MSG_TYPE_TEXT :
|
||||
# Text frame,
|
||||
if self._onTextMsg :
|
||||
try :
|
||||
msg = bytes(self._currentMsgData).decode('UTF-8')
|
||||
try :
|
||||
self._onTextMsg(self, msg)
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from "WebSocket.OnTextMessage" handler: %s' % ex,
|
||||
self._mws2.ERROR )
|
||||
self._close(1011, 'Unexpected error while processing text message')
|
||||
return
|
||||
except :
|
||||
self._mws2.Log( 'Error during UTF-8 decoding of websocket text message.',
|
||||
self._mws2.WARNING )
|
||||
self._close(1007, 'Error to decode UTF-8 text message')
|
||||
return
|
||||
else :
|
||||
self._close(1003, 'Text messages are not implemented')
|
||||
return
|
||||
elif self._currentMsgType == WebSocket._MSG_TYPE_BIN :
|
||||
# Binary frame,
|
||||
if self._onBinMsg :
|
||||
try :
|
||||
self._onBinMsg(self, bytes(self._currentMsgData))
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from "WebSocket.OnBinaryMessage" handler: %s' % ex,
|
||||
self._mws2.ERROR )
|
||||
self._close(1011, 'Unexpected error while processing binary message')
|
||||
return
|
||||
else :
|
||||
self._close(1003, 'Binary messages are not implemented')
|
||||
return
|
||||
|
||||
self._currentMsgType = None
|
||||
self._currentMsgData = None
|
||||
|
||||
self._waitFrame()
|
||||
|
||||
# - End of onPayloadDataRecv -
|
||||
|
||||
if not isCtrlFrame :
|
||||
# Message frame or continuation frame,
|
||||
if self._maxRecvMsgLen :
|
||||
l = dataLen
|
||||
if self._currentMsgData :
|
||||
l += len(self._currentMsgData)
|
||||
if l > self._maxRecvMsgLen :
|
||||
# Message length exceeds the defined limit,
|
||||
self._close(1009, 'Frame is too large to be processed')
|
||||
return
|
||||
if opcode == WebSocket._OP_FRAME_TEXT :
|
||||
self._currentMsgType = WebSocket._MSG_TYPE_TEXT
|
||||
elif opcode == WebSocket._OP_FRAME_BIN :
|
||||
self._currentMsgType = WebSocket._MSG_TYPE_BIN
|
||||
try :
|
||||
self._recvData(onPayloadDataRecv, dataLen)
|
||||
except :
|
||||
# Frame is too large for memory allocation,
|
||||
self._close(1009, 'Frame is too large to be processed')
|
||||
elif opcode == WebSocket._OP_FRAME_PING :
|
||||
# Ping control frame,
|
||||
if dataLen > 0 :
|
||||
def onPingDataRecv(xasCli, data, arg) :
|
||||
data = bytearray(data)
|
||||
self._sendFrame(WebSocket._OP_FRAME_PONG, data)
|
||||
self._waitFrame()
|
||||
self._recvData(onPingDataRecv, dataLen)
|
||||
else :
|
||||
self._sendFrame(WebSocket._OP_FRAME_PONG)
|
||||
self._waitFrame()
|
||||
elif opcode == WebSocket._OP_FRAME_PONG :
|
||||
# Pong control frame,
|
||||
if dataLen > 0 :
|
||||
def onPongDataRecv(xasCli, data, arg) :
|
||||
self._waitFrame()
|
||||
self._recvData(onPongDataRecv, dataLen)
|
||||
else :
|
||||
self._waitFrame()
|
||||
elif opcode == WebSocket._OP_FRAME_CLOSE :
|
||||
# Close control frame,')
|
||||
if dataLen > 0 :
|
||||
def onCloseDataRecv(xasCli, data, arg) :
|
||||
self._close()
|
||||
self._recvData(onCloseDataRecv, dataLen)
|
||||
else :
|
||||
self._close()
|
||||
else :
|
||||
# Unknown frame type,
|
||||
self._close(1002, 'Protocol error (bad opcode)')
|
||||
|
||||
# - End of endOfHeader -
|
||||
|
||||
def getMaskingKey(dataLen) :
|
||||
|
||||
if masked :
|
||||
# Frame is masked by the next 4 bytes key,
|
||||
def onMaskingKeyRecv(xasCli, data, arg) :
|
||||
endOfHeader(dataLen=dataLen, maskingKey=bytes(data))
|
||||
self._recvData(onMaskingKeyRecv, 4)
|
||||
else :
|
||||
# Frame is not masked,
|
||||
endOfHeader(dataLen=dataLen, maskingKey=None)
|
||||
|
||||
# - End of getMaskingKey -
|
||||
|
||||
if length == 0 and not isCtrlFrame :
|
||||
# Bad frame for a no control frame without payload data,
|
||||
self._close(1002, 'Protocol error (payload data required)')
|
||||
elif length <= 0x7D :
|
||||
# Frame length <= 0x7D,
|
||||
getMaskingKey(dataLen=length)
|
||||
elif isCtrlFrame :
|
||||
# Bad frame for length of control frame > 0x7D,
|
||||
self._close(1002, 'Protocol error (bad control frame length)')
|
||||
elif length == 0x7E :
|
||||
# Frame length is encoded on next 16 bits,
|
||||
def onLenExt1Recv(xasCli, data, arg) :
|
||||
length = (data[0] << 8) + data[1]
|
||||
if length < 0x7E :
|
||||
# Bad frame for 16 bits length < 0x7E,
|
||||
self._close(1002, 'Protocol error (bad length encoding)')
|
||||
else :
|
||||
getMaskingKey(dataLen=length)
|
||||
self._recvData(onLenExt1Recv, 2)
|
||||
else :
|
||||
# Frame length is encoded on next 64 bits.
|
||||
# It's too large and not implemented,
|
||||
self._close(1009, 'Frame is too large to be processed')
|
||||
|
||||
# - End of onHdrStartingRecv -
|
||||
|
||||
self._xasCli.AsyncRecvData( size = 2,
|
||||
onDataRecv = onHdrStartingRecv,
|
||||
timeoutSec = self._waitFrameTimeoutSec )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _sendFrame(self, opcode, data=None, fin=True) :
|
||||
try :
|
||||
if opcode >= 0x00 and opcode <= 0x0F :
|
||||
length = len(data) if data else 0
|
||||
if length <= 0xFFFF :
|
||||
data = bytes([ (opcode | 0x80) if fin else opcode ] ) \
|
||||
+ bytes([ length if length <= 0x7D else 0x7E ] ) \
|
||||
+ (pack('>H', length) if length >= 0x7E else b'') \
|
||||
+ (bytes(data) if data else b'')
|
||||
return self._xasCli.AsyncSendData(data)
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _close(self, statusCode=None, reason=None, waitCloseFrame=False) :
|
||||
if not self._isClosed :
|
||||
if statusCode :
|
||||
data = pack('>H', statusCode)
|
||||
if reason :
|
||||
data += reason.encode('UTF-8')
|
||||
else :
|
||||
data = None
|
||||
self._sendFrame(WebSocket._OP_FRAME_CLOSE, data)
|
||||
self._isClosed = True
|
||||
if waitCloseFrame :
|
||||
return
|
||||
self._xasCli.Close()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SendTextMessage(self, msg) :
|
||||
if not isinstance(msg, str) or len(msg) == 0 :
|
||||
raise ValueError('"msg" must be a not empty string.')
|
||||
if not self._isClosed :
|
||||
try :
|
||||
msg = msg.encode('UTF-8')
|
||||
except :
|
||||
return False
|
||||
return self._sendFrame(WebSocket._OP_FRAME_TEXT, msg)
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SendBinaryMessage(self, msg) :
|
||||
try :
|
||||
bytes([msg[0]])
|
||||
except :
|
||||
raise ValueError('"msg" must be a not empty bytes object.')
|
||||
if not self._isClosed :
|
||||
return self._sendFrame(WebSocket._OP_FRAME_BIN, msg)
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def Close(self) :
|
||||
if not self._isClosed :
|
||||
self._close(1000, 'Normal closure', waitCloseFrame=True)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Request(self) :
|
||||
return self._request
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsClosed(self) :
|
||||
return self._isClosed
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def WaitFrameTimeoutSec(self) :
|
||||
return self._waitFrameTimeoutSec
|
||||
|
||||
@WaitFrameTimeoutSec.setter
|
||||
def WaitFrameTimeoutSec(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"WaitFrameTimeoutSec" must be a positive integer.')
|
||||
self._waitFrameTimeoutSec = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def MaxRecvMessageLength(self) :
|
||||
return self._maxRecvMsgLen
|
||||
|
||||
@MaxRecvMessageLength.setter
|
||||
def MaxRecvMessageLength(self, value) :
|
||||
if value is not None and (not isinstance(value, int) or value < 125) :
|
||||
raise ValueError('"MaxRecvMessageLength" must be an integer >= 125 or None.')
|
||||
self._maxRecvMsgLen = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnTextMessage(self) :
|
||||
return self._onTextMsg
|
||||
|
||||
@OnTextMessage.setter
|
||||
def OnTextMessage(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnTextMessage" must be a function.')
|
||||
self._onTextMsg = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnBinaryMessage(self) :
|
||||
return self._onBinMsg
|
||||
|
||||
@OnBinaryMessage.setter
|
||||
def OnBinaryMessage(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnBinaryMessage" must be a function.')
|
||||
self._onBinMsg = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnClosed(self) :
|
||||
return self._onClosed
|
||||
|
||||
@OnClosed.setter
|
||||
def OnClosed(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnClosed" must be a function.')
|
||||
self._onClosed = value
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,184 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
# ============================================================================
|
||||
# ===( @WebRoute decorator )==================================================
|
||||
# ============================================================================
|
||||
|
||||
def WebRoute(method=None, routePath=None, name=None) :
|
||||
|
||||
if type(method) is type(lambda x:x) and not routePath :
|
||||
raise ValueError('[@WebRoute] arguments are required for this decorator.')
|
||||
|
||||
def decorated(handler) :
|
||||
RegisterRoute(handler, method, routePath, name)
|
||||
s = (' (%s)' % name) if name else ''
|
||||
print(' + [@WebRoute] %s %s' % (method, routePath) + s)
|
||||
return handler
|
||||
|
||||
return decorated
|
||||
|
||||
# ============================================================================
|
||||
# ===( RegisterResult )=======================================================
|
||||
# ============================================================================
|
||||
|
||||
def RegisterRoute(handler, method, routePath, name=None) :
|
||||
if type(handler) is not type(lambda x:x) :
|
||||
raise ValueError('"handler" must be a function.')
|
||||
if not isinstance(method, str) or len(method) == 0 :
|
||||
raise ValueError('"method" requires a not empty string.')
|
||||
if not isinstance(routePath, str) or len(routePath) == 0 :
|
||||
raise ValueError('"routePath" requires a not empty string.')
|
||||
if routePath[0] != '/' :
|
||||
raise ValueError('"routePath" must start with a "/".')
|
||||
if name is not None and not isinstance(name, str) :
|
||||
raise ValueError('"name" must be a string or None.')
|
||||
method = method.upper()
|
||||
if len(routePath) > 1 and routePath.endswith('/') :
|
||||
routePath = routePath[:-1]
|
||||
# Route -> '/users/<uID>/addresses/<addrID>/test/<anotherID>'
|
||||
# Regex -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$'
|
||||
# Args -> ['uID', 'addrID', 'anotherID']
|
||||
argNames = [ ]
|
||||
regex = ''
|
||||
try :
|
||||
for i, part in enumerate(routePath.lower().split('/')) :
|
||||
if i > 0 :
|
||||
if part.startswith('<') and part.endswith('>') :
|
||||
argName = part[1:-1]
|
||||
if not argName :
|
||||
raise Exception
|
||||
argNames.append(argName)
|
||||
regex += '/([\\w.]*)'
|
||||
else :
|
||||
regex += '/' + part
|
||||
regex = re.compile(regex + '$')
|
||||
except :
|
||||
raise ValueError('Bad route path: "%s".' % routePath)
|
||||
for regRoute in _registeredRoutes :
|
||||
if regRoute.Method == method and regRoute.Regex == regex :
|
||||
raise ValueError('Duplicated route: "%s".' % routePath)
|
||||
regRoute = _registeredRoute(handler, method, routePath, name, regex, argNames)
|
||||
_registeredRoutes.append(regRoute)
|
||||
|
||||
# ============================================================================
|
||||
# ===( ResolveRoute )=========================================================
|
||||
# ============================================================================
|
||||
|
||||
def ResolveRoute(method, path) :
|
||||
try :
|
||||
path = path.lower()
|
||||
if len(path) > 1 and path.endswith('/') :
|
||||
path = path[:-1]
|
||||
for regRoute in _registeredRoutes :
|
||||
if regRoute.Method == method :
|
||||
reMatch = regRoute.Regex.match(path)
|
||||
if reMatch :
|
||||
if not regRoute.ArgNames :
|
||||
return RouteResult(regRoute)
|
||||
args = { }
|
||||
for i, argName in enumerate(regRoute.ArgNames) :
|
||||
argValue = reMatch.group(i+1)
|
||||
try :
|
||||
argValue = int(argValue)
|
||||
except :
|
||||
pass
|
||||
args[argName] = argValue
|
||||
return RouteResult(regRoute, args)
|
||||
except :
|
||||
pass
|
||||
return None
|
||||
|
||||
# ============================================================================
|
||||
# ===( PathFromRoute )========================================================
|
||||
# ============================================================================
|
||||
|
||||
def PathFromRoute(routeName, routeArgs={ }) :
|
||||
if not isinstance(routeName, str) or len(routeName) == 0 :
|
||||
raise ValueError('"routeName" requires a not empty string.')
|
||||
if not isinstance(routeArgs, dict) :
|
||||
raise ValueError('"routeArgs" must be a dict.')
|
||||
for regRoute in _registeredRoutes :
|
||||
if regRoute.Name == routeName :
|
||||
path = regRoute.RoutePath
|
||||
for argName in regRoute.ArgNames :
|
||||
arg = routeArgs.get(argName, None)
|
||||
if arg is None :
|
||||
raise ValueError('"routeArgs" does not contains "%s" for route %s.' % (argName, routeName))
|
||||
path = path.replace('<%s>' % argName, str(arg))
|
||||
return path
|
||||
raise ValueError('"routeName" is not a registered route (%s).' % routeName)
|
||||
|
||||
# ============================================================================
|
||||
# ===( RouteResult )==========================================================
|
||||
# ============================================================================
|
||||
|
||||
class RouteResult :
|
||||
|
||||
def __init__(self, regRoute, args=None) :
|
||||
self._regRoute = regRoute
|
||||
self._args = args
|
||||
|
||||
def __repr__(self) :
|
||||
if self._regRoute.Name :
|
||||
return self._regRoute.Name
|
||||
return '%s %s' % (self._regRoute.Method, self._regRoute.RoutePath)
|
||||
|
||||
@property
|
||||
def Handler(self) :
|
||||
return self._regRoute.Handler
|
||||
|
||||
@property
|
||||
def Method(self) :
|
||||
return self._regRoute.Method
|
||||
|
||||
@property
|
||||
def RoutePath(self) :
|
||||
return self._regRoute.RoutePath
|
||||
|
||||
@property
|
||||
def Name(self) :
|
||||
return self._regRoute.Name
|
||||
|
||||
@property
|
||||
def Args(self) :
|
||||
return self._args
|
||||
|
||||
# ============================================================================
|
||||
# ===( Methods )==============================================================
|
||||
# ============================================================================
|
||||
|
||||
GET = 'GET'
|
||||
HEAD = 'HEAD'
|
||||
POST = 'POST'
|
||||
PUT = 'PUT'
|
||||
DELETE = 'DELETE'
|
||||
OPTIONS = 'OPTIONS'
|
||||
PATCH = 'PATCH'
|
||||
|
||||
# ============================================================================
|
||||
# ===( Private registered routes )===========================================
|
||||
# ============================================================================
|
||||
|
||||
_registeredRoutes = [ ]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
class _registeredRoute :
|
||||
|
||||
def __init__(self, handler, method, routePath, name, regex, argNames) :
|
||||
self.Handler = handler
|
||||
self.Method = method
|
||||
self.RoutePath = routePath
|
||||
self.Name = name
|
||||
self.Regex = regex
|
||||
self.ArgNames = argNames
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
Reference in New Issue
Block a user