Esempio n. 1
0
 def _child(self, path, title, prefix):
     raise 0
     #print(path, title, prefix)
     return File(path)
Esempio n. 2
0
    def _configure_named_resource(self, name, compress=False):
        """Build a resource map for a named resource

        Args:
            name (str): named resource: one of "client", "federation", etc
            compress (bool): whether to enable gzip compression for this
                resource

        Returns:
            dict[str, Resource]: map from path to HTTP resource
        """
        resources = {}
        if name == "client":
            client_resource = ClientRestResource(self)
            if compress:
                client_resource = gz_wrap(client_resource)

            resources.update({
                "/_matrix/client/api/v1": client_resource,
                "/_matrix/client/r0": client_resource,
                "/_matrix/client/unstable": client_resource,
                "/_matrix/client/v2_alpha": client_resource,
                "/_matrix/client/versions": client_resource,
            })

        if name == "consent":
            from synapse.rest.consent.consent_resource import ConsentResource
            consent_resource = ConsentResource(self)
            if compress:
                consent_resource = gz_wrap(consent_resource)
            resources.update({
                "/_matrix/consent": consent_resource,
            })

        if name == "federation":
            resources.update({
                FEDERATION_PREFIX: TransportLayerServer(self),
            })

        if name in ["static", "client"]:
            resources.update({
                STATIC_PREFIX:
                File(os.path.join(os.path.dirname(synapse.__file__),
                                  "static")),
            })

        if name in ["media", "federation", "client"]:
            if self.get_config().enable_media_repo:
                media_repo = self.get_media_repository_resource()
                resources.update({
                    MEDIA_PREFIX:
                    media_repo,
                    LEGACY_MEDIA_PREFIX:
                    media_repo,
                    CONTENT_REPO_PREFIX:
                    ContentRepoResource(self, self.config.uploads_path),
                })
            elif name == "media":
                raise ConfigError(
                    "'media' resource conflicts with enable_media_repo=False",
                )

        if name in ["keys", "federation"]:
            resources.update({
                SERVER_KEY_PREFIX: LocalKey(self),
                SERVER_KEY_V2_PREFIX: KeyApiV2Resource(self),
            })

        if name == "webclient":
            resources[WEB_CLIENT_PREFIX] = build_resource_for_web_client(self)

        if name == "metrics" and self.get_config().enable_metrics:
            resources[METRICS_PREFIX] = MetricsResource(self)

        if name == "replication":
            resources[REPLICATION_PREFIX] = ReplicationRestResource(self)

        return resources
Esempio n. 3
0
    ## start Twisted logging to stdout
    ##
    log.startLogging(sys.stdout)

    ## we use an Autobahn utility to install the "best" available Twisted reactor
    ##
    from autobahn.choosereactor import install_reactor
    reactor = install_reactor()
    print("Running on reactor {}".format(reactor))

    ## start a WebSocket server
    ##
    wsfactory = EchoServerFactory(args.wsurl, debug=args.debug)
    wsserver = serverFromString(reactor, args.websocket)
    wsserver.listen(wsfactory)

    ## start a Web server
    ##
    if args.web != "":
        from twisted.web.server import Site
        from twisted.web.static import File

        webfactory = Site(File("."))
        webserver = serverFromString(reactor, args.web)
        webserver.listen(webfactory)

    ## now enter the Twisted reactor loop
    ##
    reactor.run()
Esempio n. 4
0
 def setUpFileServer(self, port, path):
     # Create a local file server, can be used to serve local files. This is preferred over an external network
     # request in order to get files.
     resource = File(path)
     factory = Site(resource)
     self.file_server = reactor.listenTCP(port, factory)
Esempio n. 5
0
'''
Created on 10/set/2014

@author: riccardo
'''
from twisted.internet import reactor 
from twisted.web.server import Site 
from twisted.web.static import File

root = File('/var/www/mysite')
root.putChild("doc", File("/usr/share/doc"))
root.putChild("logs", File("/var/log/mysitelogs"))
factory = Site(root)

reactor.listenTCP(8000, factory)  # @UndefinedVariable
reactor.run()  # @UndefinedVariable
Esempio n. 6
0
 def root(request):
     return File(os.path.dirname(__file__))
Esempio n. 7
0
        yield self.register(Sketch_Stop, u"allofw.sketch.stop")
        yield self.register(Sketch_List, u"allofw.sketch.list")
        yield self.register(Sketch_GetCode, u"allofw.sketch.get_code")

        yield self.register(Project_List, u"allofw.project.list")
        yield self.register(Project_Delete, u"allofw.project.delete")
        yield self.register(Project_UploadFile, u"allofw.project.upload_file")
        yield self.register(Project_RenameFile, u"allofw.project.rename_file")
        yield self.register(Project_ListFiles, u"allofw.project.list_files")
        yield self.register(Project_LoadProject,
                            u"allofw.project.load_project")
        yield self.register(Project_SaveProject,
                            u"allofw.project.save_project")


root = File("static")
session_factory = RouterSessionFactory(RouterFactory())
component_config = types.ComponentConfig(realm="anonymous")
session_factory.add(AllofwServer(component_config))
factory = WampWebSocketServerFactory(session_factory)
factory.startFactory()
resource = WebSocketResource(factory)
root.putChild("ws", resource)

site = Site(root)
reactor.listenTCP(int(config['webserver']['port']),
                  site,
                  interface=config['webserver']['listen'])

reactor.run()
Esempio n. 8
0
 def __init__(self, port_low, port_high):
     self.port_low = port_low
     self.port_high = port_high
     self.factory = Site(File('web'))
     self.spinUp()
Esempio n. 9
0
    def render_GET(self, request):
        localPath = finders.find('/'.join(request.postpath))
        if not localPath:
            return File.childNotFound.render(request)

        return File(localPath).render_GET(request)
Esempio n. 10
0
                      action='store',
                      dest='http_port',
                      type='int',
                      default=8888)

    (options, args) = parser.parse_args()

    fast = Fast()

    fast.factory = Favor2ClientFactory(FastProtocol, fast)

    from twisted.internet import reactor
    reactor.connectTCP('localhost', options.port, fast.factory)

    passwd = {'fast': 'fast'}

    # Serve files from web
    root = File("web")
    # ...with some other paths handled also
    root.putChild("", File('web/webfast.html'))
    root.putChild("fast.html", File('web/webfast.html'))

    root.putChild("fast", WebFast(fast, base='/fast'))

    #site = Site(Auth(root, passwd))
    site = Site(root)

    reactor.listenTCP(options.http_port, site)

    reactor.run()
    def start(self, options, service):
        """
        Main method to startup the cli and add a signal handler.
        """

        msg("Service: Starting")

        self.service = service

        # State directory
        state_directory = options['statedir']
        util.create_directory_if_not_exists(state_directory)

        # port
        network_port = options['port']

        # Initial configuration
        configuration = get_default_configuration()
        configuration['address'] = "0.0.0.0"
        configuration['port'] = network_port
        configuration['keys'] = [{
            'alias':
            'my peer',
            'generation':
            u"curve25519",
            'file':
            os.path.join(state_directory, u"ec.pem")
        }]
        configuration['logger'] = {'level': "ERROR"}
        configuration['overlays'] = [{
            'class':
            'DiscoveryCommunity',
            'key':
            "my peer",
            'walkers': [{
                'strategy': 'RandomWalk',
                'peers': -1,
                'init': {
                    'timeout': 3.0
                }
            }, {
                'strategy': 'RandomChurn',
                'peers': -1,
                'init': {
                    'sample_size': 64,
                    'ping_interval': 1.0,
                    'inactive_time': 1.0,
                    'drop_time': 3.0
                }
            }],
            'initialize': {},
            'on_start': [('resolve_dns_bootstrap_addresses', )]
        }]
        configuration['overlays'] = []

        # IPv8 instance
        self.ipv8 = IPv8(configuration)

        # Network port
        actual_network_port = self.ipv8.endpoint.get_address()[1]

        # Peer
        self.my_peer = self.ipv8.keys.get('my peer')

        # Trustchain community
        self.trustchain_community = TrustChainTestnetCommunity(
            self.my_peer,
            self.ipv8.endpoint,
            self.ipv8.network,
            working_directory=state_directory)
        self.ipv8.overlays.append(self.trustchain_community)
        self.ipv8.strategies.append((EdgeWalk(self.trustchain_community), 10))

        # Event bus
        self.bus = EventBus()

        # module community
        self.module_community = ModuleCommunity(
            self.my_peer,
            self.ipv8.endpoint,
            self.ipv8.network,
            trustchain=self.trustchain_community,
            bus=self.bus,
            working_directory=state_directory,
            ipv8=self.ipv8,
            service=self.service)
        self.ipv8.overlays.append(self.module_community)
        self.ipv8.strategies.append((RandomWalk(self.module_community), 10))

        def signal_handler(sig, _):
            msg("Service: Received shut down signal %s" % sig)
            if not self._stopping:
                self.stop()

        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)

        self.rest_api = RESTManager(self.ipv8)
        self.rest_api.start(actual_network_port + 1000)
        self.rest_api.root_endpoint.putChild('module',
                                             ModuleRootEndpoint(self.ipv8))

        plugin_dir = os.path.abspath(
            os.path.dirname(os.path.realpath(__file__)))
        base_dir = os.path.dirname(os.path.dirname(plugin_dir))
        web_path = os.path.join(base_dir, 'module_loader', 'web')

        msg(plugin_dir)
        msg(base_dir)
        msg(web_path)

        self.rest_api.root_endpoint.putChild('gui', File(web_path))
Esempio n. 12
0
from twisted.internet import reactor, endpoints
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.web.static import File
import cgi

class PostHandler(Resource):

    def render_POST(self, request):
        content = request.content.read().decode("utf-8")
        escapedContent = cgi.escape(content)
        print(escapedContent)
        return b"12345"

root = File('www')
root.putChild(b"post_test", PostHandler())
factory = Site(root)
endpoint = endpoints.TCP4ServerEndpoint(reactor, 8888)
endpoint.listen(factory)
reactor.run()
Esempio n. 13
0
            c.sendMessage(msg.encode('utf8'))
            print("message sent to {}".format(c.peer))


if __name__ == '__main__':

    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        log.startLogging(sys.stdout)
        debug = True
    else:
        debug = False
    contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key',
                                                      'keys/server.crt')
    ServerFactory = BroadcastServerFactory
    factory = ServerFactory("wss://localhost:9000",
                            debug=True,
                            debugCodePaths=True)
    factory.protocol = BroadcastServerProtocol
    factory.setProtocolOptions(allowHixie76=True)
    listenWS(factory, contextFactory)
    webdir = File("web/")
    webdir.contentTypes['.crt'] = 'application/x-x509-ca-cert'
    web = Site(webdir)
    web.protocol = HTTPChannelHixie76Aware
    webdir.contentTypes['.crt'] = 'application/x-x509-ca-cert'
    factory.setProtocolOptions(allowHixie76=True)
    #reactor.listenTCP(443, web)
    reactor.listenSSL(443, web, contextFactory)
    reactor.run()
    factory.lighting.stop()
Esempio n. 14
0
    
    def unsubscribe(self, p, channel):
        if channel in self.channels:
            self.channels[channel].remove(p)
            if not self.channels[channel]:
                del self.channels[channel]
    
    def publish(self, channel, message, error=False):
        if channel in self.channels:
            for p in self.channels[channel]:
                if error:
                    p.errorReceived(channel, message)
                else:
                    p.messageReceived(channel, message)

# Start the party
shutil.rmtree("./tmp")
os.mkdir("./tmp")

index_page = File("index.html")
index_page.putChild("sockjs", SockJSResource(TumblrServer()))
index_page.putChild("archives", File("archives"))

from functools import partial
def bypass(self, path, request):
    return self
index_page.getChild = partial(bypass, index_page)

def resource():
    return index_page
Esempio n. 15
0
                if item.startswith('.'):
                    continue

                title = item
                link = os.path.join(rpath, item)
                encoded_link = urllib2.quote(link)
                #print "link: %s -> %s" % (link, encoded_link)
                full_path = os.path.join(upath, item)
                if os.path.isdir(full_path):
                    data = data + '<li><a href="/%s">%s</a></li>' % (
                        encoded_link, item)
                else:
                    data = data + '<li>%s</li>' % (item)

            data = data + "</ul>"
        else:
            data = "error: %s" % upath
        return data

root = Home()

if os.path.exists(audiobooks_path):
    root.putChild(
        'repo', File(audiobooks_path, defaultType='application/octet-stream'))
site = server.Site(root)
ip_adr = "localhost"
port = 9090
reactor.listenTCP(port, site)
print "running server at: %s:%d" % (ip_adr, port)
reactor.run()
Esempio n. 16
0
File: server.py Progetto: ror32/VTK
def start_webserver(options,
                    protocol=vtk_wamp.ServerProtocol,
                    disableLogging=False):
    """
    Starts the web-server with the given protocol. Options must be an object
    with the following members:
        options.host : the interface for the web-server to listen on
        options.port : port number for the web-server to listen on
        options.timeout : timeout for reaping process on idle in seconds
        options.content : root for web-pages to serve.
    """
    from twisted.internet import reactor
    from twisted.web.server import Site
    from twisted.web.static import File
    import sys

    if not disableLogging:
        log.startLogging(sys.stdout)

    contextFactory = None

    use_SSL = False
    if options.sslKey and options.sslCert:
        use_SSL = True
        wsProtocol = "wss"
        from twisted.internet import ssl
        contextFactory = ssl.DefaultOpenSSLContextFactory(
            options.sslKey, options.sslCert)
    else:
        wsProtocol = "ws"

    # Create WAMP router factory
    from autobahn.twisted.wamp import RouterFactory
    router_factory = RouterFactory()

    # create a user DB
    authdb = vtk_wamp.AuthDb()

    # create a WAMP router session factory
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = vtk_wamp.CustomWampCraRouterSession
    session_factory.authdb = authdb

    # Create ApplicationSession and register protocols
    appSession = protocol(types.ComponentConfig(realm="vtkweb"))
    appSession.setAuthDB(authdb)
    session_factory.add(appSession)

    # create a WAMP-over-WebSocket transport server factory
    transport_factory = vtk_wamp.TimeoutWampWebSocketServerFactory(session_factory, \
           url        = "%s://%s:%d" % (wsProtocol, options.host, options.port),    \
           debug      = options.debug,                                              \
           debug_wamp = options.debug,                                              \
           timeout    = options.timeout )

    root = Resource()

    # Do we serve static content or just websocket ?
    if len(options.content) > 0:
        # Static HTTP + WebSocket
        root = File(options.content)

    # Handle possibly complex ws endpoint
    if not options.nows:
        wsResource = WebSocketResource(transport_factory)
        handle_complex_resource_path(options.ws, root, wsResource)

    # Handle binary push WebSocket for images
    if not options.nobws:
        wsbFactory = WebSocketServerFactory( \
            url   = "%s://%s:%d" % (wsProtocol, options.host, options.port), \
            debug = options.debug)
        wsbFactory.protocol = vtk_wamp.ImagePushBinaryWebSocketServerProtocol
        wsbResource = WebSocketResource(wsbFactory)
        handle_complex_resource_path('wsb', root, wsbResource)

    # Handle possibly complex lp endpoint
    if not options.nolp:
        lpResource = WampLongPollResource(session_factory,
                                          timeout=options.timeout,
                                          debug=options.debug)
        #killAfter = 30000,
        #queueLimitBytes = 1024 * 1024,
        #queueLimitMessages = 1000,
        #debug=True,
        #reactor=reactor)
        handle_complex_resource_path(options.lp, root, lpResource)

    if options.uploadPath != None:
        from upload import UploadPage
        uploadResource = UploadPage(options.uploadPath)
        root.putChild("upload", uploadResource)

    if len(options.fsEndpoints) > 3:
        for fsResourceInfo in options.fsEndpoints.split('|'):
            infoSplit = fsResourceInfo.split(':')
            handle_complex_resource_path(infoSplit[0], root,
                                         File(infoSplit[1]))

    site = Site(root)

    if use_SSL:
        reactor.listenSSL(options.port, site, contextFactory)
    else:
        reactor.listenTCP(options.port, site)

    # flush ready line
    sys.stdout.flush()

    # Work around to force the output buffer to be flushed
    # This allow the process launcher to parse the output and
    # wait for "Start factory" to know that the WebServer
    # is running.
    if options.forceFlush:
        for i in range(200):
            log.msg("+" * 80, logLevel=logging.CRITICAL)

    # Initialize testing: checks if we're doing a test and sets it up
    testing.initialize(options, reactor, stop_webserver)

    # Start the reactor
    if options.nosignalhandlers:
        reactor.run(installSignalHandlers=0)
    else:
        reactor.run()

    # Give the testing module a chance to finalize, if necessary
    testing.finalize()
Esempio n. 17
0
 def __init__(self):
     Resource.__init__(self)
     self.putChild("static", File("data/web_static"))
Esempio n. 18
0
 def static(self, request):
     return File(self.static_path)
Esempio n. 19
0
from twisted.web.client import getPage  #helper to call remote path asynchronously
from email.mime.text import MIMEText
from twisted.mail.smtp import sendmail  #helper to send email asynchronously

from zope.interface import Interface, Attribute, implements
from twisted.python.components import registerAdapter

site_root = os.path.join("\python_projects", "twisted-website")
log_path = os.path.join(site_root, "logs", "requests.txt")
template_path = os.path.join(site_root, "templates")
public_path = os.path.join(site_root, "public")
jinja_extensions = ['jinja2.ext.autoescape']
server_port = 8080

print(public_path)
public_resource = File(public_path)

#database params
db_module = "MySQLdb"
db = "sms"
database_user = "******"
database_password = ""
database_host = "localhost"
database_port = "3306"

#lets use twisted's asynchronous approach
dbpool = adbapi.ConnectionPool(db_module,
                               database=db,
                               user=database_user,
                               password=database_password,
                               host=database_host,
Esempio n. 20
0
         'wb').write(cipher.encrypt('0|| | |0|0|0|0|0|0|0|0|0|0|0| '))
    open(os.path.join(path, 'DLC_Special_{}.txt'.format(language)),
         'wb').write(cipher.encrypt('0||0| '))


parser = argparse.ArgumentParser(
    description='Runs a proxy for serving custom MH4U DLC quests.')
parser.add_argument('region',
                    choices=('JPN', 'USA', 'EUR', 'KOR'),
                    help='your game region')
parser.add_argument('language',
                    choices=('jpn', 'eng', 'fre', 'spa', 'ger', 'ita', 'kor'),
                    help='your game language')
parser.add_argument('--event',
                    nargs='+',
                    help='the decrypted event quest files to serve')
parser.add_argument('--challenge',
                    nargs='+',
                    help='the decrypted challenge quest files to serve')
args = parser.parse_args()

root = tempfile.mkdtemp()
try:
    make_root(root, args.region, args.language, args.event, args.challenge)
    log.startLogging(sys.stderr)
    reactor.listenTCP(8080, proxy.TunnelProxyFactory())
    reactor.listenTCP(8081, Site(File(root)))
    reactor.run()
finally:
    shutil.rmtree(root)
Esempio n. 21
0
    mount.factory = Favor2ClientFactory(MountProtocol, mount)

    beholder.factory = Favor2ClientFactory(BeholderProtocol, beholder)
    scheduler.factory = Favor2ClientFactory(SchedulerProtocol, scheduler)

    from twisted.internet import reactor
    reactor.connectTCP('localhost', 5555, channel.channel_factory)
    reactor.connectTCP('localhost', 5556, channel.hw_factory)
    reactor.connectTCP('localhost', 5562, mount.factory)
    reactor.connectTCP('localhost', 5560, beholder.factory)
    reactor.connectTCP('localhost', 5557, scheduler.factory)

    passwd = {'favor': 'favor'}

    # Serve files from web
    root = File("web")
    # ...with some other paths handled also
    root.putChild("", File('web/webchannel.html'))
    root.putChild("beholder.html", File('web/webchannel.html'))
    root.putChild("channel.html", File('web/webchannel.html'))
    root.putChild("mount.html", File('web/webchannel.html'))
    root.putChild("scheduler.html", File('web/webchannel.html'))

    root.putChild("channel", WebChannel(channel))
    root.putChild("mount", WebMount(mount))
    root.putChild("beholder", WebBeholder(beholder, scheduler))
    root.putChild("scheduler", WebScheduler(scheduler))

    #site = Site(Auth(root, passwd))
    site = Site(root)
Esempio n. 22
0
 def static(self, request):
     return File("./static")
Esempio n. 23
0
    def __init__(
        self,
        pool,
        ui_enabled,
        lua_enabled,
        lua_sandbox_enabled,
        lua_package_path,
        lua_sandbox_allowed_modules,
        max_timeout,
        argument_cache_max_entries,
        strict_lua_runner,
        browser_engines_enabled: List[str],
        dont_log_args,
    ):
        Resource.__init__(self)
        self.argument_cache = ArgumentCache(argument_cache_max_entries)
        self.ui_enabled = ui_enabled
        self.lua_enabled = lua_enabled
        self.browser_engines_enabled = browser_engines_enabled
        self.max_timeout = max_timeout
        self.dont_log_args = dont_log_args

        _kwargs = dict(
            pool=pool,
            max_timeout=max_timeout,
            argument_cache=self.argument_cache,
            browser_engines_enabled=browser_engines_enabled,
            dont_log_args=self.dont_log_args,
        )
        self.putChild(b"render.html", RenderHtmlResource(**_kwargs))
        self.putChild(b"render.png", RenderPngResource(**_kwargs))
        self.putChild(b"render.jpeg", RenderJpegResource(**_kwargs))
        self.putChild(b"render.json", RenderJsonResource(**_kwargs))
        self.putChild(b"render.har", RenderHarResource(**_kwargs))

        self.putChild(b"_debug", DebugResource(pool, self.argument_cache))
        self.putChild(b"_gc", ClearCachesResource(self.argument_cache))
        self.putChild(b"_ping", PingResource())

        # backwards compatibility
        self.putChild(b"debug",
                      DebugResource(pool, self.argument_cache, warn=True))

        if self.lua_enabled and ExecuteLuaScriptResource is not None:
            lua_kwargs = dict(
                sandboxed=lua_sandbox_enabled,
                lua_package_path=lua_package_path,
                lua_sandbox_allowed_modules=lua_sandbox_allowed_modules,
                strict=strict_lua_runner,
                **_kwargs,
            )
            self.putChild(
                b"execute",
                ExecuteLuaScriptResource(implicit_main=False, **lua_kwargs))
            self.putChild(
                b"run",
                ExecuteLuaScriptResource(implicit_main=True, **lua_kwargs))

        if self.ui_enabled:
            root = os.path.dirname(__file__)
            ui = File(os.path.join(root, 'ui'))

            har_path = os.path.join(root, 'vendor', 'harviewer', 'webapp')
            ui.putChild(to_bytes(HARVIEWER_PATH), File(har_path))
            inspections_path = os.path.join(root, 'kernel', 'inspections')
            ui.putChild(b"inspections", File(inspections_path))
            examples_path = os.path.join(root, 'examples')
            ui.putChild(b"examples", File(examples_path))

            self.putChild(b"_ui", ui)
            self.putChild(
                DemoUI.PATH,
                DemoUI(pool=pool,
                       lua_enabled=self.lua_enabled,
                       max_timeout=max_timeout))
Esempio n. 24
0
    def requestAvatar(self, avatarId, mind, *interfaces):

        if resource.IResource in interfaces:
            return resource.IResource, File(self.path), lambda: None

        raise NotImplementedError()
Esempio n. 25
0
 
 #Config
 wsPort = str(options.apiport)
 urlauth = "honey:"+HoneyProxy.getAuthKey()+"@" if HoneyProxy.getAuthKey() != "NO_AUTH" else ""
 httpGui = "http://"+urlauth+"localhost:"+str(options.guiport)+"/"
 guiURL = httpGui +"app/"
 HoneyProxy.setConfig({
     "proxy-addr":options.addr,
     "proxy-port":options.port,
     "ws-port": wsPort,
     "auth": HoneyProxy.getAuthKey(),
     "dumpdir": True if options.dumpdir else False
 })
 
 root = Resource()
 root.putChild("app",File(os.path.join(dirutils.honeyproxy_dir,"gui")))
 root.putChild("api",api.HoneyProxyApi())
 root.putChild("files", content.ContentAPIResource())
 if(options.dumpdir):
     root.putChild("dump", File(options.dumpdir))
 
 if HoneyProxy.getAuthKey() != "NO_AUTH":
     import libhproxy.auth as auth
     root = auth.addBasicAuth(root,"HoneyProxy",honey=HoneyProxy.getAuthKey())
 
 reactor.listenTCP(options.guiport, Site(root))  
     
 #HoneyProxy Master
 p = hproxy.HoneyProxyMaster(server, dumpoptions, guiSessionFactory)
 HoneyProxy.setProxyMaster(p)
 p.start()
Esempio n. 26
0
def static(request):
    return File("./static")
Esempio n. 27
0
class EchoServerProtocol(WebSocketServerProtocol):
    def onConnect(self, request):
        print("WebSocket connection request: {}".format(request))

    def onMessage(self, payload, isBinary):
        self.sendMessage(payload, isBinary)


if __name__ == '__main__':

    log.startLogging(sys.stdout)

    factory = WebSocketServerFactory("ws://127.0.0.1:8080")
    factory.protocol = EchoServerProtocol

    resource = WebSocketResource(factory)

    # we server static files under "/" ..
    root = File(".")

    # and our WebSocket server under "/ws" (note that Twisted uses
    # bytes for URIs)
    root.putChild(b"ws", resource)

    # both under one Twisted Web Site
    site = Site(root)
    reactor.listenTCP(8080, site)

    reactor.run()
Esempio n. 28
0
from twisted.web.static import File
from twisted.web.server import Site

application = Site(File('.'))
Esempio n. 29
0
            print("registered client {}".format(client.peer))
            self.clients.append(client)

    def unregister(self, client):
        if client in self.clients:
            print("unregistered client {}".format(client.peer))
            self.clients.remove(client)

    def broadcast(self, msg):
        print("broadcasting message '{}' ..".format(msg))
        for c in self.clients:
            c.sendMessage(msg.encode('utf8'))
            print("message sent to {}".format(c.peer))


if __name__ == '__main__':

    log.startLogging(sys.stdout)

    ServerFactory = RainBroadcastServerFactory
    # ServerFactory = BroadcastPreparedServerFactory

    factory = ServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = BroadcastServerProtocol
    listenWS(factory)

    webdir = File(".")
    web = Site(webdir)
    reactor.listenTCP(8080, web)

    reactor.run()
Esempio n. 30
0
 def _processTemplate(self, path, registry):
     file_name = os.path.splitext(os.path.basename(path))[0]
     if file_name in self.renderers:
         return TemplateResource(self.renderers[file_name])
     else:
         return File(path)