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 disconnected(self, event, *args, **kwargs): if event.name == "disconnected": self.fire(disconnected_from(connection_name, hostname, port, client_channel, client)) # auto reconnect if reconnect_delay > 0: Timer(reconnect_delay, connect(hostname, port), client_channel).register(self)
def ready(self, component): """Ready Event This event is triggered by the underlying ``TCPClient`` Component when it is ready to start making a new connection. """ self.fire(connect(self.host, self.port), 'ircbot')
def test_tcp_lookup_failure(Poller, ipv6): m = Manager() + Poller() if ipv6: tcp_client = TCP6Client() else: tcp_client = TCPClient() client = Client() + tcp_client client.register(m) m.start() try: assert pytest.wait_for(client, "ready") client.fire(connect("foo", 1234)) assert pytest.wait_for( client, "error", lambda obj, attr: isinstance(getattr(obj, attr), SocketError)) if pytest.PLATFORM == "win32": assert client.error.errno == 11004 else: assert client.error.errno in (EAI_NODATA, EAI_NONAME,) finally: m.stop()
def __init__(self, *args, **opts): super(Telnet, self).__init__() self.args = args self.opts = opts if len(args) == 1: if os.path.exists(args[0]): UNIXClient(channel=self.channel).register(self) host = dest = port = args[0] dest = (dest,) else: raise OSError("Path %s not found" % args[0]) else: if not opts["udp"]: TCPClient(channel=self.channel).register(self) else: UDPClient(0, channel=self.channel).register(self) host, port = args port = int(port) dest = host, port self.host = host self.port = port print("Trying %s ..." % host) if not opts["udp"]: self.fire(connect(*dest, secure=opts["secure"])) else: self.fire(write((host, port), b"\x00"))
def request(self, method, url, body=None, headers=None): host, port, path, secure = parse_url(url) if not self._transport.connected: self.fire(connect(host, port, secure)) yield self.wait("connected", self._transport.channel) headers = Headers([(k, v) for k, v in (headers or {}).items()]) # Clients MUST include Host header in HTTP/1.1 requests (RFC 2616) if "Host" not in headers: headers["Host"] = "{0:s}{1:s}".format( host, "" if port in (80, 443) else ":{0:d}".format(port) ) if body is not None: headers["Content-Length"] = len(body) command = "%s %s HTTP/1.1" % (method, path) message = "%s\r\n%s" % (command, headers) self.fire(write(message.encode('utf-8')), self._transport) if body is not None: self.fire(write(body), self._transport) yield (yield self.wait("response"))
def disconnected(self): """Disconnected Event This event is triggered by the underlying ``TCPClient`` Component when the active connection has been terminated. """ self.fire(connect(self.host, self.port))
def test_tcp_lookup_failure(manager, watcher, Poller, ipv6): poller = Poller().register(manager) if ipv6: tcp_client = TCP6Client() else: tcp_client = TCPClient() client = Client() + tcp_client client.register(manager) try: assert watcher.wait("ready", "client") client.fire(connect("foo.bar.baz", 1234)) assert watcher.wait("error", "client") if pytest.PLATFORM == "win32": assert client.error.errno == 11004 else: assert client.error.errno in ( EAI_NODATA, EAI_NONAME, ) finally: poller.unregister() client.unregister()
def _on_request(self, client): if client.socket is None: host = client.request.uri.host port = client.request.uri.port secure = client.request.uri.scheme == u'https' result = yield self.call( connect(host, port, secure, certfile=client.ssl.cert, keyfile=client.ssl.key, ca_certs=[client.ssl.ca])) if result.errors: reraise(*result.value) client.socket = result.value if not client.socket.connected: yield self.wait("connected", client.socket.channel) try: state = self._buffers[client.socket] except KeyError: return # server disconnected state['requests'].append(client) composer = ComposedRequest(client.request) composer.prepare() for data in composer: self.fire(write(data), client.socket) yield client
def _on_connect(self, host=None, port=None, secure=None, certfile=None, keyfile=None, ca_certs=None): try: socket = self._socket_map[(host, port, secure)] if not socket.connected: raise KeyError except KeyError: socket = TCPClient( channel='%s_%d' % (self.channel, len(self._buffers))).register(self) self._buffers[socket] = { 'parser': ClientStateMachine(), 'socket': socket, 'requests': [], 'responses': [], } self._socket_map[(host, port, secure)] = socket self._channel_sock[socket.channel] = socket if not socket.connected: self.fire( connect(host, port, secure, certfile=certfile, keyfile=keyfile, ca_certs=ca_certs), socket) # event.stop() # FIXME: self.call does conflict with this return socket
def __init__(self, *args, **opts): super(Telnet, self).__init__() self.args = args self.opts = opts if len(args) == 1: if os.path.exists(args[0]): UNIXClient(channel=self.channel).register(self) host = dest = port = args[0] dest = (dest, ) else: raise OSError("Path %s not found" % args[0]) else: if not opts["udp"]: TCPClient(channel=self.channel).register(self) else: UDPClient(0, channel=self.channel).register(self) host, port = args port = int(port) dest = host, port self.host = host self.port = port print("Trying %s ..." % host) if not opts["udp"]: self.fire(connect(*dest, secure=opts["secure"])) else: self.fire(write((host, port), b"\x00"))
def ready(self, component): """Ready Event This event is triggered by the underlying ``TCPClient`` Component when it is ready to start making a new connection. """ self.fire(connect(self.host, self.port))
def _on_response_complete(self, e, value): response = e.args[0] request = response.request if request.sock in self._codecs: self._requests[request.sock] = request cevent = connect(request.sock, *request.sock.getpeername()) cevent.request = request self.fire(cevent, self._wschannel)
def _on_response_complete(self, e, value): response = e.args[0] request = response.request if request.sock in self._codecs: self._sessions[request.sock] = request.session if request.sock in self._codecs: evt = connect(request.sock,*request.sock.getpeername()) evt.kwargs["session"] = request.session self.fire(evt, self._wschannel)
def _on_response_complete(self, e, value): response = e.args[0] request = response.request if request.sock in self._codecs: self._sessions[request.sock] = request.session if request.sock in self._codecs: evt = connect(request.sock, *request.sock.getpeername()) evt.kwargs["session"] = request.session self.fire(evt, self._wschannel)
def _on_target_ready(self, component): """Ready Event Handler This unbound function will be later added as an event handler to a dynamically created and registered client instance and used to process Ready events of a registered client. """ self.fire(connect(*self._target, secure=self._secure), component.channel)
def disconnected(self, event, *args, **kwargs): if event.name == 'disconnected': self.fire( disconnected_from(connection_name, hostname, port, client_channel, client)) # auto reconnect if reconnect_delay > 0: Timer(reconnect_delay, connect(hostname, port), client_channel).register(self)
def _on_response_complete(self, e, value): response = e.args[0] request = response.request if request.sock in self._codecs: self.fire( connect( request.sock, *request.sock.getpeername() ), self._wschannel )
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_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 _on_ready(self, event, *args, **kwargs): p = urlparse(self._url) if not p.hostname: raise ValueError("URL must be absolute") self._host = p.hostname if p.scheme == "ws": self._secure = False self._port = p.port or 80 elif p.scheme == "wss": self._secure = True self._port = p.port or 443 else: raise NotConnected() self._resource = p.path or "/" if p.query: self._resource += "?" + p.query self.fire(connect(self._host, self._port, self._secure), self._transport)
def test_http_1_1_no_host_headers(webapp): transport = TCPClient() client = Client() client += transport client.start() host, port, resource, secure = parse_url(webapp.server.http.base) client.fire(connect(host, port)) assert pytest.wait_for(transport, "connected") client.fire(write(b"GET / HTTP/1.1\r\n\r\n")) assert pytest.wait_for(client, "done") client.stop() s = client.buffer().decode('utf-8').split('\r\n')[0] assert s == "HTTP/1.1 400 Bad Request"
def test(webapp): transport = TCPClient() client = Client() client += transport client.start() host, port, resource, secure = parse_url(webapp.server.http.base) client.fire(connect(host, port)) assert pytest.wait_for(transport, "connected") client.fire(write(b"GET / HTTP/1.1\r\n")) client.fire(write(b"Content-Type: text/plain\r\n\r\n")) assert pytest.wait_for(client, "done") client.stop() s = client.buffer().decode('utf-8').split('\r\n')[0] assert s == "HTTP/1.1 200 OK"
def _on_connect(self, host=None, port=None, secure=None, certfile=None, keyfile=None, ca_certs=None): try: socket = self._socket_map[(host, port, secure)] if not socket.connected: raise KeyError except KeyError: socket = TCPClient(channel='%s_%d' % (self.channel, len(self._buffers))).register(self) self._buffers[socket] = { 'parser': ClientStateMachine(), 'socket': socket, 'requests': [], 'responses': [], } self._socket_map[(host, port, secure)] = socket self._channel_sock[socket.channel] = socket if not socket.connected: self.fire(connect(host, port, secure, certfile=certfile, keyfile=keyfile, ca_certs=ca_certs), socket) #event.stop() # FIXME: self.call does conflict with this return socket
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()
def _on_request(self, client): if client.socket is None: host = client.request.uri.host port = client.request.uri.port secure = client.request.uri.scheme == u'https' result = yield self.call(connect(host, port, secure, certfile=client.ssl.cert, keyfile=client.ssl.key, ca_certs=[client.ssl.ca])) if result.errors: reraise(*result.value) client.socket = result.value if not client.socket.connected: yield self.wait("connected", client.socket.channel) try: state = self._buffers[client.socket] except KeyError: return # server disconnected state['requests'].append(client) composer = ComposedRequest(client.request) composer.prepare() for data in composer: self.fire(write(data), client.socket) yield client
def test_tcp_lookup_failure(manager, watcher, Poller, ipv6): poller = Poller().register(manager) if ipv6: tcp_client = TCP6Client() else: tcp_client = TCPClient() client = Client() + tcp_client client.register(manager) try: assert watcher.wait("ready", "client") client.fire(connect("foo.bar.baz", 1234)) assert watcher.wait("error", "client") if pytest.PLATFORM == "win32": assert client.error.errno == 11004 else: assert client.error.errno in (EAI_NODATA, EAI_NONAME,) finally: poller.unregister() client.unregister()
def ready(self, sock): "Connect to SSH Agent" self.fire(connect(self.agent_socket))
def connect(self): """Create the connection""" self.fire(connect(self.__host, self.__port))
def error(self, *args): """Internal transport error, try to reconnect, if disconnected""" self.log("ERROR:", args) if not self.transport.connected: Timer(5, connect(self.host, self.port)).register(self)
def ready(self, component): self.fire(connect(self.host, self.port))
def connect(self, event, host=None, port=None, secure=None): if not self._transport.connected: self.fire(connect(host, port, secure), self._transport) event.stop()
def ready(self, socket): if self.config.connectiontype == 'TCP': self.log("Connecting to tcp/ip GPS network service:", self.config.host, ':', self.config.port, lvl=debug) self.fire(connect(self.config.host, self.config.port))
def ready(self, socket): for port in self.config.ports: if port.connectiontype == 'TCP': self.log("Connecting to tcp/ip serial bus service:", port.host, ':', port.port, lvl=debug) self.fire(connect(port.host, port.port), )
def _on_ready(self, component): self.fire(connect(self.host, self.port))
def error(self, etype, evalue, etraceback, handler=None): if isinstance(evalue, SocketError): if not self.transport.connected: Timer(5, connect(self.host, self.port)).register(self)
def error(self, *args): print("ERROR:", args) if not self.transport.connected: Timer(5, connect(self.host, self.port)).register(self)
def ready(self, socket): hfoslog("[NMEA] Connecting...") self.fire(connect(self.host, self.port))
def ready(self, *args): self.fire(connect(self.host, self.port))
def connect(self): """Create the connection""" self.fire(connect(self.__host, self.__port), self.channel)
def ready(self, socket): self.fire(connect(self.host, self.port))
def _websocket_connect(self, evt, value): client = evt.args[0] if client.socket in self._codecs: # FIXME: getpeername can return empty string?! self.fire(connect(client.socket, *client.socket.getpeername()), self._wschannel)