def makeService(self, options): class LongSession(Session): sessionTimeout = 3600 if options['steamkey'] is None: raise ValueError('Must specify steam API key.') if options['strport'] is None: raise ValueError('Must specify strport description.') if options['dbdir'] is None: raise ValueError('Must specify database path.') steamAPI = API(key=options['steamkey']) store = Store(options['dbdir']) keyPath = FilePath(options['dbdir']).child('fernet.key') database = Database(store) loginRedirect = '/' portal = Portal(MapListRealm(database, options['bundle-path'], steamAPI, loginRedirect)) portal.registerChecker(PreauthenticatedChecker()) portal.registerChecker(AllowAnonymousAccess()) root = HTTPOpenIDAuthSessionWrapper(portal, [], loginRedirect, keyPath, database) site = Site(root) site.sessionFactory = LongSession return strports.service(options['strport'], site)
def whenRunning(cls, config: Configuration) -> None: """ Called after the reactor has started. """ async def start() -> None: await config.store.upgradeSchema() await config.store.validate() d = ensureDeferred(start()) host = config.HostName port = config.Port application = Application(config=config) cls.log.info( "Setting up web service at http://{host}:{port}/", host=host, port=port, ) patchCombinedLogFormatter() factory = Site(application.router.resource()) factory.sessionFactory = IMSSession from twisted.internet import reactor reactor.listenTCP(port, factory, interface=host) return d
def trade_server(): root = File("./htdocs") # for _symbol in MARKETS.keys(): root.putChild(str.encode(_symbol), resource) factory = EchoServerFactory() factory.protocol = EchoServerProtocol factory.startFactory( ) # when wrapped as a Twisted Web resource, start the underlying factory manually resource = WebSocketResource(factory) root.putChild(b"wss", resource) root.putChild(b"symbols", SymbolPage()) # 用于向页面传递交易对接口 root.putChild(b"signin", SignInPage()) # 登录页面 root.putChild(b"logout", SignOutPage()) # 登出页面 root.putChild(b"logchk", LogCheckPage()) # 登陆状态检测接口 root.putChild(b"setlost", SetLostPage()) # 设置全局变量是否自动止损 root.putChild(b"trade", TradePage()) # 交易接口 root.putChild(b"cancel", CancelPage()) # 取消所有订单 root.putChild(b"contract", GetCoinsPage()) # 获取最新价格接口 root.putChild(b"topdown", TopDownPage()) # 获取和设置当前品种的压力和支撑价格 # use TLS privkey = open('cert/server.key', 'rt').read() certif = open('cert/fullchain.cer', 'rt').read() privkeypyssl = crypto.load_privatekey(crypto.FILETYPE_PEM, privkey) certifpyssl = crypto.load_certificate(crypto.FILETYPE_PEM, certif) contextFactory = ssl.CertificateOptions(privateKey=privkeypyssl, certificate=certifpyssl) site = Site(root) site.sessionFactory = longTimeoutSession reactor.listenSSL(SRV_PORT, site, contextFactory) # reactor.listenTCP(SRV_PORT, site) reactor.run()
def main(): global root, factory for fn in "robots.txt favicon.ico style.css tpchat.js tpstyle.css".split(): staticFiles[fn] = File(os.path.join(tpconfig.htdocs_path, fn)) root = tpchat() factory = Site(root) factory.sessionFactory = LongSession connect_ircd() reactor.run()
def whenRunning(self): config = self.options["configuration"] config.directory.loadRecords() service = WebService(config) host = self.options.get("host", "localhost") port = int(self.options["port"]) self.log.info( "Setting up web service at http://{host}:{port}/", host=host, port=port, ) factory = Site(service.resource()) factory.sessionFactory = IMSSession from twisted.internet import reactor reactor.listenTCP(port, factory, interface=host)
def runServer(cls, config: Configuration) -> None: host = config.hostName port = config.port application = Application(config=config) cls.log.info( "Setting up web service at http://{host}:{port}/", host=host, port=port, ) patchCombinedLogFormatter() factory = Site(application.router.resource()) factory.sessionFactory = IMSSession from twisted.internet import reactor reactor.listenTCP(port, factory, interface=host)
def make_web_service(self): """ Create and return the web service site. """ web_realm = webauth.WebRealm.make_instance(self.reactor) portal = Portal(web_realm) checker = webauth.WerewolfWebCredChecker.make_instance() portal.registerChecker(checker) resources = WebResources.make_instance( self.reactor, portal) root = resources.app.resource() site = Site(root) session_length = self.session_length def sessionFactory(site, uid, reactor=None): s = Session(site, uid, reactor=reactor) s.sessionTimeout = session_length return s site.sessionFactory = sessionFactory site.displayTracebacks = self.displayTracebacks return site
def setup_finalize(event, application): from twisted.application import service, internet from twisted.internet import reactor, ssl from twisted.web.server import Site from twisted.python import log #from twisted.enterprise import adbapi import OpenSSL.SSL from services import ServiceEventHandler import socket_transport import http_transport #import websocket_transport import irc from stratum import settings try: import signature signing_key = signature.load_privkey_pem(settings.SIGNING_KEY) except: print "Loading of signing key '%s' failed, protocol messages cannot be signed." % settings.SIGNING_KEY signing_key = None # Attach HTTPS Poll Transport service to application try: sslContext = ssl.DefaultOpenSSLContextFactory(settings.SSL_PRIVKEY, settings.SSL_CACERT) except OpenSSL.SSL.Error: sslContext = None print "Cannot initiate SSL context, are SSL_PRIVKEY or SSL_CACERT missing?" print "This will skip all SSL-based transports." # Set up thread pool size for service threads reactor.suggestThreadPoolSize(settings.THREAD_POOL_SIZE) if settings.LISTEN_SOCKET_TRANSPORT: # Attach Socket Transport service to application socket = internet.TCPServer(settings.LISTEN_SOCKET_TRANSPORT, socket_transport.SocketTransportFactory(debug=settings.DEBUG, signing_key=signing_key, signing_id=settings.SIGNING_ID, event_handler=ServiceEventHandler, tcp_proxy_protocol_enable=settings.TCP_PROXY_PROTOCOL)) socket.setServiceParent(application) # Build the HTTP interface httpsite = Site(http_transport.Root(debug=settings.DEBUG, signing_key=signing_key, signing_id=settings.SIGNING_ID, event_handler=ServiceEventHandler)) httpsite.sessionFactory = http_transport.HttpSession if settings.LISTEN_HTTP_TRANSPORT: # Attach HTTP Poll Transport service to application http = internet.TCPServer(settings.LISTEN_HTTP_TRANSPORT, httpsite) http.setServiceParent(application) if settings.LISTEN_HTTPS_TRANSPORT and sslContext: https = internet.SSLServer(settings.LISTEN_HTTPS_TRANSPORT, httpsite, contextFactory = sslContext) https.setServiceParent(application) #if settings.LISTEN_WS_TRANSPORT: # from autobahn.websocket import listenWS # log.msg("Starting WS transport on %d" % settings.LISTEN_WS_TRANSPORT) # ws = websocket_transport.WebsocketTransportFactory(settings.LISTEN_WS_TRANSPORT, # debug=settings.DEBUG, # signing_key=signing_key, # signing_id=settings.SIGNING_ID, # event_handler=ServiceEventHandler) # listenWS(ws) #if settings.LISTEN_WSS_TRANSPORT and sslContext: # from autobahn.websocket import listenWS # log.msg("Starting WSS transport on %d" % settings.LISTEN_WSS_TRANSPORT) # wss = websocket_transport.WebsocketTransportFactory(settings.LISTEN_WSS_TRANSPORT, is_secure=True, # debug=settings.DEBUG, # signing_key=signing_key, # signing_id=settings.SIGNING_ID, # event_handler=ServiceEventHandler) # listenWS(wss, contextFactory=sslContext) if settings.IRC_NICK: reactor.connectTCP(settings.IRC_SERVER, settings.IRC_PORT, irc.IrcLurkerFactory(settings.IRC_ROOM, settings.IRC_NICK, settings.IRC_HOSTNAME)) return event
def setup_finalize(event, application): from twisted.application import service, internet from twisted.internet import reactor, ssl from twisted.web.server import Site from twisted.python import log #from twisted.enterprise import adbapi import OpenSSL.SSL from services import ServiceEventHandler import socket_transport import http_transport import websocket_transport from stratum import settings signing_key = None # Attach HTTPS Poll Transport service to application try: sslContext = ssl.DefaultOpenSSLContextFactory(settings.SSL_PRIVKEY, settings.SSL_CACERT) except OpenSSL.SSL.Error: sslContext = None print( "Cannot initiate SSL context, are SSL_PRIVKEY or SSL_CACERT missing?" ) print("This will skip all SSL-based transports.") # Set up thread pool size for service threads reactor.suggestThreadPoolSize(settings.THREAD_POOL_SIZE) if settings.LISTEN_SOCKET_TRANSPORT: # Attach Socket Transport service to application socket = internet.TCPServer( settings.LISTEN_SOCKET_TRANSPORT, socket_transport.SocketTransportFactory( debug=settings.DEBUG, signing_key=signing_key, signing_id=settings.SIGNING_ID, event_handler=ServiceEventHandler, tcp_proxy_protocol_enable=settings.TCP_PROXY_PROTOCOL)) socket.setServiceParent(application) # Build the HTTP interface httpsite = Site( http_transport.Root(debug=settings.DEBUG, signing_key=signing_key, signing_id=settings.SIGNING_ID, event_handler=ServiceEventHandler)) httpsite.sessionFactory = http_transport.HttpSession if settings.LISTEN_HTTP_TRANSPORT: # Attach HTTP Poll Transport service to application http = internet.TCPServer(settings.LISTEN_HTTP_TRANSPORT, httpsite) http.setServiceParent(application) if settings.LISTEN_HTTPS_TRANSPORT and sslContext: https = internet.SSLServer(settings.LISTEN_HTTPS_TRANSPORT, httpsite, contextFactory=sslContext) https.setServiceParent(application) if settings.LISTEN_WS_TRANSPORT: from autobahn.websocket import listenWS log.msg("Starting WS transport on %d" % settings.LISTEN_WS_TRANSPORT) ws = websocket_transport.WebsocketTransportFactory( settings.LISTEN_WS_TRANSPORT, debug=settings.DEBUG, signing_key=signing_key, signing_id=settings.SIGNING_ID, event_handler=ServiceEventHandler, tcp_proxy_protocol_enable=settings.TCP_PROXY_PROTOCOL) listenWS(ws) if settings.LISTEN_WSS_TRANSPORT and sslContext: from autobahn.websocket import listenWS log.msg("Starting WSS transport on %d" % settings.LISTEN_WSS_TRANSPORT) wss = websocket_transport.WebsocketTransportFactory( settings.LISTEN_WSS_TRANSPORT, is_secure=True, debug=settings.DEBUG, signing_key=signing_key, signing_id=settings.SIGNING_ID, event_handler=ServiceEventHandler) listenWS(wss, contextFactory=sslContext) return event
try: answer = json.loads(request.content.getvalue())['answer'] except ValueError: return 'You should be submitting as JSON' print "DBG Submission: |" + answer + "|" print "DBG Answer was: |" + self.solution + "|" # check submitted answer if answer == self.solution: print "DBG: challenge solved" return self.get_answer('challenge4') else: return 'wrong answer\n' def _expired(self, uid): try: self.sessions.remove(uid) except: pass # if __name__ == __main__ print "LOG: starting bit twiddling slash logic gate challenge" rootResource = Resource() rootResource.putChild("challenge4", Challenge4()) factory = Site(rootResource) factory.sessionFactory = LongSession reactor.listenTCP(8084, factory) reactor.run()
if answer == self.solution: return self.get_answer('challengeb1') else: return 'Try again' def _expired(self, uid): try: self.sessions.remove(uid) except KeyError: pass class GetBook(Resource): def render_POST(self, request): return "You shouldn't be posting here" def render_GET(self, request): orginalFile = open('Alice_in_Wonderland.txt','r') data = orginalFile.read() orginalFile.close() return data rootResource = Resource() rootResource.putChild("challengeb1", Challengeb1()) rootResource.putChild("book.txt", GetBook()) factory = Site(rootResource) factory.sessionFactory = ShortSession reactor.listenTCP(8091, factory) reactor.run()