def __init__(self, address, cls):
        """Initialize the server."""
        self.allow_reuse_address = True
        ThreadingTCPServer.__init__(self, address, cls)

        self.engine = None
        self.engine_lock = threading.Lock()
Ejemplo n.º 2
0
 def __init__(self, host='localhost',
              port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
              handler=LogRecordStreamHandler):
     ThreadingTCPServer.__init__(self, (host, port), handler)
     self.abort = 0
     self.timeout = 1
     self.logname = None
Ejemplo n.º 3
0
 def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
              handler=None):
     ThreadingTCPServer.__init__(self, (host, port), handler)
     logging._acquireLock()
     self.abort = 0
     logging._releaseLock()
     self.timeout = 1
Ejemplo n.º 4
0
 def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
              handler=None):
     ThreadingTCPServer.__init__(self, (host, port), handler)
     logging._acquireLock()
     self.abort = 0
     logging._releaseLock()
     self.timeout = 1
Ejemplo n.º 5
0
 def __init__(self, host, port, traceback_frames, ignore_selects, ignored_sources, ignored_request_paths):
     ThreadingTCPServer.__init__(self, (host, port), LogRecordStreamHandler)
     self.timeout = 1
     self.traceback_frames = traceback_frames
     self.ignore_selects = ignore_selects
     self.ignored_sources = [ignored_line_re.match(s).groupdict() for s in ignored_sources]
     self.ignored_request_paths = {self._process_path(x) for x in ignored_request_paths}
Ejemplo n.º 6
0
 def __init__(self, host='localhost',
                          port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                  handler=LogRecordStreamHandler):
     ThreadingTCPServer.__init__(self, (host, port), handler)
     self.abort = False
     self.timeout = 0.1
     self.finished = threading.Event()
Ejemplo n.º 7
0
 def __init__(self,
              server_address,
              RequestHandlerClass,
              server_ssl=True,
              bind_and_activate=True,
              encrypted=True):
     ThreadingTCPServer.__init__(self, server_address, RequestHandlerClass,
                                 False)
     self.secure = server_ssl
     self.__shutdown_request = False
     self.networked = []
     self.messagebox = []
     self.watch = threading.Thread(target=self._network_watch)
     self.watch.start()
     self._key = Random.new().read(AES.key_size[-1])
     self._cipherobj = AES.new(self._key, AES.MODE_CBC,
                               Random.new().read(AES.block_size))
     self._encrypted = encrypted
     self._aes_buffer = b'\x90' * 3 + b'\x05'
     signal.signal(signal.SIGINT, self.stop_thread)
     if bind_and_activate:
         try:
             self.server_bind()
             self.server_activate()
         except:
             self.server_close()
             raise
Ejemplo n.º 8
0
 def process_request(self, request, client_address):
   # Processa uma nova requisicao. Adiciona o novo cliente na lista de clientes
   # mantida pelo servidor e chama o mesmo metodo da classe-base.
   print("Novo cliente conectado " + request.getpeername()[0])
   self.clients.append(request)
   ThreadingTCPServer.process_request(self, request,
     client_address)
Ejemplo n.º 9
0
    def start(self):
        """Start the server.

        Do nothing if server is already running.
        This function will block if no_block is not set to True.
        """
        if not self.is_run:
            # set class attribute
            ThreadingTCPServer.address_family = socket.AF_INET6 if self.ipv6 else socket.AF_INET
            ThreadingTCPServer.daemon_threads = True
            # init server
            self._service = ThreadingTCPServer((self.host, self.port),
                                               self.ModbusService,
                                               bind_and_activate=False)
            # set socket options
            self._service.socket.setsockopt(socket.SOL_SOCKET,
                                            socket.SO_REUSEADDR, 1)
            self._service.socket.setsockopt(socket.SOL_SOCKET,
                                            socket.SO_KEEPALIVE, 1)
            # TODO test no_delay with bench
            self._service.socket.setsockopt(socket.IPPROTO_TCP,
                                            socket.TCP_NODELAY, 1)
            # bind and activate
            self._service.server_bind()
            self._service.server_activate()
            # serve request
            if self.no_block:
                self._serve_th = Thread(target=self._serve)
                self._serve_th.daemon = True
                self._serve_th.start()
            else:
                self._serve()
Ejemplo n.º 10
0
 def __init__(self, server_address, session, probe):
     self._session = session
     self._probe = probe
     ThreadingTCPServer.__init__(self,
                                 server_address,
                                 DebugProbeRequestHandler,
                                 bind_and_activate=False)
Ejemplo n.º 11
0
    def __init__(self, host="", port=COBRA_PORT, sslcrt=None, sslkey=None, sslca=None, msgpack=False, json=False):
        '''
        Construct a cobra daemon object.

        Parameters:
        host        - Optional hostname/ip to bind the service to (default: inaddr_any)
        port        - The port to bind (Default: COBRA_PORT)
        msgpack     - Use msgpack serialization

        # SSL Options
        sslcrt / sslkey     - Specify sslcrt and sslkey to enable SSL server side
        sslca               - Specify an SSL CA key to use validating client certs

        '''
        self.thr = None
        self.run = True
        self.shared = {}
        self.dowith = {}
        self.host = host
        self.port = port
        self.reflock = RLock()
        self.refcnts = {}
        self.authmod = None
        self.sflags = 0

        if msgpack and json:
            raise Exception('CobraDaemon can not use both msgpack *and* json!')

        if msgpack:
            requireMsgpack()
            self.sflags |= SFLAG_MSGPACK

        if json:
            self.sflags |= SFLAG_JSON

        # SSL Options
        self.sslca = sslca
        self.sslcrt = sslcrt
        self.sslkey = sslkey

        self.cansetattr = True
        self.cangetattr = True

        if sslcrt and not os.path.isfile(sslcrt):
            raise Exception('CobraDaemon: sslcrt param must be a file!')

        if sslkey and not os.path.isfile(sslkey):
            raise Exception('CobraDaemon: sslkey param must be a file!')

        if sslca and not os.path.isfile(sslca):
            raise Exception('CobraDaemon: sslca param must be a file!')

        self.allow_reuse_address = True
        ThreadingTCPServer.__init__(self, (host, port), CobraRequestHandler)

        if port == 0:
            self.port = self.socket.getsockname()[1]

        self.daemon_threads = True
        self.recvtimeout = None
Ejemplo n.º 12
0
def serve():
    parser = argparse.ArgumentParser()
    # add arguments for dispacher's host and port
    parser.add_argument("--host",
                        help="dispatcher's host, by default it is localhost",
                        default="localhost",
                        action="store")
    parser.add_argument("--port",
                        help="dispatcher's port, by default it is 8888",
                        default=8888,
                        action="store")
    args = parser.parse_args()

    # start a new server
    server = ThreadingTCPServer((args.host, int(args.port)), DispatcherServer)
    print("Serving on %s:%s" % (args.host, int(args.port)))

    # spawn 2 threads for runner and redistributor
    runner_heartbeat = threading.Thread(target=runner_checker, args=(server, ))
    redistributor = threading.Thread(target=redistribute, args=(server, ))

    try:
        runner_heartbeat.start()
        redistributor.start()
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl+C or Cmd+C
        server.serve_forever()
    except (KeyboardInterrupt, Exception):
        # if any exception occurs, kill the thread
        server.dead = True
        runner_heartbeat.join()
        redistributor.join()
Ejemplo n.º 13
0
def _do_preview(*, build, subdir, port):
    """Implements the "serve" (http) mode of main().

    Args:
        build: Same as per main().
        subdir: Same as per main().
        port: Local port number to serve on, per the command line.
    """
    print("Generating documentation preview ...")
    with tempfile.TemporaryDirectory(prefix="doc_builder_preview_") as scratch:
        if subdir:
            out_dir = join(scratch, subdir)
            os.mkdir(out_dir)
        else:
            out_dir = scratch
        pages = _call_build(build=build, out_dir=out_dir)
        assert len(pages) > 0
        os.chdir(scratch)
        print(f"The files have temporarily been generated into {scratch}")
        print()
        print("Serving at the following URLs for local preview:")
        print()
        for page in pages:
            print(f"  http://127.0.0.1:{port}/{join(subdir, page)}")
        print()
        print("Use Ctrl-C to exit.")
        ThreadingTCPServer.allow_reuse_address = True
        server = ThreadingTCPServer(("127.0.0.1", port), _HttpHandler)
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            print()
            return
Ejemplo n.º 14
0
    def __init__(self, ip, port, handler):
        ThreadingTCPServer.__init__(self, (ip, port), handler)
        Thread.__init__(self, target=self.serve_forever)

        # Set the thread name to the class name
        Thread.setName(self, f'TCP-{self.__class__.__name__} Server')
        self.daemon = True
Ejemplo n.º 15
0
 def __init__(self,
              server_address,
              RequestHandlerClass,
              bind_and_activate=True):
     """Constructor.  May be extended, do not override."""
     ThreadingTCPServer.__init__(self, server_address, RequestHandlerClass)
     self.stopped = False
Ejemplo n.º 16
0
def main():
    global data, passwords1
    tcp = False
    if '-t' in sys.argv:
        sys.argv.remove('-t')
        tcp = True
    #end if

    # Deterministic.
    if len(sys.argv) > 1:
        random.seed(sys.argv[1])
    else:
        random.seed('0x31337')
    #end if
    data = open('1558121717.Vfe01I1b573a2M922672.suzy', 'rb').read().decode('utf-8', errors='replace')
    
    passwords = 'A a aa aal aalii aam Aani aardvark aardwolf Aaron Aaronic Aaronical Aaronite Aaronitic Aaru Ab aba Ababdeh Ababua abac'.split(' ')
    passwords1 = []
    for password in passwords:
        # add junk to it
        p = data[random.randint(0, len(data) - 1)]
        passwords1.append(password + p)
    #next password
    if tcp:
        port = 2045
        addr = ('0.0.0.0', port)
        server = ThreadingTCPServer(addr, AAAS_Handler)
        server.serve_forever()
    else:
        print("tcp until you think of something")
Ejemplo n.º 17
0
    def run(self):
        if self.mode == 'grc':
            self.serv = ThreadingTCPServer(('', self.port),
                                           GRC_Handler,
                                           bind_and_activate=False)
            self.serv.socket.settimeout(1)  # 设置超时, 以便能够退出线程
            self.serv.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
                                        True)  # 设置端口重用, 以便异常socket断开后的重建
            self.serv.qthread = self  # 这里让Handle里面有信号的发射口

        elif self.mode == 'hcr':
            self.serv = ThreadingTCPServer(('', self.port),
                                           HCR_Handler,
                                           bind_and_activate=False)
            self.serv.socket.settimeout(1)  # 设置超时, 以便能够退出线程
            self.serv.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
                                        True)  # 设置端口重用, 以便异常socket断开后的重建

        else:
            print("error")
            return
        # Bind and activate
        # self.setName("tcp_server " + self.mode)
        self.serv.server_bind()
        self.serv.server_activate()
        self.serv.serve_forever()
Ejemplo n.º 18
0
def run():
    # create a genesis block
    t = str(datetime.now())
    genesis_block = {
        "Index": 0,
        "Timestamp": t,
        "BPM": 0,
        "PrevHash": "",
        "Validator": ""
    }

    genesis_block["Hash"] = calculate_hash(genesis_block)
    print(genesis_block)
    block_chain.append(genesis_block)

    thread_canditate = threading.Thread(target=candidate,
                                        args=(candidate_blocks, ),
                                        daemon=True)
    thread_pick = threading.Thread(target=pick_winner,
                                   args=(announcements, ),
                                   daemon=True)

    thread_canditate.start()
    thread_pick.start()

    # start a tcp server
    serv = ThreadingTCPServer(('', 9090), HandleConn)
    serv.serve_forever()
Ejemplo n.º 19
0
def main():
    if len(sys.argv) < 2:
        print("Usage: {} binFile [port]\n\t".format(sys.argv[0]))
        exit(-1)

    binFile = sys.argv[1]
    port = DEFAULT_PORT if len(sys.argv) < 3 else int(sys.argv[2])

    print('binFile:', binFile, 'port:', port)
    server = ThreadingTCPServer(('', port), EncodeHandler)

    def sigint_handler(signum, frame):
        print('sig {} raised: {}'.format(signum, frame))
        server.socket.close()
        server.shutdown()
        sys.exit(0)

    signal.signal(signal.SIGINT,
                  sigint_handler)  # main thread will handle signals

    try:
        EncodeHandler.bitmapList = load_video_bin(binFile)
        waiterThread = Thread(target=server.serve_forever, args=())
        waiterThread.start()
        waiterThread.join()
    except Exception as e:
        print('exception raised:', e)
    finally:
        server.socket.close()
        server.shutdown()
Ejemplo n.º 20
0
    def tcprelay(self, host: str, port: int):
        callback = self.onecmd
        welcome = f'vxi11cmd server, relay {host}:{port}, remote {self.address}.\r\n\r\n'.encode(
        )

        class CmdServerHandler(StreamRequestHandler):
            def handle(self):
                self.request.send(welcome)
                buffer = bytearray()
                while True:
                    buffer.extend(self.request.recv(64))
                    while True:
                        i = buffer.find(b'\n')
                        if i == -1:
                            break
                        line = bytes(buffer[:i + 1])
                        buffer[:] = buffer[i + 1:]
                        command = line.decode().strip()
                        print(command)
                        try:
                            answer = callback(command)
                            if answer:
                                self.request.send(answer.encode() + b'\r\n')
                        except KeyboardInterrupt:
                            sys.exit(2)
                        except Exception as e:
                            self.request.send(str(e).encode() + b'\r\n')

        server = ThreadingTCPServer((host, port), CmdServerHandler)
        server.serve_forever()
Ejemplo n.º 21
0
 def __init__(self, host='localhost',
                          port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                  handler=LogRecordStreamHandler):
     ThreadingTCPServer.__init__(self, (host, port), handler)
     self.abort = False
     self.timeout = 0.1
     self.finished = threading.Event()
Ejemplo n.º 22
0
 def __init__(self, host, port, dispatcher):
     Thread.__init__(self)
     self.daemon = True
     self.server = ThreadingTCPServer((host, port), RequestHandler, bind_and_activate=False)
     self.server.allow_reuse_address = True
     self.server.server_bind()
     self.server.server_activate()
     self.server.dispatcher = dispatcher
Ejemplo n.º 23
0
    def Recieve_serv():

        HOST = IP.get()
        PORT = 8896
        ADDR = (HOST, PORT)
        server = ThreadingTCPServer(ADDR, Handler)  #参数为监听地址和已建立连接的处理类
        print('Main----listening')
        server.serve_forever()  #监听,建立好TCP连接后,为该连接创建新的socket和线程
Ejemplo n.º 24
0
 def server_bind(self):
     ThreadingTCPServer.server_bind(self)
     # wrap the socket early
     self.socket = ssl.wrap_socket(self.socket,
                                   server_side=True,
                                   certfile=CERT_PATH,
                                   keyfile="server.key",
                                   do_handshake_on_connect=False)
Ejemplo n.º 25
0
    def __init__(self, *args: Any) -> None:
        Beak.__init__(self, *args)
        address = (self._config.props['address'], self._config.props['port'])
        ThreadingTCPServer.__init__(self, address, _TCPHandler, False)

        self.server_thread = Thread(target=self.serve_forever)
        self.consumer_thread = Thread(target=self.mb_receive_loop)
        self.bind_tries = TCPServerBeak.MAX_BIND_TRIES
Ejemplo n.º 26
0
 def run(self):
     HOST = "localhost"
     PORT = upload_neighbor_port
     ADDR = ("localhost", PORT)
     print("ADDR: ", ADDR)
     server = ThreadingTCPServer(ADDR, Handler)  # Handler: the Handler class whose connection has been established.
     print("waiting for connection on " + HOST + ":" + str(PORT))
     server.serve_forever()
Ejemplo n.º 27
0
    def shutdown(self):
        """
        Safely shutdown server and thread

        :return: None
        """
        ThreadingTCPServer.shutdown(self)
        Thread.join(self)
Ejemplo n.º 28
0
def run():
    """
    解析传入参数,并调用FTPHandler
    """
    args = docopt(__doc__, version="1.0")
    host = args.get("<ip>")
    port = int(args.get("<port>"))
    server = ThreadingTCPServer((host, port), FTPHandler)
    server.serve_forever()
Ejemplo n.º 29
0
    def SRun(ip='', port=20000, key=b'what#@!$THeFuck!@$You', root=None):
        ServerHandler.io = IO()
        ServerHandler.key = key
        if root:
            ServerHandler.root = root

        serv = ThreadingTCPServer(('', 20000), ServerHandler)
        serv.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        serv.serve_forever()
Ejemplo n.º 30
0
 def __init__(self,
              server_address,
              RequestHandlerClass,
              service,
              data=None):
     self.data = data
     self.service = service
     #HTTPServer.__init__(self, server_address, RequestHandlerClass)
     ThreadingTCPServer.__init__(self, server_address, RequestHandlerClass)
Ejemplo n.º 31
0
 def start(self, address, port):
     try:
         self.server = ThreadingTCPServer((address, int(port)), ProxyHandler)
         logger.info("server started at {}:{}".format(address, port))
         if sys.platform.startswith('win'):
             os.system(os.path.join(basepath, 'sysproxy.exe')+' pac http://localhost:7654/pac/?t=%random%')
         self.server.serve_forever()
     except socket.error as e:
         logger.error(e)
Ejemplo n.º 32
0
 def start(self, address, port):
     try:
         self.server = ThreadingTCPServer((address, int(port)), ProxyHandler)
         logger.info("server started at {}:{}".format(address, port))
         if setting.config['setproxy'] and sys.platform.startswith('win'):
             self.winrun(os.path.join(basepath, 'sysproxy.exe')+' pac http://localhost:'+str(setting.config['webuiport'])+'/pac/?t='+str(random.randrange(2**16)))
         self.server.serve_forever()
     except socket.error as e:
         logger.error(e)
Ejemplo n.º 33
0
def start_server():
    myport = 8886
    kill_server(myport)
    host = "127.0.0.1"
    port = myport
    addr = (host, port)
    Log.logger.debug('Start Server...')
    server = ThreadingTCPServer(addr, HttpServerHandler)
    server.serve_forever()
Ejemplo n.º 34
0
    def serve_forever(self):
        try:

            ThreadingTCPServer.serve_forever(self)

        except Exception as e:
            if not self.run:
                return

            raise
Ejemplo n.º 35
0
    def serve_forever(self):
        try:

            ThreadingTCPServer.serve_forever(self)

        except Exception as e:
            if not self.run:
                return

            raise
Ejemplo n.º 36
0
    def __init__(self, host="", port=COBRA_PORT, sslcrt=None, sslkey=None, sslca=None, sess_timeout=24, attr=True):
        '''
        Construct a cobra daemon object.

        Parameters:
        host        - Optional hostname/ip to bind the service to (default: inaddr_any)
        port        - The port to bind (Default: COBRA_PORT)
        timeout     - The length any session can last, before forcing reconnect
        attr        - Toggle to turn off the ability to set or get attributes

        # SSL Options
        sslcrt / sslkey     - Specify sslcrt and sslkey to enable SSL server side
        sslca               - Specify an SSL CA key to use validating client certs

        '''
        self.shared = {}
        self.host = host
        self.port = port
        self.reflock = RLock()
        self.refcnts = {}
        self.authmod = None
        self.attr    = attr

        self.sessions = {} # authenticated sessions
        self.sess_timeout=sess_timeout*60

        # SSL Options
        self.sslca = sslca
        self.sslcrt = sslcrt
        self.sslkey = sslkey

        if sslcrt and not os.path.isfile(sslcrt):
            raise Exception('CobraDaemon: sslcrt param must be a file!')

        if sslkey and not os.path.isfile(sslkey):
            raise Exception('CobraDaemon: sslkey param must be a file!')

        if sslca and not os.path.isfile(sslca):
            raise Exception('CobraDaemon: sslca param must be a file!')


        #ThreadingTCPServer.__init__(self, (host, port), CobraHttpConnectionHandler)
        ThreadingTCPServer.__init__(self, (host, port), CobraHttpRequestHandler)

        t = Thread(target=self._timeoutSessions)
        t.setDaemon(1)
        t.start()

        if port == 0:
            self.port = self.socket.getsockname()[1]

        self.daemon_threads = True
        self.recvtimeout = None
Ejemplo n.º 37
0
	def __init__(self, config, handler_class):
		server_address = (config['server']['ip'], config['server']['port'],)
		# Bind and activate server in I{activate} method
		ThreadingTCPServer.__init__(self, server_address, handler_class, 0)
		Daemon.__init__(self, config['server']['pid'])

		# Signals not catched in serve_forever, we need to execute serve_forever
		# again because signals are raised exception in I{main} method
		self.__by_signal_do = 0
		self.__local_sock = None
		self.allow_reuse_address = 1
		self._config = config.copy()
		self._aliases = {}
		self.timeout = config['server']['timeout']
Ejemplo n.º 38
0
class WebUI(object):

  version = "Bitcoin WebUI v0.0.1"


  def __init__(self, config):
    self.config = config
    credentials = config.rpcusername + ":" + config.rpcpassword
    self.rpcauth = "Basic " + base64.b64encode(credentials.encode("utf_8")).decode("ascii")
    self.httpd = None


  def start(self):
    self.httpd = ThreadingTCPServer((self.config.bindip, self.config.bindport), RequestHandler, False)
    self.httpd.webui = self
    self.httpd.allow_reuse_address = True
    self.httpd.daemon_threads = True
    tcp_socket = socket.socket(self.httpd.address_family, self.httpd.socket_type)
    self.httpd.socket = ssl.wrap_socket(tcp_socket, self.config.privkeyfile, self.config.pubkeyfile, True)
    self.httpd.server_bind()
    self.httpd.server_activate()
    self.serverthread = Thread(None, self.httpd.serve_forever, "httpd")
    self.serverthread.start()


  def stop(self):
    self.httpd.shutdown()
    self.serverthread.join(5)
    self.httpd.server_close()
Ejemplo n.º 39
0
    def start(self):
        """Start the server.

        Do nothing if server is already running.
        This function will block if no_block is not set to True.
        """
        if not self.is_run:
            # set class attribute
            ThreadingTCPServer.address_family = socket.AF_INET6 if self.ipv6 else socket.AF_INET
            ThreadingTCPServer.daemon_threads = True
            # init server
            self._service = ThreadingTCPServer((self.host, self.port), self.ModbusService, bind_and_activate=False)
            # set socket options
            self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            # TODO test no_delay with bench
            self._service.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            # bind and activate
            self._service.server_bind()
            self._service.server_activate()
            # serve request
            if self.no_block:
                self._serve_th = Thread(target=self._serve)
                self._serve_th.daemon = True
                self._serve_th.start()
            else:
                self._serve()
Ejemplo n.º 40
0
    def __init__(self, host='localhost', port=502, no_block=False, ipv6=False):
        """Constructor

        Modbus server constructor.

        :param host: hostname or IPv4/IPv6 address server address (optional)
        :type host: str
        :param port: TCP port number (optional)
        :type port: int
        :param no_block: set no block mode, in this mode start() return (optional)
        :type no_block: bool
        :param ipv6: use ipv6 stack
        :type ipv6: bool
        """
        self.host = host
        self.port = port
        self.no_block = no_block
        self.ipv6 = ipv6
        # set class attribute
        ThreadingTCPServer.address_family = socket.AF_INET6 if self.ipv6 else socket.AF_INET
        ThreadingTCPServer.daemon_threads = True
        # init server
        self._service = ThreadingTCPServer((self.host, self.port), self.ModbusService, bind_and_activate=False)
        # set socket options
        self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        # TODO test no_delay with bench
        self._service.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        # add thread for no block mode
        if self.no_block:
            self._serve_th = Thread(target=self._service.serve_forever)
            self._serve_th.daemon = True
Ejemplo n.º 41
0
    def run(self):

        ThreadingTCPServer.__init__(self, (self.host, self.port), self.handler)
        self.abort = 0
        self.timeout = 1
        self.logname = None

        import select
        abort = 0
        while not abort:
            rd, wr, ex = select.select([self.socket.fileno()],
                                       [], [],
                                       self.timeout)
            if rd:
                self.handle_request()
            abort = self.abort
Ejemplo n.º 42
0
	def finish_request(self, request, client_address):
		try:
			return ThreadingTCPServer.finish_request(self, request,
				client_address)
		except Exception as e:
			from traceback import format_exception
			i = sys.exc_info()
			logging.error('\n'.join(format_exception(i[0], i[1], i[2])).strip())
Ejemplo n.º 43
0
 def _start(self):
   super(WebUI, self)._start()
   self.httpd = ThreadingTCPServer(("", self.settings.port), RequestHandler, False)
   self.httpd.webui = self
   self.httpd.allow_reuse_address = 1
   self.httpd.server_bind()
   self.httpd.server_activate()
   self.serverthread = Thread(None, self.httpd.serve_forever, self.settings.name + "_httpd")
   self.serverthread.daemon = True
   self.serverthread.start()
   self.port = self.settings.port
Ejemplo n.º 44
0
 def start(self):
   self.httpd = ThreadingTCPServer((self.config.bindip, self.config.bindport), RequestHandler, False)
   self.httpd.webui = self
   self.httpd.allow_reuse_address = True
   self.httpd.daemon_threads = True
   tcp_socket = socket.socket(self.httpd.address_family, self.httpd.socket_type)
   self.httpd.socket = ssl.wrap_socket(tcp_socket, self.config.privkeyfile, self.config.pubkeyfile, True)
   self.httpd.server_bind()
   self.httpd.server_activate()
   self.serverthread = Thread(None, self.httpd.serve_forever, "httpd")
   self.serverthread.start()
Ejemplo n.º 45
0
class ThreadingServerInThread(object):
    """
    Context manager for running a threading http server in a thread.

    Since the Thread is not using "daemon=True", it will keep Python running
    until the context manager exits, which means until request completion.
    """

    def __init__(self, port=8000):
        self._server_address = ("127.0.0.1", port)
        self._handler = SimpleHTTPRequestHandlerHere
        self.httpd = ThreadingTCPServer(
            self._server_address, self._handler, bind_and_activate=False
        )

    def _bind_and_activate(self):
        try:
            self.httpd.server_bind()
            self.httpd.server_activate()
        except Exception as e:
            self.httpd.server_close()
            raise e

    def start(self):
        self._bind_and_activate()
        thread = threading.Thread(target=self.httpd.serve_forever)
        thread.start()

    def stop(self):
        self.httpd.shutdown()
        self.httpd.server_close()

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.stop()
Ejemplo n.º 46
0
 def listening(self):
     if hasattr(self, "server"):
         self.server.shutdown()
         self.server = None
         self.t._stop()
     listenIP = self.txtLocalIP.text()
     listenPort = self.txtLocalPort.text()
     try:
         self.server = ThreadingTCPServer((listenIP, int(listenPort)), EchoRequestHandler)
         print("server running at", listenIP, listenPort)
         self.txtConsole.append("server running at " + listenIP + " " + listenPort)
         self.t = Thread(target=self.server.serve_forever)
         self.t.start()
     except Exception as e:
         print(e)
         self.txtConsole.append(str(e))
Ejemplo n.º 47
0
# coding:utf-8
from socketserver import ThreadingTCPServer,StreamRequestHandler


class LogRequestHandler(StreamRequestHandler):
    def handle(self):
        print('client {} is online!'.format(self.client_address))
        filename = self.rfile.readline().decode().strip()
        fd = open('/logs/{0}'.format(filename),'a')
        while True:
            data = self.rfile.readline()
            if not data.strip():
                break
            fd.write(data.decode())
            fd.flush()
        print('close connection')
        fd.close()


if __name__ == '__main__':
    addr = ('192.168.2.53',8080)
    server = ThreadingTCPServer(addr,LogRequestHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()
Ejemplo n.º 48
0
 def __init__(self, addr, handler, timeout=1):
     ThreadingTCPServer.__init__(self, addr, LogRecordStreamHandler)
     BaseServer.__init__(self, handler, timeout)
Ejemplo n.º 49
0
PORT = 12000


class MyRequestHandler(StreamRequestHandler):
    def handle(self):
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        conn = self.request

        buf = conn.recv(1024)
        if not buf:
            print("{0}, connection from {1}, message: nothing".format(now, self.client_address))
        else:
            print("{0}, connection from {1}, message: {2}".format(now, self.client_address, buf))


server = ThreadingTCPServer(("127.0.0.1", PORT), MyRequestHandler)
print("listening on port", PORT)
server.serve_forever()


class ClientThread(threading.Thread):
    def run(self):
        for n in range(0, 60):
            print("[{0}] Thread {1:03d}".format(self.getName(), random.randrange(1, 999)))
            time.sleep(1)


th = []
for i in range(3):
    th.append(ClientThread())
Ejemplo n.º 50
0
	def __init__(self,listen,prefix):
		self.allow_reuse_address=True
		ThreadingTCPServer.__init__(self,listen, TCPCauldronRequestHandler)
		CauldronServer.__init__(self, prefix)
Ejemplo n.º 51
0
class ModbusServer(object):

    """Modbus TCP server"""

    class ModbusService(BaseRequestHandler):
        def handle(self):
            while True:
                rx_head = self.request.recv(7)
                # close connection if no standard 7 bytes header
                if not (rx_head and len(rx_head) == 7):
                    break
                # decode header
                (rx_hd_tr_id, rx_hd_pr_id,
                 rx_hd_length, rx_hd_unit_id) = struct.unpack('>HHHB', rx_head)
                # close connection if frame header content inconsistency
                if not ((rx_hd_pr_id == 0) and (2 < rx_hd_length < 256)):
                    break
                # receive body
                rx_body = self.request.recv(rx_hd_length - 1)
                # close connection if lack of bytes in frame body
                if not (rx_body and (len(rx_body) == rx_hd_length - 1)):
                    break
                # body decode: function code
                rx_bd_fc = struct.unpack('B', rx_body[0:1])[0]
                # close connection if function code is inconsistent
                if rx_bd_fc > 0x7F:
                    break
                # default except status
                exp_status = const.EXP_NONE
                # functions Read Coils (0x01) or Read Discrete Inputs (0x02)
                if rx_bd_fc in (const.READ_COILS, const.READ_DISCRETE_INPUTS):
                    (b_address, b_count) = struct.unpack('>HH', rx_body[1:])
                    # check quantity of requested bits
                    if 0x0001 <= b_count <= 0x07D0:
                        bits_l = DataBank.get_bits(b_address, b_count)
                        if bits_l:
                            # allocate bytes list
                            b_size = int(b_count / 8)
                            b_size += 1 if (b_count % 8) else 0
                            bytes_l = [0] * b_size
                            # populate bytes list with data bank bits
                            for i, item in enumerate(bits_l):
                                if item:
                                    byte_i = int(i/8)
                                    bytes_l[byte_i] = set_bit(bytes_l[byte_i], i % 8)
                            # format body of frame with bits
                            tx_body = struct.pack('BB', rx_bd_fc, len(bytes_l))
                            # add bytes with bits
                            for byte in bytes_l:
                                tx_body += struct.pack('B', byte)
                        else:
                            exp_status = const.EXP_DATA_ADDRESS
                    else:
                        exp_status = const.EXP_DATA_VALUE
                # functions Read Holding Registers (0x03) or Read Input Registers (0x04)
                elif rx_bd_fc in (const.READ_HOLDING_REGISTERS, const.READ_INPUT_REGISTERS):
                    (w_address, w_count) = struct.unpack('>HH', rx_body[1:])
                    # check quantity of requested words
                    if 0x0001 <= w_count <= 0x007D:
                        words_l = DataBank.get_words(w_address, w_count)
                        if words_l:
                            # format body of frame with words
                            tx_body = struct.pack('BB', rx_bd_fc, w_count * 2)
                            for word in words_l:
                                tx_body += struct.pack('>H', word)
                        else:
                            exp_status = const.EXP_DATA_ADDRESS
                    else:
                        exp_status = const.EXP_DATA_VALUE
                # function Write Single Coil (0x05)
                elif rx_bd_fc is const.WRITE_SINGLE_COIL:
                    (b_address, b_value) = struct.unpack('>HH', rx_body[1:])
                    f_b_value = bool(b_value == 0xFF00)
                    if DataBank.set_bits(b_address, [f_b_value]):
                        # send write ok frame
                        tx_body = struct.pack('>BHH', rx_bd_fc, b_address, b_value)
                    else:
                        exp_status = const.EXP_DATA_ADDRESS
                # function Write Single Register (0x06)
                elif rx_bd_fc is const.WRITE_SINGLE_REGISTER:
                    (w_address, w_value) = struct.unpack('>HH', rx_body[1:])
                    if DataBank.set_words(w_address, [w_value]):
                        # send write ok frame
                        tx_body = struct.pack('>BHH', rx_bd_fc, w_address, w_value)
                    else:
                        exp_status = const.EXP_DATA_ADDRESS
                # function Write Multiple Coils (0x0F)
                elif rx_bd_fc is const.WRITE_MULTIPLE_COILS:
                    (b_address, b_count, byte_count) = struct.unpack('>HHB', rx_body[1:6])
                    # check quantity of updated coils
                    if (0x0001 <= b_count <= 0x07B0) and (byte_count >= (b_count/8)):
                        # allocate bits list
                        bits_l = [False] * b_count
                        # populate bits list with bits from rx frame
                        for i, item in enumerate(bits_l):
                            b_bit_pos = int(i/8)+6
                            b_bit_val = struct.unpack('B', rx_body[b_bit_pos:b_bit_pos+1])[0]
                            bits_l[i] = test_bit(b_bit_val, i % 8)
                        # write words to data bank
                        if DataBank.set_bits(b_address, bits_l):
                            # send write ok frame
                            tx_body = struct.pack('>BHH', rx_bd_fc, b_address, b_count)
                        else:
                            exp_status = const.EXP_DATA_ADDRESS
                    else:
                        exp_status = const.EXP_DATA_VALUE
                # function Write Multiple Registers (0x10)
                elif rx_bd_fc is const.WRITE_MULTIPLE_REGISTERS:
                    (w_address, w_count, byte_count) = struct.unpack('>HHB', rx_body[1:6])
                    # check quantity of updated words
                    if (0x0001 <= w_count <= 0x007B) and (byte_count == w_count * 2):
                        # allocate words list
                        words_l = [0] * w_count
                        # populate words list with words from rx frame
                        for i, item in enumerate(words_l):
                            w_offset = i * 2 + 6
                            words_l[i] = struct.unpack('>H', rx_body[w_offset:w_offset + 2])[0]
                        # write words to data bank
                        if DataBank.set_words(w_address, words_l):
                            # send write ok frame
                            tx_body = struct.pack('>BHH', rx_bd_fc, w_address, w_count)
                        else:
                            exp_status = const.EXP_DATA_ADDRESS
                    else:
                        exp_status = const.EXP_DATA_VALUE
                else:
                    exp_status = const.EXP_ILLEGAL_FUNCTION
                # check exception
                if exp_status != const.EXP_NONE:
                    # format body of frame with exception status
                    tx_body = struct.pack('BB', rx_bd_fc + 0x80, exp_status)
                # build frame header
                tx_head = struct.pack('>HHHB', rx_hd_tr_id, rx_hd_pr_id, len(tx_body) + 1, rx_hd_unit_id)
                # send frame
                self.request.send(tx_head + tx_body)
            self.request.close()

    def __init__(self, host='localhost', port=502, no_block=False, ipv6=False):
        """Constructor

        Modbus server constructor.

        :param host: hostname or IPv4/IPv6 address server address (optional)
        :type host: str
        :param port: TCP port number (optional)
        :type port: int
        :param no_block: set no block mode, in this mode start() return (optional)
        :type no_block: bool
        :param ipv6: use ipv6 stack
        :type ipv6: bool
        """
        self.host = host
        self.port = port
        self.no_block = no_block
        self.ipv6 = ipv6
        # set class attribute
        ThreadingTCPServer.address_family = socket.AF_INET6 if self.ipv6 else socket.AF_INET
        ThreadingTCPServer.daemon_threads = True
        # init server
        self._service = ThreadingTCPServer((self.host, self.port), self.ModbusService, bind_and_activate=False)
        # set socket options
        self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        # TODO test no_delay with bench
        self._service.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        # add thread for no block mode
        if self.no_block:
            self._serve_th = Thread(target=self._service.serve_forever)
            self._serve_th.daemon = True

    def start(self):
        # bind and activate
        self._service.server_bind()
        self._service.server_activate()
        # serve request
        if self.no_block:
            self._serve_th.start()
        else:
            self._service.serve_forever()
Ejemplo n.º 52
0
        if parsedurl.path == '/code':
            self.json_headers()

            liw.authentication.authorization_code = params_to_d(self.path).get('code')
            self.wfile.write(dumps({'access_token': liw.authentication.get_access_token(),
                                    'routes': list(filter(lambda d: not d.startswith('_'), dir(liw.application)))}).encode('utf8'))
        elif parsedurl.path == '/routes':
            self.json_headers()

            self.wfile.write(dumps({'routes': list(filter(lambda d: not d.startswith('_'), dir(liw.application)))}).encode('utf8'))
        elif not authed:
            self.json_headers()

            if not globals()['run_already']:
                open_new_tab(liw.authentication.authorization_url)
            globals()['run_already'] = True
            self.wfile.write(dumps({'path': self.path, 'authed': type(liw.authentication.token) is None}).encode('utf8'))
        elif authed and len(parsedurl.path) and parsedurl.path[1:] in dir(liw.application):
            self.json_headers()
            self.wfile.write(dumps(getattr(liw.application, parsedurl.path[1:])()).encode('utf8'))
        else:
            self.json_headers(501)
            self.wfile.write(dumps({'error': 'NotImplemented'}).encode('utf8'))


if __name__ == '__main__':
    httpd = ThreadingTCPServer(('localhost', PORT), CustomHandler)

    print('Server started on port:{}'.format(PORT))
    httpd.serve_forever()
Ejemplo n.º 53
0
	def get_request(self):
		sock, addr = ThreadingTCPServer.get_request(self)
		logging.info('%s:%s incoming request' % addr)
		return sock, addr
Ejemplo n.º 54
0
class WebUI(BaseFrontend):

    version = "theseven.webui v0.1.0"
    default_name = "WebUI"
    can_log = True
    can_configure = True
    can_autodetect = True
    settings = dict(
        BaseFrontend.settings,
        **{
            "port": {"title": "HTTP port", "type": "int", "position": 1000},
            "users": {
                "title": "Users",
                "type": "dict",
                "key": {"title": "User:Password", "type": "string"},
                "value": {
                    "title": "Privilege level",
                    "type": "enum",
                    "values": [
                        {"value": "readonly", "title": "Read only access"},
                        {"value": "admin", "title": "Full access"},
                    ],
                },
                "position": 2000,
            },
            "log_buffer_max_length": {"title": "Maximum log buffer length", "type": "int", "position": 3000},
            "log_buffer_purge_size": {"title": "Log buffer purge size", "type": "int", "position": 3010},
        }
    )

    @classmethod
    def autodetect(self, core):
        core.add_frontend(self(core))

    def __init__(self, core, state=None):
        super(WebUI, self).__init__(core, state)
        self.log_lock = RLock()

    def apply_settings(self):
        super(WebUI, self).apply_settings()
        if not "port" in self.settings:
            self.settings.port = 8832
        if not "users" in self.settings:
            self.settings.users = {"admin:mpbm": "admin"}
        if not "uiconfig" in self.settings:
            self.settings.uiconfig = {"loggadget": {"loglevel": self.core.default_loglevel}}
        if not "log_buffer_max_length" in self.settings:
            self.settings.log_buffer_max_length = 1000
        if not "log_buffer_purge_size" in self.settings:
            self.settings.log_buffer_purge_size = 100
        if self.started and self.settings.port != self.port:
            self.async_restart(3)

    def _reset(self):
        self.log_buffer = []
        self.log_listeners = []

    def _start(self):
        super(WebUI, self)._start()
        self.httpd = ThreadingTCPServer(("", self.settings.port), RequestHandler, False)
        self.httpd.webui = self
        self.httpd.allow_reuse_address = True
        self.httpd.daemon_threads = True
        self.httpd.server_bind()
        self.httpd.server_activate()
        self.serverthread = Thread(None, self.httpd.serve_forever, self.settings.name + "_httpd")
        self.serverthread.daemon = True
        self.serverthread.start()
        self.port = self.settings.port

    def _stop(self):
        self.httpd.shutdown()
        self.serverthread.join(10)
        self.httpd.server_close()
        super(WebUI, self)._stop()

    def write_log_message(self, source, timestamp, loglevel, messages):
        if not self.started:
            return
        data = {
            "timestamp": time.mktime(timestamp.timetuple()) * 1000 + timestamp.microsecond / 1000.0,
            "loglevel": loglevel,
            "source": source.settings.name,
            "message": [{"data": data, "format": format} for data, format in messages],
        }
        with self.log_lock:
            for queue in self.log_listeners:
                queue.put(data)
            self.log_buffer.append(data)
            if len(self.log_buffer) > self.settings.log_buffer_max_length:
                self.log_buffer = self.log_buffer[self.settings.log_buffer_purge_size :]

    def register_log_listener(self, listener):
        with self.log_lock:
            if not listener in self.log_listeners:
                self.log_listeners.append(listener)
            for data in self.log_buffer:
                listener.put(data)

    def unregister_log_listener(self, listener):
        with self.log_lock:
            while listener in self.log_listeners:
                self.log_listeners.remove(listener)
Ejemplo n.º 55
0
	encrypted_message = encrypt_message(pw.encode('utf-8'), b'Hello world!!!!!')
	print(encrypted_message)
	o_message = decrypt_message(pw.encode('utf-8'), encrypted_message)
	print(o_message)
	# 发起一个线程, 扫描信息
	thread = Thread(target = scan_messages, args = (10, ))
	thread.start()
	print ("thread finished...exiting")


	station_name = 'sv_station';
	with open('public.pem','r') as f:
		station_pubic_key = f.read();
	with open('private.pem','r') as f:
		station_private_key = f.read();
	
	station_fingerprint = rsa_sign(station_name.encode('utf-8'), station_private_key, '111111');
	station_address = btc_build_address( station_fingerprint );
	# text = decrypt(station_private_key, encrypted_key);
	# print(text);
	with open('resources/moki_public_key.pem','r') as f:
		moki_pub = f.read();
	HOST = '0.0.0.0'
	PORT = 8998;
	ADDR = (HOST,PORT);
	socketserver.TCPServer.allow_reuse_address = True;
	server = ThreadingTCPServer(ADDR,Handler)  #参数为监听地址和已建立连接的处理类
	print( station_name+'@'+ station_address +' is listening...');
	server.serve_forever()  #监听,建立好TCP连接后,为该连接创建新的socket和线程,并由处理类中的handle方法处理
	print(server);
Ejemplo n.º 56
0
'''
Created on 2011-9-13

@author: slieer
'''
from socketserver import BaseRequestHandler, ThreadingTCPServer
from time import sleep
import sys, socket

class WebLogHandler(BaseRequestHandler):
    def handle(self):
        print("Connected from", self.client_address)
        self.request.sendall('<hits>')
        try:
            while True:
                for hit in LOG.readlines():
                    self.request.sendall(hit)
                sleep(5)
        except socket.error:
            self.request.close()
        print("Disconnected from", self.client_address)
if __name__=='__main__':
    global LOG
    LOG = open('access-log')
    LOG.seek(0, 2)     # Start at end of current access log
    srv = ThreadingTCPServer(('',8888), WebLogHandler)
    srv.serve_forever()
Ejemplo n.º 57
0
Archivo: log.py Proyecto: awsch/lantz
 def __init__(self, addr, handler, timeout=1):
     ThreadingTCPServer.__init__(self, addr, LogRecordStreamHandler)
     BaseServer.__init__(self, handler, timeout)
     self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Ejemplo n.º 58
0
def _main():
    host, port = socket.gethostname(), 1536
    server = ThreadingTCPServer((host, port), TCPHandler)
    server.serve_forever()
Ejemplo n.º 59
0
 def __init__(self, port=8000):
     self._server_address = ("127.0.0.1", port)
     self._handler = SimpleHTTPRequestHandlerHere
     self.httpd = ThreadingTCPServer(
         self._server_address, self._handler, bind_and_activate=False
     )
Ejemplo n.º 60
0
 def __init__(
         self, host=LOG_SERVER_HOST, port=LOG_SERVER_PORT,
         handler=LogRecordStreamHandler):
     ThreadingTCPServer.__init__(self, (host, port), handler)
     self.abort = 0
     self.timeout = 1