Exemple #1
0
    def stop(self):
        if not self.is_started():
            log.d('Box relay has already stopped!!!')
            return

        # TODO: Need notify first.
        self.__clean_cached_boxes()

        if self.box:
            self.__notify_box_close()

        self.hub_linker.stop()
        self.__notify_relay_thread_quit()
        self.relay_thread.join()
        self.relay_thread = None

        self.upnp.release_upnp_ports()

        if self.box:
            self.__close_box()
        self.cs.close()
        self.cs = None
        self.s.close()
        self.s = None

        self.__qs.close()
        self.__qs = None

        log.d('Box relay stopped.')
Exemple #2
0
    def __handle_connection_timeout(self):
        # log.v('Handle connection in select() timeout.')

        # Clean cached boxes.

        for c in self.box_cache[:]:
            if c.ping_tracer.update():  # Image no ping msg.
                self.__close_cached_box(c)

        # Check client connection timeout.

        for c in self.clients[:]:
            if c.timeout_tracer.update():
                log.d('Client %d connection closed because timeout.' % c.uuid)

                self.box.append_data_to_buffer(
                    Message.create_client_error_data(
                        c.uuid, ECode.RELAY_CLIENT_TIMEOUT))
                self.__close_client(c)

        # Check box connection timeout.

        if self.box:
            is_no_ping = self.box.ping_tracer.update()
            is_timeout = self.box.timeout_tracer.update()
            if is_no_ping or is_timeout:
                log.d('Box %d connection closed because %s.' %
                      (self.box.uuid, 'no ping' if is_no_ping else 'timeout'))

                self.__notify_box_close()
                self.__close_box()
Exemple #3
0
 def __handle_box_server_error(self, c, msg):
     log.d('Get an error message from box %d for client %d.' %
           (self.box.uuid, c.uuid))
     for cc in self.clients:
         if cc.uuid == msg.uuid:
             self.__close_client(cc)
             return
Exemple #4
0
 def __handle_quit_request(self, r):
     c, addr = r.accept()
     data = c.recv(config.SOCKET_RECV_LEN)
     if data == RelayServer.MSG_QUIT:
         self.__is_quit_thread = True
         log.d('Get a quit request from quit-port.')
     else:
         log.e('Get an unknown message from quit-port.')
Exemple #5
0
 def __init__(self, relay, upnp):
     self.relay = relay
     self.upnp = upnp
     self.address = self._get_local_address()
     log.d('local address: %s' % self.address)
     self.port = 8100 # May be changed by RelayServer.
     self.client_port = 8120 # May be changed by RelayServer.
     self.quit_port = 8140 # May be changed by RelayServer.
     self.udp_port = 8160 # May be changed by StunServer.
     self.last_ports = None
Exemple #6
0
    def start(self):
        if self.is_started():
            log.d('Box relay has already started!!!')
            return

        config.bind_except_hook()

        self.hub_linker = HubLinker(self)

        self.__qs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.upnp.quit_port = self.hub_linker.bind_socket_to_port(
            self.__qs, self.upnp.address, self.upnp.quit_port)
        self.__qs.listen(5)
        log.d('Prepare quit port: %s, %d' %
              (self.upnp.address, self.upnp.quit_port))
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.upnp.port = self.hub_linker.bind_socket_to_port(
            self.s, self.upnp.address, self.upnp.port)
        self.s.listen(10)
        log.d('Prepare box port: %s, %d' % (self.upnp.address, self.upnp.port))
        self.box = None
        self.cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.upnp.client_port = self.hub_linker.bind_socket_to_port(
            self.cs, self.upnp.address, self.upnp.client_port)
        log.d('Prepare client port: %s, %d' %
              (self.upnp.address, self.upnp.client_port))
        self.cs.listen(5)
        self.clients = []

        self.relay_thread = Thread(target=RelayServer.__start_main,
                                   args=(self, ))
        self.relay_thread.start()

        self.hub_linker.start()
Exemple #7
0
    def __handle_connection_read(self, r):
        # log.v('Handle connection reading.')

        if r is self.s:
            log.v('Handle box listener reading.')

            c, addr = r.accept()
            conn = BoxConnection(c)
            log.d('Connected by box %d, address, %s' % (conn.uuid, repr(addr)))
            if self.box:
                conn.close()
            else:
                self.box_cache.append(conn)
        elif r in self.box_cache:
            log.v('Handle cached box reading.')

            try:
                self.__handle_cached_box_connection(r)
            except (socket.error, socket.timeout) as e:
                log.e('Cached box %d connection encounter an error: %s' %
                      (r.uuid, str(e)))
                self.__close_cached_box(r)
        elif r is self.box:
            log.v('Handle box reading.')

            try:
                self.__handle_box_connection(r)
            except (socket.error, socket.timeout) as e:
                log.e('Box %d connection encounter an error: %s' %
                      (r.uuid, str(e)))
                self.__close_box()
        elif r is self.cs:
            log.v('Handle client listener reading.')

            c, addr = r.accept()
            conn = ClientConnection(c)
            log.d('Connected by client %d, address, %s' %
                  (conn.uuid, repr(addr)))
            if not self.box:
                log.d('Skip this client because no box connected !!!')
                conn.close()
                return
            self.clients.append(conn)
        elif r in self.clients:
            log.v('Handle client reading.')

            try:
                r.timeout_tracer.reset()
                self.__handle_client_connection(r)
            except (socket.error, socket.timeout) as e:
                log.e('Client %d connection enconter an error: %s.' %
                      (r.uuid, str(e)))
                self.__notify_box_client_broken(r.uuid)
                self.__close_client(r)
        elif r is self.__qs:
            log.v('Handle quit-socket reading.')

            self.__handle_quit_request(r)
        else:
            log.d('The connection does not need handle.')
Exemple #8
0
    def run(self):
        self.load_plugin_list()
        log.i("Plugins Loaded.")

        self.connect()
        log.i("Bot Connected.")

        self.on_connect()
        log.i("Deception locked and loaded!")

        while self.connected:
            msg = self.recv()

            if len(msg) == 0:
                self.connected = False
                continue

            msglist = msg.split('\n')

            for line in msglist:
                if len(line) == 0: continue

                log.d(line)

                cmd = self.parse_cmd(line.strip())
                if cmd == None:
                    self.on_msg_recv(line)
                    continue

                log.d(cmd);

                if self.process_server_cmd(cmd):
                    continue

                if cmd.name not in self.cmd_handlers.keys():
                    log.e("Command '%s' not recognized." % cmd.name)
                    self.on_unknown_cmd(cmd)
                    continue

                if not self.check_permission(cmd):
                    self.on_permission_denied(cmd)

                self.process_cmd(cmd)

        self.on_disconnect()
Exemple #9
0
 def __send_status(self):
     addr, port, cport, udp_port = self.upnp.get_router_info()
     info = {
         'cpuRatio': self.__get_cpu_utilization_ratio(),
         'memoryRatio': self.__get_memory_utilization_ratio(),
         'ioRatio': 0.0,
         'bandwidthUpload': str(self.upload_speed),
         'bandwidthDownload': str(self.download_speed),
         'connections': '0',
         'dataRate': '0',
         # 'status': 'busy' if self.relay.is_busy() or self.udp_server.is_busy() else 'free',
         'status': 'busy' if self.relay.is_busy() else 'free',
         'ip': addr,
         'tcpPort': str(port) if port else '',
         # 'udpPort': udp_port,
         'udpPort': '',
     }
     log.d('[RM] STATUS: %s' % str(info))
     self.conn.send(RelayManagerMessage.create_load_balance_data(info))
Exemple #10
0
 def _init_margins(self):
     """
     设置绘图的区域,区域之外,无法绘图。
     """
     xpppi, ypppi = self.printout.GetPPIPrinter()
     page_r = self.printout.GetPaperRectPixels()
     pw, ph = self.printout.GetPageSizePixels()
     margin_l, margin_t = self.printer.margins[0] # mm
     margin_r, margin_b = self.printer.margins[1] # mm
     orig_dl = int(float(0 - page_r.left) / float(xpppi) * 25.4)
     orig_dt = int(float(0 - page_r.top) / float(xpppi) * 25.4)
     orig_dr = int(float(pw - page_r.right) / float(xpppi) * 25.4)
     orig_db = int(float(ph - page_r.bottom) / float(xpppi) * 25.4)
     pt1 = wx.Point(margin_l - orig_dl, margin_t - orig_dt)
     pt2 = wx.Point(210 - (margin_r - orig_dr), 297 - (margin_b - orig_db))
     self.margins_r_mm = wx.RectPP(pt1, pt2)
     log.d('Margins mm rect: %s' % repr(self.margins_r_mm))
     self.margins_r = wx.RectPP(wx.Point(self.mm2s(pt1.x), self.mm2s(pt1.y)),
                                wx.Point(self.mm2s(pt2.x), self.mm2s(pt2.y)))
     log.d('Margins rect: %s' % repr(self.margins_r))
     self.dc.SetClippingRect(self.margins_r)
Exemple #11
0
    def __handle_box_register(self, c, msg):
        """
        :param c:
        :param msg:
        :return: the box is valid.
        """

        log.d('Get box %d register content: %s' % (c.uuid, msg.content))

        try:
            sn = str(msg.content['deviceId'])
            service = str(msg.content['service'])
            token = str(msg.content['token'])
        except:
            log.e('Box register information format is not correct.')
            c.send(Message.create_refuse_data(ECode.RELAY_BOX_INVALID_INFO))
            return False

        device_token = self.hub_linker.connector.verify_token(
            sn, service, token)
        if not device_token:
            log.e('Box register information is invalid by hub.')
            c.send(Message.create_refuse_data(ECode.RELAY_BOX_INVALID_INFO))
            return False

        log.d('Box register info is valid, device_id %s, token %s.' %
              (str(sn), str(token)))

        _, _, cport, udp_port = self.upnp.get_router_info()
        if not cport:
            log.e('Can not set up client upnp port.')
            c.send(
                Message.create_refuse_data(
                    ECode.RELAY_FAILED_CREATE_CLIENT_PORT))
            return False
        reply = {'port': str(cport)}
        c.send(Message.create_accept_data(reply))
        return True
Exemple #12
0
 def __send_heartbeat(self):
     log.d('[RM] HEARTBEAT')
     self.conn.send(RelayManagerMessage.create_heartbeat_data())
Exemple #13
0
def exception_hook(ex_type, value, tb):
    log.d(traceback.format_exception(ex_type, value, tb))
    raise value