Exemplo n.º 1
0
class Database():
    '''
    INFO: ALWAYS close the Instans to close the Connection
    '''
    def __init__(self):
        self.log = Logging()
        self.log.debug('Database instance has been created')

    def initialize_data(self):
        pass

    #initialize_connection
    def get_connection(self):
        config = Config()
        config.initialize()
        try:
            connection = pymysql.connect(
                host=config.get_host(),
                port=config.get_port(),
                user=config.get_user(),
                password=config.get_pass(),
                db=config.get_database_name(),
                cursorclass=pymysql.cursors.DictCursor)
            return connection

        except pymysql.Error as Error:
            self.log.warning('Database - initialize_connection\n' +
                             'Config: ' + str(config.get_host()) + ' - ' +
                             str(config.get_port()) + ' - ' +
                             str(config.get_user()) + ' - ' +
                             str(config.get_pass()) + ' - ' +
                             str(config.get_database_name()) +
                             '\nDatabase - inicon - Something went wrong: {}'.
                             format(str(Error)))
            return False
Exemplo n.º 2
0
class MapData(DAO):

    def __init__(self):
        self.log = Logging()

    def load(self):
        '''
        DataFrame:

        '''
        self.dataSource = []
        connection = dataSource.Database().get_connection()
        cursor = connection.cursor()
        try:
            cursor.execute('SELECT * FROM accounts;')
            data = cursor.fetchall()
            for row in data:
                self.dataSource.append(row)
        except Exception as Error:
            self.log.warning(' account_data.py - Can\'t load table accounts')
            self.log.warning(str(Error))
        finally:
            cursor.close()
            connection.close()

    def get_map_data(self):
        print('bin ich hier ?????')
        return self.dataSource
Exemplo n.º 3
0
    def __init__(self, c, ipbans):
        self.log = Logging()
        client = c
        # We send the first package (HC + KEY + empty byte)
        client.write('HC' + client.get_key())

        # We are waiting for the client version
        data = client.get_io_session().recv(2048)
        msg = data.decode()
        if not (msg == '1.30.9\n\x00' or msg == '1.29.1\n\x00'
                or msg == '1.30.0\n\x00' or msg == '1.31.2\n\x00'):
            self.log.debug('[' + str(client.get_address()[0]) + ':' +
                           str(client.get_address()[1]) + '][' +
                           str(client.get_status().name) +
                           '] The client has the wrong version - ' + '(' +
                           str(msg.split('\n')[0]) + ')')
            # TODO wrong text window is displayed "Invalid login or password."
            client.write('AlEf')
            sys.exit(0)
        for i in ipbans:
            if client.get_address()[0] == i['ip']:
                self.log.debug('[' + str(client.get_address()[0]) + ':' +
                               str(client.get_address()[1]) + ']' + '[' +
                               str(client.get_status().name) + '] ' +
                               'This IP is banned')
                client.write('AlEb')
                client.kick()
        self.log.debug('[' + str(client.get_address()[0]) + ':' +
                       str(client.get_address()[1]) + '][' +
                       str(client.get_status().name) + '] Version accepted ' +
                       '(' + str(msg.split('\n')[0]) + ')')
        return
Exemplo n.º 4
0
class ExchangeClient():

    def __init__(self):
        self.log = Logging()

    def send(self, i):
        msg = bytes(i, 'utf-8')
        self.log.debug('[{}:{}][EX-SEND->] {}'.format(str(self.addr[0]),
                                                str(self.addr[1]),
                                                i))               
        self.IoSession.send(msg)

    def kick(self):
        self.log.info('[{}:{}] Exchange Client has disconnected'.format(str(self.addr[0]),
                                                                str(self.addr[1])))
        sys.exit(0)

    def set_addr(self, addr):
        self.addr = addr

    def get_addr(self):
        return self.addr

    def get_id(self):
        return self.id

    def set_id(self, i):
        self.id = i

    def get_io_session(self):
        return self.IoSession

    def set_io_session(self, s):
        self.IoSession = s
Exemplo n.º 5
0
 def __init__(self, gameClient):
     self.log = Logging()
     self.nameGenerator = NameGenerator()  # "world.join()" should quake it
     self.gameClient = gameClient
     self.account = None
     self.accId = None
     self.player = None
Exemplo n.º 6
0
class Database():
    '''
    INFO: ALWAYS close the Instans to close the Connection
    '''
    def __init__(self):
        self.log = Logging()
        self.log.debug('Database instance has been created')

    def initialize_data(self):
        pass

    #initialize_connection
    def get_connection(self):
        config = Config()
        config.initialize()
        try:
            connection = mysql.connector.connect(
                host=config.get_world_db_host(),
                port=config.get_world_db_port(),
                user=config.get_world_db_user(),
                password=config.get_world_db_passwo(),
                db=config.get_world_db_name(),
                auth_plugin='mysql_native_password')
            return connection

        except mysql.connector.Error as Error:
            self.log.warning(
                'Database - initialize_connection\n' + 'Config: ' +
                str(config.get_world_db_host()) + ' - ' +
                str(config.get_world_db_port()) + ' - ' +
                str(config.get_world_db_user()) + ' - ' +
                str(config.get_world_db_passwo()) + ' - ' +
                str(config.get_world_db_name()) +
                '\nDatabase - Something went wrong: {}'.format(str(Error)))
            return False
Exemplo n.º 7
0
    def __init__(self, ip, port, gameClientDic, accountDataDic, hostList,
                 ipBans):
        self.log = Logging()
        self.logoniIP = ip
        self.logonPort = port
        self.gameClientDic = gameClientDic
        self.accountDataDic = accountDataDic
        self.hostList = hostList
        self.ipBans = ipBans

        self.start()
Exemplo n.º 8
0
 def __init__(self, socket, addr):
     self.log = Logging()
     self.session = socket
     self.addr = addr
     # self.account = account
     # self.actions =
     self.timeLastChatMsg = 0
     self.timeLastIncarnamMsg = 0
     self.timeLastAlignMsg = 0
     self.timeLastRecrutmentMsg = 0
     self.timeLastTradeMsg = 0
     self.walk = False
Exemplo n.º 9
0
    def __init__(self, socket, addr, exchangeTransferList, world):
        self.log = Logging()
        self.world = world
        self.gameClient = GameClient(socket, addr)
        self.exchangeTransferList = exchangeTransferList
        self.socketManager = SocketManager(self.gameClient)

        self.accId = None
        self.account = None

        self.socketManager.GAME_SEND_HELLOGAME_PACKET()
        self.loop()
Exemplo n.º 10
0
class GameServer:
    def __init__(self):
        self.log = Logging()

    def initialize(self, ip, port):
        threadName = 'Game-Server - ' + str(port)
        try:
            t = threading.Thread(target=GameServer.server,
                                 name=threadName,
                                 args=(self, ip, port))
            t.start()
        except threading.ThreadError as e:
            self.log.warning('Game Server could not be created: ' + str(e))

    def server(self, game_ip, game_port):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind((game_ip, game_port))
        except socket.error:
            self.log.warning('Game Socket - Binding faild')
        s.listen()
        self.log.info('Game Socket is listening on Port: ' + str(game_port))
        while True:
            c, self.addr = s.accept()
            self.log.info('Connected ' + str(self.addr[0]) + ':' +
                          str(self.addr[1]))
            GameHandler().session_created(c, self.addr)
        s.close()
Exemplo n.º 11
0
class Main:
    def __init__(self):
        self.log = Logging()
        self.config = Config()
        self.console = Console()
        self.console.clear()

    def start(self):
        #  ======================================================
        #  start message

        def clear():
            return os.system('cls')

        clear()

        def wel():
            welmsg = [
                58 * '─', '|  0.01  |' + 12 * ' ' +
                'pyCestra -  World Server' + 11 * ' ' + '|', 58 * "─"
            ]
            for x in welmsg:
                print(bcolors.blue + x + bcolors.cend)

        wel()

        #  ======================================================
        #  connection test

        self.log.info('Connection Test...')
        database = dataSource.Database()
        if database.get_connection():
            self.log.info('Connection Successfully')
        else:
            self.log.warning('Connection ERROR')
            sys.exit(0)

        #  ======================================================
        #  world class test
        world = World()
        world.createWorld()
        #  ======================================================
        #  exchange client test

        exchangeTransferList = []
        exClient = ExchangeClient()
        exClient.initialize(self.config.get_exchange_ip(),
                            self.config.get_exchange_port(),
                            exchangeTransferList)

        self.log.debug('Game Server Start')
        GameServer().initialize(self.config.get_world_ip(),
                                self.config.get_world_port(),
                                exchangeTransferList, world)
Exemplo n.º 12
0
class LoginServer:
    def __init__(self, ip, port, gameClientDic, accountDataDic, hostList,
                 ipBans):
        self.log = Logging()
        self.logoniIP = ip
        self.logonPort = port
        self.gameClientDic = gameClientDic
        self.accountDataDic = accountDataDic
        self.hostList = hostList
        self.ipBans = ipBans

        self.start()

    def start(self):
        threadName = 'Login-Server - ' + str(self.logonPort)
        try:
            t = threading.Thread(target=self.server,
                                 name=threadName,
                                 args=(self.logoniIP, self.logonPort,
                                       self.gameClientDic, self.accountDataDic,
                                       self.hostList, self.ipBans))
            t.start()
        except threading.ThreadError as e:
            self.log.warning('Login Server could not be created: ' + str(e))

    def server(self, logoniIP, logonPort, gameClientDic, accountDataDic,
               hostList, ipBans):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind((self.logoniIP, self.logonPort))
        except socket.error:
            print('Login Socket - Binding faild')
        s.listen()
        self.log.info('Logon Socket is listening on Port: ' +
                      str(self.logonPort))
        while True:
            c, self.addr = s.accept()
            self.log.info('[{}:{}] Client Connected '.format(
                str(self.addr[0]), str(self.addr[1])))
            self.session_created(c, self.addr)
        s.close()

    def session_created(self, soecket, addr):
        threadName = 'Client-Session ' + str(addr[0]) + ':' + str(addr[1])
        try:
            t = threading.Thread(target=LoginHandler,
                                 name=threadName,
                                 args=(soecket, addr, self.gameClientDic,
                                       self.accountDataDic, self.hostList,
                                       self.ipBans))
            t.start()
        except threading.ThreadError as e:
            self.log.debug('Created Session ' + str(addr[0]) + ':' +
                           str(addr[1]) + ': ' + str(e))
Exemplo n.º 13
0
class LoginServer:
    def __init__(self):
        self.log = Logging()

    def start(self, ip, port, game_client_dic, accountDataDic, hostList,
              ipbans):
        threadName = 'Login-Server - ' + str(port)
        try:
            t = threading.Thread(target=LoginServer.server,
                                 name=threadName,
                                 args=(self, ip, port, game_client_dic,
                                       accountDataDic, hostList, ipbans))
            t.start()
        except threading.ThreadError as e:
            self.log.warning('Login Server could not be created: ' + str(e))

    def server(self, logon_ip, login_port, game_client_dic, accountDataDic,
               hostList, ipbans):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind((logon_ip, login_port))
        except socket.error:
            print('Binding faild')
        s.listen()
        self.log.info('Logon Socket is listening on Port: ' + str(login_port))
        while True:
            c, self.addr = s.accept()
            self.log.info('Connected ' + str(self.addr[0]) + ':' +
                          str(self.addr[1]))
            LoginHandler().session_created(c, self.addr, game_client_dic,
                                           accountDataDic, hostList, ipbans)
        s.close()
Exemplo n.º 14
0
class DatabaseUpdateService:
    def __init__(self):
        self.log = Logging()

    def start(self, accountDic, updateTime):
        threadName = 'Database-Update-Service'
        try:
            t = threading.Thread(target=DatabaseUpdateService.update_loop,
                                 name=threadName,
                                 args=(self, accountDic, updateTime))
            t.start()
            self.log.info('Database-Update-Service Successfully')
        except:
            self.log.warning('Database-Update-Service could not be created')

    def update_loop(self, accountDic, updateTime):
        def string_builder(i):
            queryPart = ('UPDATE `accounts` SET '
                         '`pass` = \'{}\','
                         '`rank` = \'{}\','
                         '`nickname` = \'{}\','
                         '`lastConnectionDate` = \'{}\','
                         '`lastIP` = \'{}\','
                         '`friends` = \'{}\','
                         '`reload_needed` = \'{}\','
                         '`logged` = \'{}\','
                         '`subscribe` = \'{}\' '
                         'WHERE (`id` = \'{}\');'.format(
                             i["pass"], i["rank"], i["nickname"],
                             i["lastConnectionDate"], i["lastIP"],
                             i["friends"], i["reload_needed"], i["logged"],
                             i["subscribe"], i["id"]))
            return queryPart

        dao = DAO()
        while True:
            time.sleep(updateTime)
            self.log.debug('[Database-Update-Service] - '
                           'Data is send to the database')
            start = time.time()
            counter = 0
            for i in accountDic:
                query = string_builder(i)
                dao.multi_update_data(query)
                del query
                counter = counter + 1
            ende = time.time()
            self.log.debug('[Database-Update-Service] - Data was transferred '
                           '(query:{}, total time: {:5.3f}s)'.format(
                               counter, ende - start))
Exemplo n.º 15
0
class MapData(DAO):
    def __init__(self):
        self.log = Logging()

    def load_in_to_class(self):
        '''
        DataFrame:

        '''
        self.dataSource = {}
        connection = dataSource.Database().get_connection()
        cursor = connection.cursor(dictionary=True)
        try:
            cursor.execute('SELECT * FROM maps;')
            data = cursor.fetchall()
            for result in data:
                try:
                    mapData = Map(
                        result['id'],
                        result['date'],
                        result['width'],
                        result['heigth'],
                        result['key'],
                        result['places'],
                        result['mapData'],
                        result['cells'],
                        result['monsters'],
                        result['mappos'],
                        result['numgroup'],
                        result['fixSize'],
                        result['minSize'],
                        result['maxSize'],
                        result['cases'],
                        result['forbidden'],
                    )
                    self.dataSource[result['id']] = mapData
                except Exception as Error:
                    self.log.warning(
                        'maps_data.py - maps:{} can\'t be loaded'.format(
                            str(result['id'])))
                    self.log.warning(Error)
        except Exception as Error:
            self.log.warning('map_data.py - Can\'t load table accounts')
            self.log.warning(str(Error))
        finally:
            cursor.close()
            connection.close()

    def get_map_data(self):
        return self.dataSource
Exemplo n.º 16
0
class ExchangeClient():
    def __init__(self):
        self.log = Logging()

    def initialize(self, exchange_ip, exchange_port):
        try:
            exSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            exSocket.connect((exchange_ip, exchange_port))
            self.log.info('Exchange-Client connected to logon server ' +
                          str(exchange_ip) + ':' + str(exchange_port))
            self.ioConnector = exSocket
        except:
            exSocket.close()
            self.log.warning('It could not be connected to the login server')
            sys.exit(0)
        try:
            exchangeHandler = ExchangeHandler()
            threadName = 'Exchange-Receiver - Port: ' + str(exchange_port)
            t = threading.Thread(target=exchangeHandler.loop,
                                 name=threadName,
                                 args=(self.ioConnector, ))
            t.start()
        except threading.ThreadError as e:
            self.log.warning('Exchange-Receiver could not be created ' +
                             str(e))

        return self.ioConnector
Exemplo n.º 17
0
class ExchangePacketHandler:
    def __init__(self):
        self.log = Logging()

    def parser(self, packet, exClient):
        if packet[0] == 'F':
            if packet[1] == '?':  # F?
                # i = 50000 - Main.gameServer.getPlayerNumber()
                # exchangeClient.send("F" + i)
                return
            return
        elif packet[0] == 'S':
            if packet[1] == 'H':
                if packet[2] == 'K':  # SHK
                    self.log.debug(
                        'The Logon-Server validates the connection successfully.'
                    )
                    return
                return
            elif packet[1] == 'K':
                if packet[2] == '?':  # SK?
                    i = 50000 - 0  # Main.gameServer.getPlayerNumber()
                    # TODO Main.exchangeClient.send("SK" + Main.serverId + ";" + Main.key + ";" + i)
                    ExchangePacketHandler().send(exClient,
                                                 'SK1;demo;' + str(i))
                    return
                elif packet[2] == 'K':  # SKK
                    self.log.debug(
                        'The Logon-Server has accepted the connection')
                    # TODO Main.exchangeClient.send("SH" + Main.Ip + ";" + Main.gamePort)
                    ExchangePacketHandler().send(
                        exClient, 'SH' + '127.0.0.1' + ';' + '5555')
                    return
                elif packet[2] == 'R':  # SKR
                    # self.log.debug('The login server refused the connection')
                    # Main.stop()
                    return
                return
            return
        elif packet[0] == 'W':
            # if (packet.split("W").length > 2)
            # magic !
            if packet[1] == 'A':  # WA
                return
            elif packet[1] == 'K':  # WK
                return
            return
        elif packet[0] == 'M':
            if packet[1] == 'G':  # MG
                return
            if packet[1] == 'F':  # MF
                return
            if packet[1] == 'D':  # MD
                return
            return

    def send(self, exClient, o):
        msg = bytes(o, 'utf-8')
        self.log.debug('[logon ip]' + '[EX-SEND->] ' + o)
        exClient.send(msg)
Exemplo n.º 18
0
class ExchangeServer():
    def __init__(self):
        self.log = Logging()

    def start(self, ip, port, hostList):
        threadName = 'Exchange-Server - ' + str(port)
        try:
            t = threading.Thread(target=ExchangeServer.server,
                                 name=threadName,
                                 args=(self, ip, port, hostList))
            t.start()
        except:
            self.log.warning('Exchange Server could not be created')

    def server(self, ex_ip, ex_port, hostList):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind((ex_ip, ex_port))
        except socket.error:
            self.log.warning('Exchange Socket - Binding faild')
        s.listen()
        self.log.info('Exchange Socket is listening on Port: ' + str(ex_port))
        while True:
            c, self.addr = s.accept()
            self.log.info('Exchange Client connected ' + str(self.addr[0]) +
                          ':' + str(self.addr[1]))
            ExchangeServer().session_created(c, self.addr, hostList)
        s.close()

    def session_created(self, soecket, addr, hostList):
        threadName = 'Exchange-Client ' + str(addr[0]) + ':' + str(addr[1])
        try:
            t = threading.Thread(target=HelloExchangeClient,
                                 name=threadName,
                                 args=(soecket, addr, hostList))
            t.start()
        except:
            self.log.warning('Exchange Client could not be created ' +
                             str(addr[0]) + ':' + str(addr[1]))
Exemplo n.º 19
0
class GameServer:

    def __init__(self):
        self.log = Logging()

    def initialize(self, ip, port, exchangeTransferList, world):
        self.world = world
        threadName = 'Game-Server - ' + str(port)
        try:
            t = threading.Thread(target=self.server,
                                name=threadName,
                                args=(ip, port, exchangeTransferList))
            t.start()
        except threading.ThreadError as e:
            self.log.warning('Game Server could not be created: ' + str(e))

    def server(self, game_ip, game_port, exchangeTransferList):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind((game_ip, game_port))
        except socket.error:
            self.log.warning('Game Socket - Binding faild')
        s.listen()
        self.log.info('Game Socket is listening on Port: ' + str(game_port))
        while True:
            c, self.addr = s.accept()
            self.log.debug('[{}:{}] Client Connected '.format(str(self.addr[0]),str(self.addr[1])))
            self.session_created(c, self.addr, exchangeTransferList)
        s.close()

    def session_created(self, socket, addr, exchangeTransferList):
        threadName = 'Game-Client-Session '+str(addr[0])+':'+ str(addr[1])
        try:
            t = threading.Thread(target=GameHandler,
                                name=threadName,
                                args=(socket, addr, exchangeTransferList, self.world,))
            t.start()
        except:
            self.log.warning('Game Client could not be created '+ str(addr[0])+':'+ str(addr[1]))
Exemplo n.º 20
0
    def __init__(self, soecket, addr, gameClientDic, accountDataDic, hostList,
                 ipbans):
        self.log = Logging()
        self.gameClientDic = gameClientDic
        self.accountDataDic = accountDataDic
        self.hostList = hostList

        self.client = LoginClient(self.gameClientDic, self.accountDataDic)
        self.client.set_key(self.generate_key())
        self.client.set_address(addr)
        self.client.set_status(Status(0))
        self.client.set_io_session(soecket)

        self.log.debug('[' + str(addr[0]) + ':' + str(addr[1]) + '][' +
                       str(self.client.get_status().name) +
                       '] Client created - ' + self.client.get_key())

        # the object is save in the global dictionary
        dict_str = addr[0] + ':' + str(addr[1])
        self.gameClientDic[dict_str] = self.client

        HelloConnection(self.client, ipbans)
        self.recv_loop()
Exemplo n.º 21
0
class GameClient:
    def __init__(self, socket, addr):
        self.log = Logging()
        self.session = socket
        self.addr = addr
        # self.account = account
        # self.actions =
        self.timeLastChatMsg = 0
        self.timeLastIncarnamMsg = 0
        self.timeLastAlignMsg = 0
        self.timeLastRecrutmentMsg = 0
        self.timeLastTradeMsg = 0
        self.walk = False
        # self.waiter =

    def kick(self):
        self.log.info('[{}][ACC:{}] Client kick'.format(
            str(self.addr[0]), str('X')))
        sys.exit(0)

    def get_session(self):
        return self.session

    def get_addr(self):
        return self.addr

    def set_character(self, character):
        self.character = character

    def get_character(self):
        return self.character

    def set_account(self, account):
        self.account = account

    def get_account(self):
        return self.account
Exemplo n.º 22
0
class DAO:
    def __init__(self):
        self.log = Logging()
        self.connection = dataSource.Database().get_connection()
        self.cursor = self.connection.cursor()

    def get_data(self, query):
        connection = dataSource.Database().get_connection()
        cursor = connection.cursor()
        try:
            if not query.endswith(';'):
                query += ";"
            cursor.execute(query)
            data = cursor.fetchall()
            return data
        except Exception as e:
            self.log.warning('DAO.py - Can\'t load: \n{}\n{}'.format(
                query, str(e)))
            cursor.close()
            connection.close()
        finally:
            cursor.close()
            connection.close()

    def multi_update_data(self, query):
        '''
        This function does not end the connection after use
        '''
        try:
            if not query.endswith(';'):
                query += ";"
            self.cursor.execute(query)
        except pymysql.Error as Error:
            self.log.warning(
                'DAO.py - update_data - Can\'t update the Database\n{}\n{}'.
                format(str(Error), query))
Exemplo n.º 23
0
class LoginHandler:
    def __init__(self, soecket, addr, gameClientDic, accountDataDic, hostList,
                 ipbans):
        self.log = Logging()
        self.gameClientDic = gameClientDic
        self.accountDataDic = accountDataDic
        self.hostList = hostList

        self.client = LoginClient(self.gameClientDic, self.accountDataDic)
        self.client.set_key(self.generate_key())
        self.client.set_address(addr)
        self.client.set_status(Status(0))
        self.client.set_io_session(soecket)

        self.log.debug('[' + str(addr[0]) + ':' + str(addr[1]) + '][' +
                       str(self.client.get_status().name) +
                       '] Client created - ' + self.client.get_key())

        # the object is save in the global dictionary
        dict_str = addr[0] + ':' + str(addr[1])
        self.gameClientDic[dict_str] = self.client

        HelloConnection(self.client, ipbans)
        self.recv_loop()

    def recv_loop(self):
        packetHandler = PacketHandler()
        while True:
            data = self.client.get_io_session().recv(2048)
            packet = data.decode()
            packetPrint = packet.replace('\n', '[n]')
            self.log.debug('[' + str(self.client.get_address()[0]) + ':' +
                           str(self.client.get_address()[1]) + ']' + '[' +
                           str(self.client.get_status().name) + '][<-RECV] ' +
                           packetPrint)
            if not data:
                self.log.debug('[' + str(self.client.get_address()[0]) + ':' +
                               str(self.client.get_address()[1]) + ']' + '[' +
                               str(self.client.get_status().name) +
                               '] PacketLoop no data')
                self.client.kick()
                break
            packetHandler.parser(self.client, packet, self.gameClientDic,
                                 self.accountDataDic, self.hostList)

    def send_to_all(self):
        pass

    def generate_key(self):
        key = ''
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        while len(key) < 32:
            char = random.choice(alphabet)
            key += char
        # key = key[:-1]
        return key
Exemplo n.º 24
0
class ServerData(DAO):
    def __init__(self):
        self.log = Logging()
        self.Datasource = []

    def load(self):
        '''
        DataFrame:
        id, name, key, population, isSubscriberServer
        ['1','Demo', 'demo', 0, 0,]

        relevant data:
        id, key, population, isSubscriberServer
        ['1', 'key', 'population', 'isSubscriberServer']
        '''
        connection = dataSource.Database().get_connection()
        cursor = connection.cursor()
        try:
            cursor.execute('SELECT * FROM servers;')
            data = cursor.fetchall()
            for result in data:
                # only relevant data is saved
                server = Server(result['id'], result['key'], 0,
                                result['population'],
                                result['isSubscriberServer'])

                self.Datasource.append(server)
        except pymysql.Error as Error:
            self.log.warning('server_data.py - Can\'t load table servers - ')
            self.log.warning(str(Error))
        finally:
            cursor.close()
            connection.close()

    def get_server_data(self):
        return self.Datasource
Exemplo n.º 25
0
class AccountData(DAO):

    def __init__(self):
        self.log = Logging()
        self.Datasource = []

    def load(self):
            '''
            DataFrame:

            '''
            connection = dataSource.Database().get_connection()
            cursor = connection.cursor(dictionary=True)
            try:
                cursor.execute('SELECT * FROM accounts;')
                data = cursor.fetchall()
                for row in data:
                    self.Datasource.append(row)
            except Exception as Error:
                self.log.warning(' account_data.py - Can\'t load table accounts')
                self.log.warning(str(Error))
            finally:
                cursor.close()
                connection.close()

    def get_account_data(self):
        return self.Datasource

    def single_update(self, acc_id, valueTyp, value):
        '''
        acc_id
        valueTyp = Column name as in the database
        value

        example:
        update(1,'logged','1')
        '''
        data = 'UPDATE `accounts` SET `{}` = \'{}\' WHERE (`id` = \'{}\');'.format(str(valueTyp),str(value),str(acc_id))
        super().update_data(data)

    # Use databank account ID to find the right account
    def get_from_id(self, idwis):
        if not idwis == 0:
            account = idwis - 1
            return self.Datasource[account]
        else:
            self.log.warning('account_data.py - Can\'t load account id 0')
Exemplo n.º 26
0
class ExchangeHandler:

    def __init__(self):
        self.log = Logging()

    def loop(self, exSocket):
        self.log.debug('Exchange-Receiver is started')
        while True:
            data = exSocket.recv(2048)
            packet = data.decode()
            packetLog = packet.replace('\n', '[]')
            self.log.debug('[logon ip][<-EX-RECV] '
                            + packetLog)
            if not data:
                self.log.debug('[logon ip] PacketLoop no data')
                # kick
                break
            ExchangePacketHandler().parser(packet, exSocket)
Exemplo n.º 27
0
 def __init__(self):
     self.log = Logging()
Exemplo n.º 28
0
 def __init__(self):
     self.log = Logging()
     self.Datasource = []
Exemplo n.º 29
0
class LoginHandler:
    def __init__(self):
        self.log = Logging()

    def login(self, soecket, key, addr, game_client_dic, accountDataDic,
              hostList, ipbans):
        client = LoginClient(game_client_dic, accountDataDic)
        client.set_key(key)
        client.set_address(addr)
        client.set_status(Status(0))
        client.set_io_session(soecket)

        self.log.debug('[' + str(addr[0]) + ':' + str(addr[1]) + '][' +
                       str(client.get_status().name) + '] Client created - ' +
                       key)

        # the object is save in the global dictionary
        dict_str = addr[0] + ':' + str(addr[1])
        game_client_dic[dict_str] = client

        HelloConnection(client, ipbans)
        LoginHandler().recv_loop(client, game_client_dic, accountDataDic,
                                 hostList)

    def recv_loop(self, client, game_client_dic, accountDataDic, hostList):
        while True:
            data = client.get_io_session().recv(2048)
            packet = data.decode()
            packetPrint = packet.replace('\n', '[n]')
            self.log.debug('[' + str(client.get_address()[0]) + ':' +
                           str(client.get_address()[1]) + ']' + '[' +
                           str(client.get_status().name) + '][<-RECV] ' +
                           packetPrint)
            if not data:
                self.log.debug('[' + str(client.get_address()[0]) + ':' +
                               str(client.get_address()[1]) + ']' + '[' +
                               str(client.get_status().name) +
                               '] PacketLoop no data')
                client.kick()
                break
            PacketHandler().parser(client, packet, game_client_dic,
                                   accountDataDic, hostList)

    def session_created(self, soecket, addr, game_client_dic, accountDataDic,
                        hostList, ipbans):
        key = LoginHandler.generate_key(0)
        threadName = 'Client-Session ' + str(addr[0]) + ':' + str(addr[1])
        try:
            t = threading.Thread(target=LoginHandler.login,
                                 name=threadName,
                                 args=(self, soecket, key, addr,
                                       game_client_dic, accountDataDic,
                                       hostList, ipbans))
            t.start()
        except threading.ThreadError as e:
            self.log.debug('Created Session ' + str(addr[0]) + ':' +
                           str(addr[1]) + ': ' + str(e))

    def session_opened(self):
        pass

    def send_to_all(self):
        pass

    def generate_key(self):
        key = ''
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        while len(key) < 32:
            char = random.choice(alphabet)
            key += char
        # key = key[:-1]
        return key
Exemplo n.º 30
0
class ChooseNickName:
    '''
    information material:
    https://www.dofus.com/en/mmorpg/community/nicknames#\n
    https://www.python-kurs.eu/re.php
    '''
    def __init__(self):
        self.log = Logging()

    def inspect(self, nickname):
        #                  Admin                    Modo                 GM           Game Master
        forbiddenWords = [
            r'[Aa][Dd][Mm][Ii][Nn]',
            r'[Mm][Oo][Dd][Oo]',
            r'[Gg][Mm]',
            r'[Gg][Aa][Mm][Ee]-?[Mm][Aa][Ss][Tt][Ee][Rr]',
        ]

        def forbidden_words_check(val):
            for x in forbiddenWords:
                if re.search(x, nickname):
                    return False
            return True

        def forbidden_symbol(val):
            for i in nickname:
                nick = re.match(r'[a-z]?[A-Z]?[0-9]?\x2D?', i)
                if nick.group(0) == '':
                    return False
            return True

        flag = 0
        while True:
            # the nickname must be at least 3 symbol long
            if (len(nickname) < 3):
                flag = -1
                break
            # the nickname may only consist of a-z, A-Z, 0-1 and -
            elif not forbidden_symbol(nickname):
                flag = -1
                break
            # the nickname can not contain more than 4 "-"
            elif len(re.findall(r'\x2D', nickname)) >= 5:
                flag = -1
                break
            # the nickname can not contain more than 2 numbers
            elif len(re.findall(r'[0-9]', nickname)) >= 3:
                flag = -1
                break
            # The nickname can not be a forbidden word
            elif not forbidden_words_check(nickname):
                flag = -1
                break
            else:
                flag = 0
                return True
        if flag == -1:
            return False

    def verify(self, client, nickname, accountDataDic, hostList):

        # test if the nickname of the account is empty
        account = client.get_account()
        if not account.get_nickname() == '':
            client.kick()
            return

        # nickname must be different from your username
        if nickname.lower() == account.get_name().lower():
            client.send("AlEr")
            return

        # the examination of the nickname string
        if not self.inspect(nickname):
            self.log.debug('[' + str(client.get_address()[0]) + ']'
                           '[' + str(client.get_status().name) +
                           '] This nickname is not available')
            # 'AlEs'= this nickname is not available.
            client.write("AlEs")
            return

        # is the nickname already taken?
        # AlEs = this nickname is not available.
        for i in accountDataDic:
            if i['nickname'] == nickname:
                self.log.debug('[' + str(client.get_address()[0]) + ']'
                               '[' + str(client.get_status().name) + ']' +
                               'This nickname is already in use')
                client.write("AlEs")
                return

        account.set_nickname(nickname)
        account.set_state(0)

        # set client status to SERVER
        client.set_status(Status(4))

        # update of the accountDataDic entry
        for i in accountDataDic:
            if i['id'] == account.get_id():
                i['nickname'] = account.get_nickname()
                break

        AccountQueue().verify(client, accountDataDic, hostList)