def receive_and_parse( self, sock ): try: # Received something on a client socket logging.debug( 'reciving from %s' % repr( sock ) ) try: str = unicode(sock.recv(4096), self.charset) except: logging.debug('recive from client error %s %s' % (trace(), repr(sock))) self.skipme.remove( sock ) return # Check to see if the peer socket closed if str == '': host,port = sock.getpeername() addr = '%s:%s' % (host, port) logging.debug ('disconnecting: %s..' % addr) self.emit('onDisconnected',addr) self.drop_user_by_addr(addr) else: # -- Recive up to 10 x 4096 from socket. If it still not empty - ignore it. i=10 while str[-1]!="|" and i>0: try: str=str+unicode(sock.recv(4096),self.charset) except: logging.debug('recive from client error %s' % trace()) self.skipme.remove( sock ) return i-=1 # -- logging.debug( 'parsing' ) host,port = sock.getpeername() addr = '%s:%s' % (host, port) logging.debug ('recived: %s from %s' % (str, addr)) if str[-1]=="|": if self.emit('onRecivedSomething',addr): logging.debug('Recived: %s' % str) if len(str)>0: msgarr=str.split('|') for i in msgarr: if i=="": pass elif i[0]=="$": self.parse_protocol_cmd(i,addr) else: self.parse_chat_msg(i,addr) else: logging.warning ( 'Too big or wrong message recived from %s: %s' % (addr,s) ) self.skipme.remove( sock ) except: self.drop_user_by_sock(sock) logging.debug('User Lost: %s' % trace())
def send_to_nick(self,nick,msg): if nick in self.nicks: if not (len(msg)>0 and msg[-1]=="|"): msg=msg+"|" try: logging.debug('senging %s to %s' % (msg, nick)) self.nicks[nick].descr.send(msg.encode(self.charset)) except: logging.debug('Error while sending %s to %s. Dropping. %s' % (msg,nick,trace())) self.drop_user_by_nick(nick) logging.debug('socket error %s. user lost!' % trace() ) else: logging.debug('send to unknown nick: %s' % nick)
def UnloadPlugin(self,addr,params=[]): # Params should be: 'plugin' logging.debug('unloading plugin') if len(params)==1: try: if params[0] in self.plugs: plug=self.plugs.pop(params[0]) plug.unload() for key in plug.commands.keys(): self.commands.pop(key,None) for key in plug.usercommands.keys(): self.usercommands.pop(key,None) for key, value in plug.slots.iteritems(): if key in self.slots: if value in self.slots[key]: self.slots[key].remove(value) self.Gen_UC() self.send_usercommands_to_all() return self._('Success') else: return self._('Plugin not loaded') except: return self._('Plugin unload error: %s' % trace()) else: return self._('Params error')
def AddForbid(self,addr,params=[]): #params ['regexp\nsource' 'action'] ''' add forbid element into list''' full=' '.join(params) full=full.split('\n',1) if len(full)!=2: return self.hub._('Params error') params=[] params.append(full[0]) params.extend(full[1].split(' ')) # params ['regexp' 'source' '...] if len(params)>=3: if params[1] in ['mc', 'pm', 'all']: action=' '.join(params[2:]) action=self.hub.unmasksyms(action) params[0]=self.hub.unmasksyms(params[0]) # -- checking regexp try: re.compile(params[0]) except: return self.hub._('Error %s' % trace()) self.regexps[params[0]]={'source':params[1],'action':action} self.recompile() else: return self.hub._('Params error: %s should be %s recived %s') % ('source', 'mc/pm/all', repr(params)) else: return self.hub._('Params error') return 'Success'
def clientserv(self, part): ''' listen for client sockets in descriptors[part]''' logging.debug('clientserv %s started!' % part) while self.work: try: if len(self.descriptors[part])>0: (sread, swrite, sexc) = select.select( self.descriptors[part], [], [], 1 ) else: time.sleep(1) sread=[] for sock in sread: if sock == None: continue #logging.debug( 'activity in socket %s' % repr( sock ) ) if sock not in self.skipme: # logging.debug( 'accepting activity' ) self.skipme.append( sock ) #Temporary remove socket, it will be served in separate thread parser=threading.Thread(None, self.receive_and_parse, 'Recive/Parse', (sock,)) parser.start() except: logging.debug( 'clientserv error %s' % trace() ) print('clientserv %s stopped!' % part) return
def run( self ): logging.info ('Hub started!') try: try: self.work=True self.pingthread=threading.Thread(None,self.pinger,'pinger',(120,)) self.autosaver=threading.Thread(None,self.settings_autosaver,'saver',(self.settings['core']['autosave'],)) self.pingthread.setDaemon(True) self.autosaver.setDaemon(True) self.pingthread.start() self.autosaver.start() while self.work: (sread, swrite, sexc) = select.select( self.srvsock, [], [], 1 ) for sock in sread: # Start new thread to avoid hub lock when user connecting newsock, (host, port) = sock.accept() connhandler=threading.Thread(None,self.accept_new_connection,'newConnection: %s %s' %(str(host), str(port)),(newsock, host, port)) connhandler.setDaemon(True) connhandler.start() #self.accept_new_connection() except: logging.error(trace()) self.on_exit() finally: # Save settings before exiting self.on_exit()
def parse_cmd(self,cmd,addr): logging.debug('command recived %s' % cmd) #cmd=self.decode(cmd) acmd=cmd.split(' ') ncmd=acmd[0] for j in self.commands: if acmd[0].lower() == j.lower(): ncmd=j if self.check_rights(self.addrs[addr],acmd[0]): if ncmd in self.commands: try: if (len(acmd[1:]))>0: result=self.commands[ncmd](addr,acmd[1:]) else: result=self.commands[ncmd](addr) if result!='': self.send_to_addr(addr,self._('<HUB> %s|') % result) except SystemExit: raise SystemExit except: self.send_to_addr(addr,self._('<HUB> Error while proccessing command %s|') % trace()) else: self.send_to_addr(addr,self._('<HUB> No such command')) else: self.send_to_addr(addr,self._('<HUB> Premission denied')) return
def queue_worker(self, ping_timer): if ping_timer > 0: ping_timer -= self.delay result = '' if not self.queue_lock: self.queue_lock = True msgs = self.queue self.queue = [] self.queue_lock = False if len(msgs)>0: for msg in msgs: logging.debug('sending to all %s' % msg) if not (len(msg)>0 and msg[-1]=="|"): msg += "|" result += msg if not result and ping_timer <= 0: # We should probably "ping" all connections if no messages to send ping_timer += self.ping_time logging.debug('pinging') result = '|' if result: logging.debug('senging "%s" to all' % result) for transport in self.transports: try: transport.write(result.encode(self.charset)) except: logging.debug('transport layer error %s' % trace()) reactor.callLater(0, self.drop_user_by_transport, transport) reactor.callLater(self.delay, self.queue_worker, ping_timer)
def _get_html(path: str) -> str: try: logging.info('getting html code') settings = ChromeOptions() settings.add_argument(f'user-data-dir={abspath("../cache")}') browser = Chrome('../resource/lib/chrome_driver.exe', options=settings) del settings browser.set_window_size(1920, 1080) browser.get(path) sleep(10) html = str(browser.page_source) browser.close() del browser logging.info('browser closed') return html except WebDriverException: trace(limit=1, file=stdout)
def error(ex): # return 500 with stack trace return { 'statusCode': 500, 'body': trace(), 'headers': { 'Content-Type': 'text/plain; charset=utf-8' } }
def get_permission_content(player, permnode, default_value = None): try: perms = player.getEffectivePermissions() for perm in perms: if str(perm.getPermission()).startswith(permnode): return str(perm.getPermission())[len(permnode):] return default_value except: error(trace())
def load_settings(self): logging.debug('reading settigs') try: for i in os.listdir(self.path_to_settings): if self.recp['.yaml'].search(i)!=None: mod=self.recp['before.yaml'].search(i).group(0) logging.debug('loading settings for %s' % mod) try: f=codecs.open(self.path_to_settings+'/'+ i,'r','utf-8') text=f.read() dct=yaml.load(text) if dct!=None: self.settings[mod]=dct except: logging.error('fail to load settings for module %s. cause:' % mod) logging.error('%s' % trace()) except: logging.error('error while loading settings: %s', trace())
def __exit__(self, exc_type, exc_inst, exc_tb): if exc_type is None: try: self.conn.commit() self.curs.close() self.conn.close() except: print(trace()) else: print(exc_tb)
def send_to_addr(self,addr,msg): if addr in self.addrs: if not (len(msg)>0 and msg[-1]=="|"): msg=msg+"|" try: self.addrs[addr].descr.send(msg.encode(self.charset)) except: logging.debug('socket error %s' % trace()) else: logging.warning('uknown addres: %s' % addr)
def get_aviable_plugins( self ): ans = [] try: for i in os.listdir(self.path_to_plugins): if self.recp['.py'].search(i)!=None and i!="__init__.py" and i!="plugin.py": mod=self.recp['before.py'].search(i).group(0) ans.append( mod ) return ans except: logging.error('error while listing plugins: %s', trace()) return ans
def Set(self,addr,params=[]): # Setting param for core or plugin # Params should be: 'core/plugin name' 'parameter' 'value' # Cause 'value' can contain spaces - join params[2:] if len(params)<2: return self._('Params error') try: value=yaml.load(" ".join(params[2:])) self.settings[params[0]][params[1]]=value return self._('Settings for %s - %s setted for %s') % (params[0], params[1], value) except: return self._('Error: %s') % trace()
def send_to_all(self, msg, omitSock=None): logging.debug('sending to all %s' % msg) if not (len(msg)>0 and msg[-1]=="|"): msg=msg+"|" for part in self.descriptors: for sock in part: if sock!=self.srvsock and sock!=omitSock: try: sock.send(msg.encode(self.charset)) except: logging.debug('socket error %s' % trace()) self.drop_user_by_sock( sock )
def emit(self,signal,*args): #logging.debug('emitting %s' % signal) #logging.debug('emit map %s' % repr(self.slots)) for slot in self.slots.get(signal,[]): logging.debug( 'Emitting: %s, for %s slot' % ( signal, repr( slot )) ) try: if not slot(*args): logging.debug( 'Emit %s: FALSE' % signal ) return False except: logging.error('PLUGIN ERROR: %s' % trace()) logging.debug( 'Emit %s: True' % signal ) return True
def drop_user(self, addr, nick, transport): logging.debug('dropping %s %s' % (addr, nick)) try: if transport in self.transports: self.transports.remove(transport) self.addrs.pop(addr,'') self.nicks.pop(nick,'') if transport in self.hello: self.hello.remove(transport) transport.loseConnection() except: logging.debug('something wrong while dropping client %s' % trace()) self.send_to_all('$Quit %s|' % nick) self.emit('onUserLeft',addr,nick)
def drop_user(self,addr,nick,sock): logging.debug('dropping %s %s %s' % (addr, nick, sock)) try: for i in self.descriptors: if sock in i: i.remove(sock) self.addrs.pop(addr,'') self.nicks.pop(nick,'') if sock in self.hello: self.hello.remove(sock) sock.close() except: logging.debug('something wrong while dropping client %s' % trace()) logging.debug ('Quit %s' % nick) self.send_to_all('$Quit %s|' % nick) self.emit('onUserLeft',addr,nick)
def print_list(sender, closed): try: # new thread, anything can happen. targeted_reports = dict(enumerate(reports)) for i in list(targeted_reports): report = targeted_reports[i] if report["closed"] != closed: targeted_reports.pop(i) msg(sender, "&a%s %s reports:" % (len(targeted_reports), "closed" if closed else "open")) for i in targeted_reports: report = targeted_reports[i] name = retrieve_player(report["uuid"]).getName() msg(sender, "&8[&e%s &c%s&8] &3%s&f: &a%s" % (i, report["time"], name, report["msg"])) except: warn("Failed to complete report's print_list() thread") error(trace())
def save_settings(self): logging.debug('saving settigs') try: for mod, sett in self.settings.items(): try: logging.info('saving settings for %s' % mod) f=open(self.path_to_settings+'/'+mod+'.yaml','wb') f.write(yaml.safe_dump(sett,default_flow_style=False,allow_unicode=True)) except: logging.error('failed to load settings for module %s. cause:' % mod) logging.error('%s' % trace()) return False except: logging.error('!!! SETTINGS NOT SAVED !!!') return False return True
def AddPlugin(self,addr,params=[]): ans=[] try: for i in os.listdir(self.hub.path_to_plugins): if self.hub.recp['.py'].search(i)!=None and i!="__init__.py" and i!="plugin.py": mod=self.hub.recp['before.py'].search(i).group(0) ans.append(mod) if params[0] in ans: self.hub.core_settings['autoload'].append(params[0]) self.hub.Gen_UC() self.hub.send_usercommands_to_all() return self.hub._('Success') else: return self.hub._('No plugin') except: logging.error('error while listing plugins: %s', trace())
def LoadPlugin(self,addr,params=[]): # Params should be: 'plugin' if len(params)==1: logging.debug('loading plugin %s' % params[0]) if params[0] not in self.plugs: try: if not '.' in sys.path: sys.path.append('.') if 'plugins.'+params[0] not in sys.modules: plugins=__import__('plugins.'+params[0]) plugin=getattr(plugins,params[0]) else: plugin=reload(sys.modules['plugins.'+params[0]]) logging.getLogger().setLevel(self.settings['core']['loglevel']) logging.debug('loaded plugin file success') cls=getattr(plugin,params[0]+'_plugin') obj=cls(self) self.plugs[params[0]]=obj self.commands.update(obj.commands) #self.usercommands.update(obj.usercommands) logging.debug( 'Plugin %s slots: %s' % (params[0], repr( obj.slots ) ) ) for key,value in obj.slots.iteritems(): logging.debug( 'Activating Slot: %s, on plugin %s' % ( key, params[0] ) ) if key in self.slots: self.slots[key].append(value) else: self.slots[key]=[value] logging.debug( 'MessageMap: %s' % repr( self.slots )) self.Gen_UC() self.send_usercommands_to_all() return self._('Success') except: e=trace() logging.debug( 'Plugin load error: %s' % (e,) ) return self._( 'Plugin load error: %s' % (e,) ) else: return self._('Plugin already loaded') else: return self._('Params error')
def print_list(sender, closed): try: # new thread, anything can happen. targeted_reports = dict(enumerate(reports)) for i in list(targeted_reports): report = targeted_reports[i] if report["closed"] != closed: targeted_reports.pop(i) msg( sender, "&a%s %s reports:" % (len(targeted_reports), "closed" if closed else "open")) for i in targeted_reports: report = targeted_reports[i] name = retrieve_player(report["uuid"]).getName() msg( sender, "&8[&e%s &c%s&8] &3%s&f: &a%s" % (i, report["time"], name, report["msg"])) except: warn("Failed to complete report's print_list() thread") error(trace())
self.setTimeout(None) def timeoutConnection(self): """ Called when the connection times out. """ logging.debug('timeout: %s' % self._addr) self.write('<HUB> Login timeout!|') self.transport.loseConnection() def on_exit(self): self.work=False self.save_settings() sys.exit() #RUNNING HUB #application = service.Application('DirectConnect Hub') hub = DCHub() hub.protocol = DCProtocol for i in hub.core_settings['port']: try: #internet.TCPServer(i, hub).setServiceParent(application) reactor.listenTCP(i, hub) logging.debug('Started on port %d' % i) except: logging.error('---- A PROBLEM WHILE BINDING TO PORT: %s \n %s----' % (i, trace(),) ) reactor.run()
def accept_new_connection( self, newsock, host, port ): if len( self.nicks ) >= self.core_settings['max_users']: newsock.close() logging.warning( 'MAX USERS REACHED!!!' ) return try: addr='%s:%s' % (host, port) logging.debug ('connecting: %s' % addr) if self.emit('onConnecting', addr): newsock.send('$Lock %s|$HubName %s|<HUB> Hub is powered by ViperHive [ http://dc.hovel.ru http://code.google.com/p/viperhive/ ]|' % ( self.LOCK , self.core_settings['hubname'].encode(self.charset) ) ) (sock, sw, sx)=select.select([newsock],[],[],15) logging.debug(repr(sock)) if sock!=[]: newsock.settimeout(5.0) s=unicode(newsock.recv(4096),self.charset) supports=self.recp['Supports'].search(s) if supports!=None: supports=supports.group(0) else: supports='' #clisup=[] validated=True logging.debug('Supports: %s' % supports) #if supports!=None: # #Normal clients should support this # supports=supports.group(0) # logging.debug('client supports: %s' % supports) # if self.recp['NoGetINFO'].search(supports)!=None: # clisup.append('NoGetINFO') # if self.recp['NoHello'].search(supports)!=None: # clisup.append('NoHello') nick=self.recp['ValidateNick'].search(s) #checking nick # if nick == None => something like microdc2 if nick==None: logging.debug('Old client: %s' %s) newsock.send('$Supports %s|' % self.SUPPORTS) (sock, sw, sx)=select.select([newsock],[],[],15) if sock!=[]: s+=unicode(newsock.recv(4096),self.charset) nick=self.recp['ValidateNick'].search(s) logging.debug('Old client full: %s' %s) #checking nick if nick!=None: nick=nick.group(0) logging.debug('validating: %s' % nick) if nick in self.reglist: # if user registred, and passwd is correct # we should connect it even if it's already connected (drop & connect) newsock.send('$GetPass|') (sock, sw, sx)=select.select([newsock],[],[],15) if sock!=[]: s+=unicode(newsock.recv(4096),self.charset) passw=self.recp['MyPass'].search(s) if passw!=None: passw=passw.group(0) logging.debug('MyPass %s' % passw) if passw!=self.reglist[nick]['passwd']: logging.info('wrong pass') newsock.send(('<HUB> %s|' % (self._('Password incorrect. Provided: %s') % str(passw),)).encode(self.charset)) newsock.send('$BadPass|') validated=False else: if nick in self.nicks: logging.debug('reconnecting identified user') try: self.nicks[nick].descr.send('<HUB> youre connecting from different machine. bye.|') except: pass self.drop_user_by_nick(nick) else: validated=False else: validated=False else: # if nick in self.reglist #nick is not registred if nick in self.nicks: newsock.send('ValidateDenie') validated=False else: validated=True else: validated=False if validated: logging.debug ('validated %s' % nick) newsock.send('$Hello %s|' % nick.encode(self.charset)) newsock.send('$Supports %s|' % self.SUPPORTS) #for i in self.hello: # i.send('$Hello %s|' % nick) k=3 while (not 'MyINFO' in s) and (k>0): (sock, sw, sx)=select.select([newsock],[],[],15) if sock!=[]: s+=unicode(newsock.recv(4096),self.charset) k=k-1 info=self.recp['MyINFO'].search(s) if info!=None: tr=True info=info.group(0) try: user=DCUser(info,newsock,addr) except: logging.warning( 'wrong myinfo from: %s addr: %s info: %s %s' % ( nick, addr, info, trace() ) ) tr=False if tr: if nick in self.reglist: user.level=self.reglist[nick]['level'] else: user.level='unreg' self.nicks[nick]=user self.addrs[addr]=user try: # --- APPLY LIMITS --- if user.share < self.core_settings['min_share'] and user.level not in self.core_settings['pass_limits']: newsock.send( (self._( '<HUB> Too low share. Min share is %s.|' ) % number_to_human_size( self.core_settings['min_share'] ) ).encode( self.charset ) ) logging.debug('not validated. dropping') self.drop_user(addr, nick, newsock) return if user.sum_hubs > self.core_settings['max_hubs'] and user.level not in self.core_settings['pass_limits']: newsock.send( (self._( '<HUB> Too many hubs open. Max hubs is %s.|' ) % self.core_settings['max_hubs']).encode( self.charset ) ) logging.debug('not validated. dropping') self.drop_user(addr, nick, newsock) return if user.slots < self.core_settings['min_slots'] and user.level not in self.core_settings['pass_limits']: newsock.send( (self._( '<HUB> Too few slots open. Min slots is %s.|' ) % self.core_settings['min_slots']).encode( self.charset ) ) logging.debug('not validated. dropping') self.drop_user(addr, nick, newsock) return logging.debug('slots: %s, hubs: %s' % (user.slots, user.hubs) ) if self.emit('onConnected',user): logging.debug('Validated. Appending.') free=None # No free workers for i, val in enumerate(self.descriptors): # Search for free worker if len(val)<self.WORKER_MAX: val.append(newsock) free=i break if free==None: #adding worker logging.info('Many users. Appending worker') self.descriptors.append([newsock]) try: newthread=(threading.Thread(None,self.clientserv,'worker',(len(self.descriptors)-1,))) logging.debug(newthread.getName()) newthread.setDaemon(True) newthread.start() except: logging.error(trace()) self.clthreads.append(newthread) if user.level in self.oplevels: self.send_to_all(self.get_op_list()) if not 'NoHello' in supports: self.hello.append(newsock) if not 'NoGetINFO' in supports: newsock.send(self.get_nick_list().encode( self.charset )) #newsock.send(self.get_op_list().encode( self.charset )) else: for i in self.nicks.values(): newsock.send(i.MyINFO.encode(self.charset)+"|") newsock.send(self.get_op_list().encode(self.charset)) self.send_to_all(info+"|") uips=self.get_userip_acc_list() if ('UserIP' in supports) or ('UserIP2' in supports): self.send_to_nick(nick, '$UserIP %s %s$$|' %(nick, user.get_ip())) if user.level in self.core_settings['userip']: self.send_to_nick(nick, self.get_userip_list()) for unick in uips: self.send_to_nick(unick, '$UserIP %s %s$$|' %(nick, user.get_ip())) self.send_usercommands_to_nick(nick) self.send_to_nick(nick, '$HubTopic %s|' % self.core_settings['topic']) #logging.debug (repr(self.nicks)) #logging.debug (repr(self.addrs)) else: logging.debug('not validated. dropping') self.drop_user(addr, nick, newsock) except: logging.debug('error while connect: %s' % trace()) self.drop_user(addr, nick, newsock) else: logging.debug('no MyINFO recived\n recived: %s' % s) newsock.close() else: logging.debug('not validated nick. dropping.') newsock.close() else: logging.debug('timeout: %s' % addr) newsock.send('login timeout') newsock.close() else: logging.debug('Connectin not allowed by plugins') logging.debug('handheld complite with %s' % nick) except: logging.debug('Unexpected error: %s' % trace()) return
def parse_protocol_cmd(self,cmd,addr): acmd=cmd.split(' ') if acmd[0]=='$GetINFO': if len(acmd)==3: if self.addrs[addr].nick==acmd[2] and self.nicks.has_key(acmd[1]): if self.emit('onGetINFO',acmd[1],acmd[2]): logging.debug('send myinfo %s' % self.nicks[acmd[1]].MyINFO) self.send_to_nick(acmd[2],self.nicks[acmd[1]].MyINFO+"|") elif acmd[0]=='$MyINFO': if len(acmd)>=3: if self.addrs[addr].nick==acmd[2]: try: self.nicks[acmd[2]].upInfo(cmd) if self.emit('onMyINFO',cmd): self.send_to_all(cmd+"|") except: logging.warning( 'Wrong MyINFO by: %s with addr %s: %s' ( acmd[2], addr, trace() ) ) self.drop_user_by_addr(addr) elif acmd[0]=='$To:': if len(acmd)>5: if acmd[3]==self.addrs[addr].nick==acmd[4][2:-1]: if acmd[1] in self.nicks: tocmd=cmd.split(' ',5) if self.emit('onPrivMsg',acmd[3],acmd[1],tocmd[5]): self.send_to_nick(acmd[1],cmd+"|") elif acmd[0]=='$ConnectToMe': if len(acmd)==3: if acmd[2].split(':')[0]==addr.split(':')[0]: if self.emit('onConnectToMe',addr,acmd[1]): self.send_to_nick(acmd[1],cmd+"|") elif acmd[0]=='$RevConnectToMe': if len(acmd)==3: if acmd[1] in self.nicks: if self.addrs[addr].nick==acmd[1]: if self.emit('onRevConnectToMe',acmd[1],acmd[2]): self.send_to_nick(acmd[2],cmd+"|") elif acmd[0]=='$Search': if len(acmd)>=3: srcport=acmd[1].split(':') if len(srcport)==2: if srcport[0]=='Hub': #Passive Search if srcport[1]==self.addrs[addr].nick: bcmd=cmd.split(' ',2) if self.emit('onSearchHub',bcmd[1],bcmd[2]): self.send_to_all(cmd+"|",self.addrs[addr].descr) else: #Active Search if srcport[0]==self.addrs[addr].addr.split(':')[0]: bcmd=cmd.split(' ',2) if self.emit('onSearch',bcmd[1],bcmd[2]): self.send_to_all(cmd+"|",self.addrs[addr].descr) elif acmd[0]=='$SR': fcmd=cmd.split(chr(5)) if len(fcmd)==4: if len(acmd)>=3: sender=acmd[1] reciver=fcmd[3] if self.addrs[addr].nick==sender: if self.emit('onSearchResult',sender,reciver,cmd): self.send_to_nick(reciver,cmd+"|") elif acmd[0] == '$GetNickList': self.send_to_addr( addr, self.get_nick_list() ) elif acmd[0]=='$HubINFO' or acmd[0]=='$BotINFO': hubinfo='$HubINFO ' info=self.core_settings['hubinfo'] hubinfo+='%s$' % self.core_settings['hubname'] hubinfo+='%s:%s$' % ( info.get('address',''), self.core_settings['port'][0] ) hubinfo+='%s$' % info.get('description','') hubinfo+='%s$' % self.core_settings.get('max_users','10000') hubinfo+='%s$' % self.core_settings.get('min_share','0') hubinfo+='%s$' % self.core_settings.get('min_slots','0') hubinfo+='%s$' % self.core_settings.get('max_hubs','1000') hubinfo+='%s$' % info.get('type','') hubinfo+='%s$' % info.get('owner','') hubinfo+='|' self.send_to_addr( addr,hubinfo ) else: logging.debug('Unknown protocol command: %s from: %s' % (cmd,addr)) return
def _get_test_html(path: str) -> str: try: with open(path, 'r', encoding='utf-8') as file: return str(file.read()) except FileNotFoundError: trace(limit=1, file=stdout)
def parseMsg(self, from_nick, message, source): #if source=='mc': # msg=' '.join(params[1:]) #else: # msg=' '.join(params[2:]) if self.hub.nicks[from_nick].level in self.immune: # user immuned return True logging.debug('parsing in forbid') for i in self.res: if i.search(message)!=None: #GOTCHA! logging.debug('forbid signal') if self.regexps[i.pattern]['source']==source or self.regexps[i.pattern]['source']=='all': action=self.regexps[i.pattern]['action'] logging.debug('trigger %s found %s in %s' % (i.pattern,i.search(message).group(0),message)) # -- specical actions! if action=='ignore': return False action=action.replace('%[nick]',from_nick) actions=action.split('|') for i in actions: acmd=i.split(' ') try: addr=self.hub.nicks[from_nick].addr if (len(acmd[1:]))>0: result=self.hub.commands[acmd[0]](addr,acmd[1:]) else: result=self.hub.commands[acmd[0]](addr) if result!='': if from_nick in self.hub.nicks: self.hub.send_to_addr(self.hub.nicks[from_nick].addr,self.hub._('<HUB> %s|') % result) except: logging.error('error in forbid module: %s' % trace()) return False else: #no, different channel return True return True
def __init__( self ): # COMMANDS self.commands={} # SIGNAL-SLOT EVENT SUBSYSTEM self.slots={} # COMPILE REGEXPS self.recp={} self.recp['Key']=re.compile('(?<=\$Key )[^|]*(?=[|])') self.recp['ValidateNick']=re.compile('(?<=\$ValidateNick )[^|]*(?=[|])') self.recp['Supports']=re.compile('(?<=\$Supports )[^|]*(?=[|])') self.recp['MyPass']=re.compile('(?<=\$MyPass )[^|]*(?=[|])') self.recp['MyINFO']=re.compile('\$MyINFO [^|]*(?=[|])') self.recp['NoGetINFO']=re.compile('NoGetINFO') self.recp['NoHello']=re.compile('NoHello') self.recp['.yaml']=re.compile('\.yaml$') self.recp['before.yaml']=re.compile('.*(?=\.yaml)') self.recp['.py']=re.compile('\.py$') self.recp['before.py']=re.compile('.*(?=\.py)') self.recp['tag']=re.compile('[<](.*)[>]$') # SET PATHS self.path_to_settings="./settings/" self.path_to_plugins="./plugins/" # ----- SETTINGS ----- self.settings={} # LOADING SETTINGS self.load_settings() # SHORTCUTS self.core_settings=self.settings.get('core',{}) self.reglist=self.settings.get('reglist',{}) self.privlist=self.settings.get('privlist',{}) # DEFAULTS defcore_settings={} defcore_settings['port']=[411] defcore_settings['hubname']='Viperhive powered hub' defcore_settings['topic']='Viperhive powered hub' defcore_settings['cmdsymbol']='!' defcore_settings['OpLevels']=['owner'] defcore_settings['Protected']=['owner', 'op'] defcore_settings['Lang']='ru.cp1251' defcore_settings['autoload']=['ban', 'mute', 'forbid', 'say', 'motd', 'regme'] defcore_settings['loglevel']=10 defcore_settings['autosave']=120 defcore_settings['userip']=['owner', 'op'] # ---- LIMITS ---- defcore_settings['max_users'] = 10000 defcore_settings['min_share'] = 0 defcore_settings['max_hubs'] = 1000 defcore_settings['min_slots'] = 0 defcore_settings['pass_limits'] = ['owner', 'op', 'chatroom'] defcore_settings['hubinfo']={'address':'example.com','description':'Viperhive powered hub','type':'ViperHive Hub', 'hubowner':'owner'} defreglist={'admin':{'level':'owner', 'passwd':'megapass'}} defprivlist={'owner':['*']} # If loaded core_settings miss some stuff - load defaults if len(self.core_settings)==0: self.settings['core']=self.core_settings={} for i in defcore_settings.keys(): if not i in self.core_settings: self.core_settings[i]=defcore_settings[i] #------UPDATE SETTINGS FROM OLD VERSION:------- # UPDATE PORT SETTINGS FOR VERSIONS <= svn r168 if not isinstance( self.core_settings['port'], list ): self.core_settings['port'] = [ self.core_settings['port'] ] if len(self.reglist)==0: self.settings['reglist']=self.reglist=defreglist if len(self.privlist)==0: self.settings['privlist']=self.privlist=defprivlist # MORE SHORTCUTS self.oplevels=self.core_settings['OpLevels'] self.protected=self.core_settings['Protected'] self.KEY=lock2key(self.LOCK) # ---- SOCKETS ---- self.srvsock = [] for i in self.core_settings['port']: try: sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) sock.bind( ("", i) ) sock.listen( 5 ) self.srvsock.append( sock ) except: logging.error('---- A PROBLEM WHILE BINDING TO PORT: %s \n %s----' % (i, trace(),) ) #self.descriptors = [[self.srvsock]] self.descriptors=[] # User hashes self.nicks={} self.addrs={} # Support for very, VERY old clients self.hello=[] self.getinfo=[] self.clthreads=[] # Reinitialize Logging logging.debug('Set logging level to %s' % str(self.settings['core']['loglevel'])) reload(sys.modules['logging']) logging.getLogger().setLevel(self.settings['core']['loglevel']) # REGISTERING CORE COMMANDS self.commands['Quit']=self.Quit #Usercommands + self.commands['AddReg']=self.AddReg #Usercommands + self.commands['DelReg']=self.DelReg #Usercommands + self.commands['ListReg']=self.ListReg #Usercommands + self.commands['Get']=self.Get #Usercommands + self.commands['Set']=self.Set #Usercommands + self.commands['SetLevel']=self.SetLevel #Usercommands + self.commands['Help']=self.Help #Usercommands + self.commands['ListPlugins']=self.ListPlugins #Usercommands + self.commands['LoadPlugin']=self.LoadPlugin #Usercommands + self.commands['UnloadPlugin']=self.UnloadPlugin #Usercommands + self.commands['ActivePlugins']=self.ActivePlugins #Usercommands + self.commands['Save']=self.Save #Usercommands + self.commands['ReloadPlugin']=self.ReloadPlugin self.commands['RP']=self.ReloadPlugin #Usercommands + self.commands['Passwd']=self.Passwd self.commands['PasswdTo']=self.PasswdTo #Usercommands + self.commands['Kick']=self.Kick #Usercommands + self.commands['UI']=self.UI #Usercoommands + self.commands['SetTopic']=self.SetTopic #Usercommands + self.commands['RegenMenu'] = self.RegenMenu #Usercommands + self.commands['ReloadSettings'] = self.ReloadSettings #Usercommands + # TRANSLATION SYSTEM self.lang={} # Current language array self.help={} # Help for current language # -- LOADING LANGUAGE lang=self.core_settings['Lang'].split('.')[0] self.charset=cpage=self.core_settings['Lang'].split('.')[1] try: lpath='./languages/'+lang+'/' lfiles=os.listdir(lpath) for i in lfiles: # LOAD MESSAGES FOR CURRENT LANGUAGE if self.recp['.yaml'].search(i)!=None: try: arr=yaml.load(codecs.open(lpath+i,'r','utf-8').read()) #for key,value in arr.iteritems(): # arr[key]=value.encode(cpage) self.lang.update(arr) except: logging.error('file %s in wrong format: %s' % ((lpath+i), trace())) if 'help' in lfiles: # LOAD HELP FOR CURRENT LANGUAGE hpath=lpath+'help/' hfiles=os.listdir(hpath) for i in hfiles: if self.recp['.yaml'].search(i)!=None: try: arr=yaml.load(codecs.open(hpath+i,'r','utf-8').read()) #for key,value in arr.iteritems(): # arr[key]=value.encode(cpage) self.help.update(arr) except: logging.error('file %s in wrong format: %s' % ((lpath+i), trace())) except: logging.error('language directory not found %s' % (trace())) logging.info('Language loaded: %s strings' % str(len(self.lang))) logging.info('Help loaded: %s strings' % str(len(self.help))) # PLUGINS self.plugs={} self.Gen_UC() # AUTOLOAD PLUGINS for i in self.core_settings['autoload']: self.LoadPlugin(None,[i]) logging.info ('Hub ready to start on port %s...' % self.core_settings['port']) self.skipme=[]
def wrap(*args, **kwargs): try: return func(*args, **kwargs) except: error(trace()) return None
def run( self, newparser=None ): logging.debug( 'RUNNING PYDCPPBOT MESSAGE PARSER' ) self.work=True self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.HOST,self.PORT)) lock=self.sock.recv(1024) lock_key=re.findall('\$Lock[\s](.*?)[\s]', lock)[0] key =self._createKey(lock).encode("utf-8") self.sock.send('$Key %s|$ValidateNick %s|'%(key,self.NICK.encode( self.charset ))) self.sock.recv(4096) if self.PASS == None: self.sock.send(('$Version 1,0091|$GetNickList|$MyINFO $ALL %s %s%s$ $0$$%s$|' % (self.NICK,self.DESCR,self.TAG,self.SHARE)).encode( self.charset )) else: self.sock.send( ('$Version 1,0091|$MyPass %s|$GetNickList|$MyINFO $ALL %s %s%s$ $0$$%s$|' %(self.PASS,self.NICK,self.DESCR,self.TAG,self.SHARE) ).encode( self.charset )) if newparser != None: logging.debug ( 'New paserr defined' ) self.parser=newparser logging.debug( 'Bot parser: %s' % repr(self.parser) ) self.sock.settimeout(5) self.sock.send( '$BotINFO|' ) while self.work: try: s = '' (sr,sw,sx)=select.select([self.sock],[],[],1) if sr==[]: continue try: s = unicode(self.sock.recv(4096), self.charset) except: logging.error( '%s \nString recived: %s' % (trace(), s) ) continue if s == '': # connection break logging.error( 'pydcppbot: connection lost' ) break # check if message too long? k=5 while s[-1] != '|' and k > 0: (sr,sw,sx)=select.select([self.sock],[],[],1) if sr == []: logging.error( 'pydcppbot eror: String recived: %s' % (s,) ) break try: s += unicode(self.sock.recv(4096), self.charset) except: logging.error( '%s \nString recived: %s' % (trace(), s) ) continue if s[-1] != '|': continue logging.debug( 'pydcppbot - parsing: %s' % s ) self.parser( s ) except: logging.error( trace() ) self.work = False break self.sock.send('$Quit|') self.sock.close() return
def parse_negotiate_cmd(self, cmd): acmd = cmd.split(' ', 1) if acmd[0] == '$MyINFO': try: user=DCUser(cmd, self.transport, self._addr) except: logging.warning( 'wrong myinfo from: %s addr: %s info: %s %s' % ( self._nick, self._addr, cmd, trace() ) ) else: if self._nick in self.factory.reglist: user.level=self.factory.reglist[self._nick]['level'] else: user.level='unreg' self.factory.nicks[self._nick] = user self.factory.addrs[self._addr] = user try: # --- APPLY LIMITS --- if user.share < self.factory.core_settings['min_share'] and user.level not in self.factory.core_settings['pass_limits']: self.write( (self._( '<HUB> Too low share. Min share is %s.|' ) % number_to_human_size( self.factory.core_settings['min_share'] ) ).encode( self.factory.charset ) ) logging.debug('not validated. dropping') self.factory.drop_user(self._addr, self._nick, self.transport) return if user.sum_hubs > self.factory.core_settings['max_hubs'] and user.level not in self.factory.core_settings['pass_limits']: self.write( (self._( '<HUB> Too many hubs open. Max hubs is %s.|' ) % self.factory.core_settings['max_hubs']).encode( self.factory.charset ) ) logging.debug('not validated. dropping') self.factory.drop_user(self._addr, self._nick, self.transport) return if user.slots < self.factory.core_settings['min_slots'] and user.level not in self.factory.core_settings['pass_limits']: self.write( (self._( '<HUB> Too few slots open. Min slots is %s.|' ) % self.factory.core_settings['min_slots']).encode( self.factory.charset ) ) logging.debug('not validated. dropping') self.factory.drop_user(self._addr, self._nick, self.transport) return logging.debug('slots: %s, hubs: %s' % (user.slots, user.hubs) ) if self.factory.emit('onConnected',user): logging.debug('Validated. Appending.') self.factory.transports.append(self.transport) if user.level in self.factory.oplevels: self.write('$LogedIn|') self.factory.send_to_all(self.factory.get_op_list()) if not 'NoHello' in self._supports: self.factory.hello.append(self.transport) if not 'NoGetINFO' in self._supports: self.write(self.factory.get_nick_list().encode( self.factory.charset )) else: for i in self.factory.nicks.values(): self.write(i.MyINFO.encode(self.factory.charset)) self.write(self.factory.get_op_list().encode(self.factory.charset)) self.factory.send_to_all(cmd) uips=self.factory.get_userip_acc_list() if ('UserIP' in self._supports) or ('UserIP2' in self._supports): self.factory.send_to_nick(self._nick, '$UserIP %s %s$$' %(self._nick, user.get_ip())) if user.level in self.factory.core_settings['userip']: self.factory.send_to_nick(self._nick, self.factory.get_userip_list()) for unick in uips: self.factory.send_to_nick(unick, '$UserIP %s %s$$' %(self._nick, user.get_ip())) self.factory.send_usercommands_to_nick(self._nick) self.factory.send_to_nick(self._nick, '$HubTopic %s' % self.factory.core_settings['topic']) else: logging.debug('not validated. dropping') self.factory.drop_user(self._addr, self._nick, self.transport) return except: logging.debug('error while connect: %s' % trace()) self.factory.drop_user(self._addr, self._nick, self.transport) return self._state = 'logedin' self.setTimeout(None)