Exemple #1
0
def configValue(ks):
    config = getConfig()
    try:
        a = eval('config' + ks)
        return a
    except:
        return None
Exemple #2
0
    def verify(self):
        conf = getConfig()
        license = conf.license
        data = {}
        data.update(license)
        del data['rc']
        data = json.dumps(data).encode('ascii')
        rc = license.rc
        cnt = int(len(rc) / 2)
        signature = b''.join(
            [bytes.fromhex(rc[i * 2:i * 2 + 2]) for i in range(cnt)])
        verify_ok = False
        try:
            # 使用公钥对签名数据进行验证
            # 指定填充方式为PKCS1v15
            # 指定hash方式为sha256
            self.public_key.verify(signature, data, padding.PKCS1v15(),
                                   hashes.SHA256())
        # 签名验证失败会触发名为InvalidSignature的exception
        except InvalidSignature:
            # 打印失败消息
            print('invalid signature!')
        else:
            # 验证通过,设置True
            verify_ok = True

        # 返回验证结果
        return verify_ok
Exemple #3
0
 def getPeerPublickey(self, peername):
     pk = self.publickeys.get(peername)
     return pk
     config = getConfig()
     if config.publickeys:
         return config.publickeys.get(peername)
     return None
Exemple #4
0
 def getPrivateKey(self):
     if not hasattr(self, 'rsaEngine'):
         self.rsaEngine = RSA()
         self.conf = getConfig()
         fname = self.conf.website.rsakey.privatekey
         self.privatekey = self.rsaEngine.read_privatekey(fname)
     return self.privatekey
Exemple #5
0
 def serveri18n(s):
     lang = getHeaderLang(request)
     c = getConfig()
     g = ServerEnv()
     if not g.get('myi18n', False):
         g.myi18n = getI18N()
     l = c.langMapping.get(lang, lang)
     return g.myi18n(s, l)
Exemple #6
0
 def getIp(self):
     conf = getConfig()
     macs = [i for i in getAllMacAddress()]
     for m in macs:
         if m[0] == conf.license.mac:
             return m[1]
     print(conf.license.mac, macs)
     return '0.0.0.0'
Exemple #7
0
 def i18nDICT():
     c = getConfig()
     g = ServerEnv()
     if not g.get('myi18n', False):
         g.myi18n = getI18N()
     lang = getHeaderLang(request)
     l = c.langMapping.get(lang, lang)
     return json.dumps(g.myi18n.getLangDict(l))
Exemple #8
0
def setupTemplateEngine():
    config = getConfig()
    subffixes = [i[0] for i in config.website.processors if i[1] == 'tmpl']
    print(subffixes)
    paths = [os.path.abspath(p) for p in config.website.paths]
    loader = TmplLoader(paths, config.website.indexes, subffixes, inherit=True)
    engine = TemplateEngine(loader)
    g = ServerEnv()
    g.tmpl_engine = engine
 async def datahandle(self, request: Request):
     data = ''
     with codecs.open(self.path, 'rb', 'utf-8') as f:
         data = f.read()
     b = data
     b = self.urlreplace(b, request)
     ret = {"__widget__": "markdown", "data": {"md_text": b}}
     config = getConfig()
     self.content = json.dumps(ret, indent=4)
Exemple #10
0
 def __init__(self, auth_klass=AuthAPI, workdir=None):
     super().__init__()
     if workdir is not None:
         pp = ProgramPath()
         config = getConfig(workdir, {
             'workdir': workdir,
             'ProgramPath': pp
         })
     else:
         config = getConfig()
     if config.databases:
         DBPools(config.databases)
     initEnv()
     setupTemplateEngine()
     self.app = web.Application()
     auth = auth_klass()
     auth.setupAuth(self.app)
     self.configPath(config)
Exemple #11
0
def abspath(path):
    config = getConfig()
    paths = [os.path.abspath(p) for p in config.website.paths]
    for root in paths:
        p = root + path
        if os.path.exists(root + path):
            return p

    return None
Exemple #12
0
 async def path_call(self, request, path):
     dict_data = {}
     config = getConfig()
     with codecs.open(path, 'r', config.website.coding) as f:
         b = f.read()
         dict_data = json.loads(b)
     ns = self.run_ns
     act = ns.get('action', 'getdata')
     action = self.actions.get(act)
     return await action(dict_data, ns, request)
Exemple #13
0
 def get_source(self, env: Environment, template: str):
     config = getConfig()
     coding = config.website.coding
     fp = self.url2file(template)
     if not os.path.isfile(fp):
         raise TemplateNotFound(template)
     mtime = os.path.getmtime(fp)
     with codecs.open(fp, 'r', coding) as f:
         source = f.read()
     return source, fp, lambda: mtime == os.path.getmtime(fp)
Exemple #14
0
	def __init__(self):
		self.config = getConfig()
		self.rsaobj = RSA()
		self.nodeinfo = {}
		self.cpd = CenterPeerData(config.nodeid,config.privatekey)
		self.commands={
			"heartbeat":self.heartbeat,
			"getpeerinfo":self.getpeerinfo,
			"onlinelist":self.onlinelist,
		}
Exemple #15
0
 def getGetArgs(self, request: Request):
     ret = {}
     c = getConfig()
     coding = c.website.coding
     for k, v in request.args.items():
         k = k.decode(c.website.coding)
         if len(v) > 1:
             v = [i.decode(c.website.coding) for i in v]
         else:
             v = v[0].decode(c.website.coding)
         ret[k] = v
     return ret
Exemple #16
0
    def run(self):
        config = getConfig()
        ssl_context = None
        if config.website.ssl:
            ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            ssl_context.load_cert_chain(config.website.ssl.crtfile,
                                        config.website.ssl.keyfile)

        web.run_app(self.app,
                    host=config.website.host or '0.0.0.0',
                    port=config.website.port or 8080,
                    ssl_context=ssl_context)
Exemple #17
0
 def run(self):
     config = getConfig()
     ssock = None
     host = config.website.get('host', '0.0.0.0')
     port = config.website.get('port', 8080)
     if config.website.get('ssl', False):
         ssock = openSslSock(host, port, config.website.ssl.crtfile,
                             config.website.ssl.keyfile)
     self.app.run(debug=config.get('debug', True),
                  host=host,
                  port=port,
                  sock=ssock)
Exemple #18
0
 async def handle(self, request):
     config = getConfig()
     await self.datahandle(request)
     if self.retResponse is not None:
         return self.retResponse
     if type(self.content) == type({}):
         self.content = json.dumps(self.content, indent=4)
     if type(self.content) == type([]):
         self.content = json.dumps(self.content, indent=4)
     self.content = self.content if isinstance(
         self.content, bytes) else self.content.encode('utf-8')
     self.setheaders()
     return CachedResponse(self.content, headers=self.headers)
Exemple #19
0
 async def datahandle(self, request):
     dict_data = {}
     config = getConfig()
     with codecs.open(self.path, 'r', config.website.coding) as f:
         b = f.read()
         dict_data = json.loads(b)
     ns = DictObject()
     g = ServerEnv()
     ns.update(g)
     ns.update(self.resource.env)
     ns.update(self.resource.getGetArgs(request))
     act = ns.get('action', 'getdata')
     action = self.actions.get(act)
     self.content = action(dict_data, ns, request)
Exemple #20
0
def openfile(url, m):
    fp = abspath(url)
    if fp is None:
        print(f'openfile({url},{m}),url is not match a file')
        raise Exception('url can not mathc a file')
    config = getConfig()
    paths = [os.path.abspath(p) for p in config.website.paths]
    fs = config.get('allow_folders', [])
    fs = [os.path.abspath(i) for i in fs + paths]
    r = False
    for f in fs:
        if fp.startswith(f):
            r = True
            break
    if not r:
        raise FileOutZone(fp)
    return open(fp, m)
Exemple #21
0
 def __init__(self):
     workdir = programPath = ProgramPath()
     if len(sys.argv) > 1:
         workdir = sys.argv[1]
     config = getConfig(workdir, {
         'ProgramPath': programPath,
         'workdir': workdir
     })
     if config.get('databases'):
         DBPools(config.databases)
     initEnv()
     paths = [os.path.abspath(p) for p in config.website.paths]
     resource = BaseResource(paths, indexes=config.website.indexes)
     setupTemplateEngine()
     resource.indexes = config.website.indexes
     resource.processors = config.website.processors
     self.app = MyApp(static=resource)
     resource.app = self.app
Exemple #22
0
    def __init__(self):
        self.config = getConfig()
        self.peertasks = {}
        self.rsaobj = RSA()
        self.center_addr = gethostbyname(self.config.center), \
           self.config.port
        self.direct_addrs = {}

        self.cpd = NodePeerData(config.nodeid, config.privatekey)
        self.cpd.publickeys = {}
        self.local_ip = getlocalip()
        self.commands = {
            "greeting": self.greeting,
            "heartbeatresp": self.heartbeatresp,
            "getpeerinforesp": self.getpeerinforesp,
            "forwardmsg": self.forwardmsg,
            "peer_connect": self.peer_connect,
        }
Exemple #23
0
    def __init__(self):
        self.config = getConfig()
        self.rsaobj = RSA()
        self.nodeinfo = {}
        """
		nodeinfo 
		{
			nodeid:"fff",
			publickey:"ffkgrjgr",
			innerinfo:('192.168.1.22',19993),
			internetinfo:('xxx.xxx.xxx.xxx',22232),
			service:{
			}
		}
		"""
        self.cpd = CenterPeerData(config.nodeid, config.privatekey)
        self.commands = {
            "heartbeat": self.heartbeat,
            "getpeerinfo": self.getpeerinfo,
            "onlinelist": self.onlinelist,
        }
Exemple #24
0
def watch():
	workdir = ProgramPath()
	if len(sys.argv)>1:
		workdir = sys.argv[1]
	config = getConfig(workdir)
	observer = Observer()
	for m in config.monitors:
		handler = None
		if m.get('identify_by_ok'):
			print(curdt(),':','using OKFileHandler......')
			handler =OKFileHandler(m,config.peers)
		else:
			handler = FileEventHandler(m,config.peers)
		observer.schedule(handler,m.get('path'),True)
	observer.start()
	try:
		while True:
			yield from asyncio.sleep(1)

	except KeyboardInterrupt:
		observer.stop()
	observer.join()
Exemple #25
0
    def url2processor(self, request, url, fpath):
        config = getConfig()
        url = self.entireUrl(request, url)
        host = '/'.join(str(request.url).split('/')[:3])
        path = url[len(host):].split('?')[0]
        real_path = self.abspath(request, path)
        if config.website.startswiths:
            for a in config.website.startswiths:
                if path.startswith(a.leading):
                    processor = FunctionProcessor(path, self, a)
                    return processor

        if self.request_filename is None:
            self.error('%s:not found' % str(request.url))
            raise HTTPNotFound

        for word, handlername in self.y_processors:
            if fpath.endswith(word):
                Klass = getProcessor(handlername)
                processor = Klass(path, self)
                return processor
        return None
Exemple #26
0
 def getPeerPublickey(self, peername):
     return self.nodeinfo[peername].public_key
     config = getConfig()
     if config.publickeys:
         return config.publickeys.get(peername)
     return None
Exemple #27
0
            retdata.update(nodeinfo)
            retdata['cmd'] = 'getpeerinforesp'
        text = json.dumps(retdata)
        msg = self.cpd.setSendData(d.sender, text)
        self.send(msg, d.sender_addr)
        if nodeinfo is None:
            print(self.config.nodeid, 'getpeerinfo(),nodeinfo is none for',
                  d.peername)
            return
        forward = {
            "cmd": "forwardmsg",
            "forwardfrom": d.sender,
            "forwardto": d.peername,
            "forwarddata": self.nodeinfo.get(d.sender)
        }
        text = json.dumps(forward)
        msg = self.cpd.setSendData(d.peername, text)
        self.send(msg, tuple(nodeinfo.internetinfo))


if __name__ == '__main__':
    from appPublic.folderUtils import ProgramPath
    pp = ProgramPath()
    workdir = pp
    if len(sys.argv) > 1:
        workdir = sys.argv[1]
    config = getConfig(workdir, NS={'workdir': workdir, 'ProgramPath': pp})
    loop = asyncio.get_event_loop()
    server = serverFactory(CenterProtocol, '0.0.0.0', config.port)
    loop.run_forever()
Exemple #28
0
def appname():
    config = getConfig()
    try:
        return config.license.app
    except:
        return "test app"
Exemple #29
0
 def __init__(self):
     config = getConfig()
     self.root = config.filesroot or tempfile.gettempdir()
Exemple #30
0
    def on_created(self, event):
        print(self.__class__, 'on_create called')
        if event.is_directory:
            print("directory created:{0}".format(event.src_path))
            self.createdir(event.src_path)
        else:
            print('{0} created'.format(event.src_path))
            if endsWith(event.src_path.lower(), '.ok'):
                self.copyfile(event.src_path)


if __name__ == "__main__":
    workdir = ProgramPath()
    if len(sys.argv) > 1:
        workdir = sys.argv[1]
    config = getConfig(workdir)
    observer = Observer()
    for m in config.monitors:
        handler = None
        if m.get('identify_by_ok'):
            print('using OKFileHandler......')
            handler = OKFileHandler(m, config.peers)
        else:
            handler = FileEventHandler(m, config.peers)
        observer.schedule(handler, m.get('path'), True)
    observer.start()
    try:
        while True:
            time.sleep(0.01)
    except KeyboardInterrupt:
        observer.stop()