def init(self, source, target, secure=False): self._source = source self._target = target self._secure = secure self._clients = dict() self._sockets = dict() # Setup our components and register them. server = TCPServer(self._source, secure=self._secure, channel="source") server.register(self)
def __init__(self, tcp_updater_sett_entity=SettingsEntity(""), **kwargs): self.tcp_conn = tcp_updater_sett_entity.get_settings() TCPServer.__init__(self, **self.tcp_conn, **kwargs) self.negotiator = TransmissionNegotiation() self.data_assembly = DataAssembly() self.data_processor = UpdaterDataProcessor() self.stdio = self.write_line self.stderr = self.on_error EventlessUpdaterTCPServer.__init__(self, negotiator=self.negotiator, data_assembly=self.data_assembly, data_processor=self.data_processor, stdio=self.stdio, stderr=self.stderr, **self.tcp_conn, **kwargs)
def init(self, args, opts): """Initialize our ``ChatServer`` Component. This uses the convenience ``init`` method which is called after the component is properly constructed and initialized and passed the same args and kwargs that were passed during construction. """ self.args = args self.opts = opts self.clients = {} if opts.debug: Debugger().register(self) if ":" in opts.bind: address, port = opts.bind.split(":") port = int(port) else: address, port = opts.bind, 8000 bind = (address, port) TCPServer(bind).register(self)
def init(self, args, logger=None): self.args = args self.logger = logger or getLogger(__name__) self.buffers = defaultdict(bytes) self.nicks = {} self.users = {} self.channels = {} Debugger(events=args.debug, logger=self.logger).register(self) if ":" in args.bind: address, port = args.bind.split(":") port = int(port) else: address, port = args.bind, 6667 bind = (address, port) self.transport = TCPServer( bind, channel=self.channel ).register(self) self.protocol = IRC( channel=self.channel, getBuffer=self.buffers.__getitem__, updateBuffer=self.buffers.__setitem__ ).register(self)
def __init__(self, *args): """ Initialize the bus repeater component. :param args: """ super(BusRepeater, self).__init__('BUSREPEATER', *args) self._tcp_socket = self._udp_socket = None self._connected_tcp_endpoints = [] if self.config.tcp_port != 0 and \ self.config.tcp_ip is not None and \ self.config.tcp_enabled is True: address = self.config.tcp_ip + ':' + str(self.config.tcp_port) self.log('Opening listening socket on', address, lvl=debug) self._tcp_socket = TCPServer(address, channel=self.channel + '_tcp').register(self) if len(self.config.udp_endpoints) > 0 and \ self.config.udp_enabled is True: address = self.config.udp_ip + ':' + str(self.config.udp_port) self.log('Registering udp socket on', address, lvl=debug) self._udp_socket = UDPClient(0, channel=self.channel + '_udp').register(self)
def test_tcps_basic(manager, watcher, client, Poller, ipv6): poller = Poller().register(manager) if ipv6: tcp_server = TCP6Server(("::1", 0), secure=True, certfile=CERT_FILE) else: tcp_server = TCPServer(0, secure=True, certfile=CERT_FILE) server = Server() + tcp_server server.register(manager) try: watcher.wait("ready", "server") client.connect(server.host, server.port) assert watcher.wait("connect", "server") assert client.recv() == b"Ready" client.send(b"foo") assert watcher.wait("read", "server") assert client.recv() == b"foo" client.disconnect() assert watcher.wait("disconnect", "server") server.fire(close()) assert watcher.wait("closed", "server") finally: poller.unregister() server.unregister()
def init(self, args): self.args = args self.logger = getLogger(__name__) if args.debug: self += Debugger(channel=self.channel, IgnoreEvents=['_read', '_write', 'ping']) self += stdin #self += Debugger(logger=self.logger, channel=self.channel) self.buffers = defaultdict(bytes) self.nicks = {} self.users = {} self.channels = {} if ':' in args.bind: address, port = args.bind.split(':', 1) port = int(port) else: address, port = args.bind, 6667 self.transport = TCPServer(bind=(address, port), channel=self.channel).register(self) self.protocol = IRC( channel=self.channel, getBuffer=self.buffers.__getitem__, updateBuffer=self.buffers.__setitem__).register(self)
def test_tcp_reconnect(Poller, ipv6): # XXX: Apparently this doesn't work on Windows either? # XXX: UPDATE: Apparently Broken on Windows + Python 3.2 # TODO: Need to look into this. Find out why... if pytest.PLATFORM == "win32" and pytest.PYVER[:2] >= (3, 2): pytest.skip("Broken on Windows on Python 3.2") m = Manager() + Poller() if ipv6: tcp_server = TCP6Server(("::1", 0)) tcp_client = TCP6Client() else: tcp_server = TCPServer(0) tcp_client = TCPClient() server = Server() + tcp_server client = Client() + tcp_client server.register(m) client.register(m) m.start() try: assert pytest.wait_for(client, "ready") assert pytest.wait_for(server, "ready") wait_host(server) # 1st connect client.fire(connect(server.host, server.port)) assert pytest.wait_for(client, "connected") assert pytest.wait_for(server, "connected") assert pytest.wait_for(client, "data", b"Ready") client.fire(write(b"foo")) assert pytest.wait_for(server, "data", b"foo") # disconnect client.fire(close()) assert pytest.wait_for(client, "disconnected") # 2nd reconnect client.fire(connect(server.host, server.port)) assert pytest.wait_for(client, "connected") assert pytest.wait_for(server, "connected") assert pytest.wait_for(client, "data", b"Ready") client.fire(write(b"foo")) assert pytest.wait_for(server, "data", b"foo") client.fire(close()) assert pytest.wait_for(client, "disconnected") assert pytest.wait_for(server, "disconnected") server.fire(close()) assert pytest.wait_for(server, "closed") finally: m.stop()
def init(self, bind, host, port): self.bind = bind self.host = host self.port = port self.clients = dict() TCPServer(self.bind).register(self)
def __init__(self, org_id, host=DEFAULT_TEST_HOST, port=DEFAULT_TEST_PORT): super(ResilientTestActions, self).__init__() self.org_id = org_id bind = (host, port) LOG.debug("Binding test server to %s:%d", host, port) TCPServer(bind).register(self) self.messages_in_progress = {} self.actions_sent = {}
def __init__(self, port, server_ip='0.0.0.0', channel=channel, receive_event_firewall=None, send_event_firewall=None, **kwargs): """Create server on node system. :param port: start server on this port. :type port: int :param server_ip: An optional keyword argument which which define ip where the socket has listen to. **Default:** ``0.0.0.0`` (all ip is allowed) :type server_ip: str :param channel: An optional keyword argument which if defined, set channel used for node event. **Default:** ``node`` :type channel: str :param receive_event_firewall: An optional keyword argument which if defined, set function or method to call to check if event is allowed for sending **Default:** ``None`` (no firewall) :type receive_event_firewall: function :type receive_event_firewall: method :param send_event_firewall: An optional keyword argument which if defined, set function or method to call to check if event is allowed for executing **Default:** ``None`` (no firewall) :type send_event_firewall: function :type send_event_firewall: method """ super(Server, self).__init__(channel=channel, **kwargs) bind = (server_ip, port) self.server = TCPServer(bind, channel=self.channel, **kwargs) self.server.register(self) self.__receive_event_firewall = receive_event_firewall self.__send_event_firewall = send_event_firewall
def __init__(self, bind, **kwargs): super(BaseServer, self).__init__(**kwargs) self.server = (TCPServer(bind, **kwargs) + HTTP()) self += self.server Request.server = self Request.local = Host(self.server.bind[0], self.server.bind[1]) Request.host = self.host print "%s listening on %s" % (self.version, self.base)
def __init__(self): BaseComponent.__init__(self) http = HTTP(channel=self.channel) self += http self += Logger(channel=self.channel) http += TCPServer(('localhost', 8090), channel=self.channel) self.domains = DomainRouter(channel=self.channel) self += self.domains self.localhost = Domain('localhost') self.domains += self.localhost
def test_tcp_bind(Poller, ipv6): m = Manager() + Poller() if ipv6: sock = socket(AF_INET6, SOCK_STREAM) sock.bind(("::1", 0)) sock.listen(5) _, bind_port, _, _ = sock.getsockname() sock.close() server = Server() + TCP6Server(("::1", 0)) client = Client() + TCP6Client() else: sock = socket(AF_INET, SOCK_STREAM) sock.bind(("", 0)) sock.listen(5) _, bind_port = sock.getsockname() sock.close() server = Server() + TCPServer(0) client = Client() + TCPClient() server.register(m) client.register(m) m.start() try: assert pytest.wait_for(client, "ready") assert pytest.wait_for(server, "ready") wait_host(server) client.fire(connect(server.host, server.port)) assert pytest.wait_for(client, "connected") assert pytest.wait_for(server, "connected") assert pytest.wait_for(client, "data", b"Ready") # assert server.client[1] == bind_port client.fire(write(b"foo")) assert pytest.wait_for(server, "data", b"foo") client.fire(close()) assert pytest.wait_for(client, "disconnected") assert pytest.wait_for(server, "disconnected") server.fire(close()) assert pytest.wait_for(server, "closed") finally: m.stop()
def test(): m = Manager() poller = Poller().register(m) TCPServer(0).register(m) TCPClient().register(m) m.start() try: pollers = findtype(m, BasePoller, all=True) assert len(pollers) == 1 assert pollers[0] is poller finally: m.stop()
def test_tcp_connect_closed_port(Poller, ipv6): ### FIXME: This test is wrong. ### We need to figure out the sequence of events on Windows ### for this scenario. I think if you attempt to connect to ### a shutdown listening socket (tcp server) you should get ### an error event as response. if pytest.PLATFORM == "win32": pytest.skip("Broken on Windows") m = Manager() + Poller() if ipv6: tcp_server = TCP6Server(("::1", 0)) tcp_client = TCP6Client() else: tcp_server = TCPServer(0) tcp_client = TCPClient() server = Server() + tcp_server client = Client() + tcp_client server.register(m) client.register(m) m.start() try: assert pytest.wait_for(client, "ready") assert pytest.wait_for(server, "ready") wait_host(server) host, port = server.host, server.port tcp_server._sock.close() # 1st connect client.fire(connect(host, port)) assert pytest.wait_for(client, "connected") assert isinstance(client.error, SocketError) client.fire(write(b"foo")) assert pytest.wait_for(client, "disconnected") client.disconnected = False client.fire(write(b"foo")) assert pytest.wait_for(client, "disconnected", timeout=1.0) is None finally: m.stop()
def test_tcps_basic(Poller, ipv6): from circuits import Debugger m = Manager() + Debugger() + Poller() if ipv6: tcp_server = TCP6Server(("::1", 0), secure=True, certfile=CERT_FILE) tcp_client = TCP6Client() else: tcp_server = TCPServer(0, secure=True, certfile=CERT_FILE) tcp_client = TCPClient() server = Server() + tcp_server client = Client() + tcp_client server.register(m) client.register(m) m.start() try: assert pytest.wait_for(client, "ready") assert pytest.wait_for(server, "ready") wait_host(server) client.fire(connect(server.host, server.port, secure=True)) assert pytest.wait_for(client, "connected") assert pytest.wait_for(server, "connected") assert pytest.wait_for(client, "data", b"Ready") client.fire(write(b"foo")) assert pytest.wait_for(server, "data", b"foo") assert pytest.wait_for(client, "data", b"foo") client.fire(close()) assert pytest.wait_for(client, "disconnected") assert pytest.wait_for(server, "disconnected") server.fire(close()) assert pytest.wait_for(server, "closed") finally: m.stop()
def test_tcp_basic(Poller, ipv6): m = Manager() + Poller() if ipv6: tcp_server = TCP6Server(("::1", 0)) tcp_client = TCP6Client() else: tcp_server = TCPServer(0) tcp_client = TCPClient() server = Server() + tcp_server client = Client() + tcp_client server.register(m) client.register(m) m.start() try: assert pytest.wait_for(client, "ready") assert pytest.wait_for(server, "ready") wait_host(server) client.fire(connect(server.host, server.port)) assert pytest.wait_for(client, "connected") assert pytest.wait_for(server, "connected") assert pytest.wait_for(client, "data", b"Ready") client.fire(write(b"foo")) assert pytest.wait_for(server, "data", b"foo") assert pytest.wait_for(client, "data", b"foo") client.fire(close()) assert pytest.wait_for(client, "disconnected") assert pytest.wait_for(server, "disconnected") server.fire(close()) assert pytest.wait_for(server, "closed") finally: m.stop()
def test_tcp_connect_closed_port(Poller, ipv6): if pytest.PLATFORM == "win32": pytest.skip("Broken on Windows") m = Manager() + Poller() + Debugger() if ipv6: tcp_server = TCP6Server(("::1", 0)) tcp_client = TCP6Client(connect_timeout=1) else: tcp_server = TCPServer(0) tcp_client = TCPClient(connect_timeout=1) server = Server() + tcp_server client = Client() + tcp_client server.register(m) client.register(m) m.start() try: assert pytest.wait_for(client, "ready") assert pytest.wait_for(server, "ready") wait_host(server) host, port = server.host, server.port tcp_server._sock.close() # 1st connect client.fire(connect(host, port)) waiter = WaitEvent(m, "unreachable", channel='client') assert waiter.wait() finally: server.unregister() client.unregister() m.stop()
class Server(BaseComponent): """Node server.""" channel = 'node' __protocols = {} def __init__(self, port, server_ip='0.0.0.0', channel=channel, receive_event_firewall=None, send_event_firewall=None, **kwargs): """Create server on node system. :param port: start server on this port. :type port: int :param server_ip: An optional keyword argument which which define ip where the socket has listen to. **Default:** ``0.0.0.0`` (all ip is allowed) :type server_ip: str :param channel: An optional keyword argument which if defined, set channel used for node event. **Default:** ``node`` :type channel: str :param receive_event_firewall: An optional keyword argument which if defined, set function or method to call to check if event is allowed for sending **Default:** ``None`` (no firewall) :type receive_event_firewall: function :type receive_event_firewall: method :param send_event_firewall: An optional keyword argument which if defined, set function or method to call to check if event is allowed for executing **Default:** ``None`` (no firewall) :type send_event_firewall: function :type send_event_firewall: method """ super(Server, self).__init__(channel=channel, **kwargs) bind = (server_ip, port) self.server = TCPServer(bind, channel=self.channel, **kwargs) self.server.register(self) self.__receive_event_firewall = receive_event_firewall self.__send_event_firewall = send_event_firewall def send(self, event, sock, no_result=False): """Send event to peer :param event: Event to execute remotely. :type event: :class:`circuits.core.events.Event` :param sock: Client's socket (peer selection). :type sock: :class:`socket.socket` :param no_result: An optional keyword argument which if True don't return the event result. **Default:** ``False`` (wait the result) :type no_result: bool :return: The result of remote event :rtype: generator """ iterator = self.__protocols[sock].send(event) if no_result: event.node_without_result = True try: next(iterator) except StopIteration: pass return iterator def send_to(self, event, socks): """Send event to multiple peer :param event: Event to execute remotely. :type event: :class:`circuits.core.events.Event` :param socks: Client's socket list (peer selection). :type socks: list of :class:`socket.socket` """ for sock in socks: self.send(event, sock, no_result=True) def send_all(self, event): """Send event to all peer :param event: Event to execute remotely. :type event: :class:`circuits.core.events.Event` """ self.send_to(event, list(self.__protocols)) @handler('read') def _on_read(self, sock, data): self.__protocols[sock].add_buffer(data) @property def host(self): if hasattr(self, 'server'): return self.server.host @property def port(self): if hasattr(self, 'server'): return self.server.port def get_socks(self): """Get clients sockets list :return: The list of client socket :rtype: list of :class:`socket.socket` """ return list(self.__protocols) @handler('connect') def __connect_peer(self, sock, host, port): self.__protocols[sock] = Protocol( sock=sock, server=self.server, receive_event_firewall=self.__receive_event_firewall, send_event_firewall=self.__send_event_firewall, channel=self.channel).register(self) @handler('disconnect') def __disconnect_peer(self, sock): for s in self.__protocols.copy(): try: s.getpeername() except: del (self.__protocols[s])
def init(self): self.clients = {} self.tcp = TCPServer(("0.0.0.0", 7001), channel="tcp").register(self) self.udp = UDPServer(("0.0.0.0", 7000), channel="udp").register(self)
def test_socket_options_server(): s = TCPServer(('0.0.0.0', 8090), socket_options=[(SOL_SOCKET, SO_REUSEPORT, 1)]) assert s._sock.getsockopt(SOL_SOCKET, SO_REUSEPORT) == 1
""" curl -i https://localhost:8443/ --cacert ~/git/circuits.http/examples/server/ssl/ca-chain.pem -k """ import sys sys.path.insert(0, '.') from circuits import Debugger from circuits.http.server.resource import method from circuits.net.sockets import TCPServer from resource import BaseResource as Resource from server import HTTPServer sslsocket = lambda channel: TCPServer(('', 8443), secure=True, certfile='./ssl/server-cert.pem', keyfile='./ssl/server-key.pem', channel=channel) class Secured(Resource): channel = '/' @method def GET(self, client): return {"message": "This connection uses TLS: %s" % (client.server.secure,)} GET.codec('application/json') if __name__ == '__main__': server = HTTPServer() server += sslsocket(server.channel)
class Server(BaseComponent): """Node server.""" channel = 'node' __protocols = {} def __init__(self, port, server_ip='0.0.0.0', channel=channel, receive_event_firewall=None, send_event_firewall=None, **kwargs): """Create server on node system. :param port: start server on this port. :type port: int :param server_ip: An optional keyword argument which which define ip where the socket has listen to. **Default:** ``0.0.0.0`` (all ip is allowed) :type server_ip: str :param channel: An optional keyword argument which if defined, set channel used for node event. **Default:** ``node`` :type channel: str :param receive_event_firewall: An optional keyword argument which if defined, set function or method to call to check if event is allowed for sending **Default:** ``None`` (no firewall) :type receive_event_firewall: function :type receive_event_firewall: method :param send_event_firewall: An optional keyword argument which if defined, set function or method to call to check if event is allowed for executing **Default:** ``None`` (no firewall) :type send_event_firewall: function :type send_event_firewall: method """ super(Server, self).__init__(channel=channel, **kwargs) bind = (server_ip, port) self.server = TCPServer(bind, channel=self.channel, **kwargs) self.server.register(self) self.__receive_event_firewall = receive_event_firewall self.__send_event_firewall = send_event_firewall def send(self, event, sock, no_result=False): """Send event to peer :param event: Event to execute remotely. :type event: :class:`circuits.core.events.Event` :param sock: Client's socket (peer selection). :type sock: :class:`socket.socket` :param no_result: An optional keyword argument which if True don't return the event result. **Default:** ``False`` (wait the result) :type no_result: bool :return: The result of remote event :rtype: generator """ iterator = self.__protocols[sock].send(event) if no_result: event.node_without_result = True try: next(iterator) except StopIteration: pass return iterator def send_to(self, event, socks): """Send event to multiple peer :param event: Event to execute remotely. :type event: :class:`circuits.core.events.Event` :param socks: Client's socket list (peer selection). :type socks: list of :class:`socket.socket` """ for sock in socks: self.send(event, sock, no_result=True) def send_all(self, event): """Send event to all peer :param event: Event to execute remotely. :type event: :class:`circuits.core.events.Event` """ self.send_to(event, list(self.__protocols)) @handler('read') def _on_read(self, sock, data): self.__protocols[sock].add_buffer(data) @property def host(self): if hasattr(self, 'server'): return self.server.host @property def port(self): if hasattr(self, 'server'): return self.server.port def get_socks(self): """Get clients sockets list :return: The list of client socket :rtype: list of :class:`socket.socket` """ return list(self.__protocols) @handler('connect') def __connect_peer(self, sock, host, port): self.__protocols[sock] = Protocol( sock=sock, server=self.server, receive_event_firewall=self.__receive_event_firewall, send_event_firewall=self.__send_event_firewall, channel=self.channel ).register(self) @handler('disconnect') def __disconnect_peer(self, sock): for s in self.__protocols.copy(): try: s.getpeername() except: del(self.__protocols[s])