def test_source_address(self): self.client.quit() port = support.find_unused_port() self.client.connect(self.server.host, self.server.port, source_address=(HOST, port)) self.assertEqual(self.client.sock.getsockname()[1], port) self.client.quit()
def __init__(self, certfile): self.flag = None self.active = False self.port = support.find_unused_port() self.server = self.EchoServer(self.port, certfile) threading.Thread.__init__(self) self.daemon = True
def prepare_socksendfile(self): proto = MyProto(self.loop) port = support.find_unused_port() srv_sock = self.make_socket(cleanup=False) srv_sock.bind((support.HOST, port)) server = self.run_loop(self.loop.create_server( lambda: proto, sock=srv_sock)) self.reduce_receive_buffer_size(srv_sock) sock = self.make_socket() self.run_loop(self.loop.sock_connect(sock, ('127.0.0.1', port))) self.reduce_send_buffer_size(sock) def cleanup(): if proto.transport is not None: # can be None if the task was cancelled before # connection_made callback proto.transport.close() self.run_loop(proto.wait_closed()) server.close() self.run_loop(server.wait_closed()) self.addCleanup(cleanup) return sock, proto
def test_start_serving_dual_stack(self): f_proto = futures.Future() def connection_handler(transport): f_proto.set_result(MyProto(transport)) port = find_unused_port() f = self.loop.start_serving(connection_handler, host=None, port=port) socks = self.loop.run_until_complete(f) client = socket.socket() client.connect(('127.0.0.1', port)) client.send(b'xxx') proto = self.loop.run_until_complete(f_proto) proto.transport.close() client.close() f_proto = futures.Future() client = socket.socket(socket.AF_INET6) client.connect(('::1', port)) client.send(b'xxx') proto = self.loop.run_until_complete(f_proto) proto.transport.close() client.close() for s in socks: self.loop.stop_serving(s)
def __init__(self, certfile): self.flag = None self.active = False self.RootedHTTPRequestHandler.root = os.path.split(CERTFILE)[0] self.port = support.find_unused_port() self.server = self.HTTPSServer( (HOST, self.port), self.RootedHTTPRequestHandler, certfile) threading.Thread.__init__(self) self.daemon = True
def test_create_connection_local_addr(self): with test_utils.run_test_server(self.loop) as httpd: port = find_unused_port() f = self.loop.create_connection( *httpd.address, local_addr=(httpd.address[0], port)) tr = self.loop.run_until_complete(f) pr = MyProto(tr, create_future=True) expected = pr.transport.get_extra_info('socket').getsockname()[1] self.assertEqual(port, expected) tr.close()
def test_source_address_passive_connection(self): port = support.find_unused_port() self.client.source_address = (HOST, port) try: with self.client.transfercmd('list') as sock: self.assertEqual(sock.getsockname()[1], port) except IOError as e: if e.errno == errno.EADDRINUSE: self.skipTest("couldn't bind to port %d" % port) raise
def test_source_address_passive_connection(self): port = support.find_unused_port() self.client.source_address = (HOST, port) try: with self.client.transfercmd('list') as sock: self.assertEqual(sock.getsockname()[1], port) except OSError as e: if e.errno == errno.EADDRINUSE: self.skipTest("couldn't bind to port %d" % port) raise
def setUp(self): self.serv_evt = threading.Event() self.client_evt = threading.Event() self.port = support.find_unused_port() self.serv = SimSMTPServer((HOST, self.port), ('nowhere', -1)) serv_args = (self.serv, self.serv_evt, self.client_evt) threading.Thread(target=debugging_server, args=serv_args).start() # wait until server thread has assigned a port number self.serv_evt.wait() self.serv_evt.clear()
def test_source_address(self): self.client.quit() port = support.find_unused_port() try: self.client.connect(self.server.host, self.server.port, source_address=(HOST, port)) self.assertEqual(self.client.sock.getsockname()[1], port) self.client.quit() except OSError as e: if e.errno == errno.EADDRINUSE: self.skipTest("couldn't bind to port %d" % port) raise
def test_create_connection_local_addr(self): from test.support import find_unused_port loop = get_event_loop() with run_test_server(loop, EchoServerProtocol) as server: yield server.start_serving() host = server.address[0] port = find_unused_port() tr, pr = yield loop.create_connection(SimpleProtocol, *server.address, local_addr=(host, port)) expected = pr.transport.get_extra_info('socket').getsockname()[1] self.assertEqual(port, expected) tr.close()
def testSourceAddress(self): # connect src_port = support.find_unused_port() try: smtp = smtplib.SMTP(self.host, self.port, local_hostname='localhost', timeout=3, source_address=(self.host, src_port)) self.assertEqual(smtp.source_address, (self.host, src_port)) self.assertEqual(smtp.local_hostname, 'localhost') smtp.quit() except OSError as e: if e.errno == errno.EADDRINUSE: self.skipTest("couldn't bind to source port %d" % src_port) raise
def testSourceAddress(self): # connect port = support.find_unused_port() try: smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3, source_address=('127.0.0.1', port)) self.assertEqual(smtp.source_address, ('127.0.0.1', port)) self.assertEqual(smtp.local_hostname, 'localhost') smtp.quit() except OSError as e: if e.errno == errno.EADDRINUSE: self.skipTest("couldn't bind to port %d" % port) raise
def testSourceAddress(self): # connect port = support.find_unused_port() try: smtp = smtplib.SMTP( HOST, self.port, local_hostname="localhost", timeout=3, source_address=("127.0.0.1", port) ) self.assertEqual(smtp.source_address, ("127.0.0.1", port)) self.assertEqual(smtp.local_hostname, "localhost") smtp.quit() except IOError as e: if e.errno == errno.EADDRINUSE: self.skipTest("couldn't bind to port %d" % port) raise
def test_create_server_sock(self): port = find_unused_port() sock = create_server_sock((None, port)) with contextlib.closing(sock): self.assertEqual(sock.getsockname()[1], port) self.assertEqual(sock.type, socket.SOCK_STREAM) if has_dual_stack(): self.assertEqual(sock.family, socket.AF_INET6) else: self.assertEqual(sock.family, socket.AF_INET) self.echo_server(sock) cl = socket.create_connection(('localhost', port), timeout=2) with contextlib.closing(cl): cl.sendall(b'foo') self.assertEqual(cl.recv(1024), b'foo')
def test_it(self): port = find_unused_port() with socket.create_server(("", port)) as sock: self.tcp_server(sock) with socket.create_connection(("127.0.0.1", port)) as client: with open(TESTFN, 'rb') as f: client.sendfile(f) self.tearDown() size = os.path.getsize(TESTFN) self.assertEqual(os.path.getsize(TESTFN2), size) with open(TESTFN2, 'rb') as f: self.assertEqual(f.read(5), b'z\x00\x00\x00\x00') f.seek(size - 5) self.assertEqual(f.read(), b'\x00\x00\x00\x00a')
def setUp(self): # temporarily replace sys.stdout to capture DebuggingServer output self.old_stdout = sys.stdout self.output = io.StringIO() sys.stdout = self.output self.serv_evt = threading.Event() self.client_evt = threading.Event() self.port = support.find_unused_port() self.serv = smtpd.DebuggingServer((HOST, self.port), ('nowhere', -1)) serv_args = (self.serv, self.serv_evt, self.client_evt) threading.Thread(target=debugging_server, args=serv_args).start() # wait until server thread has assigned a port number self.serv_evt.wait() self.serv_evt.clear()
def prepare_sendfile(self, *, is_ssl=False, close_after=0): port = support.find_unused_port() srv_proto = MySendfileProto(loop=self.loop, close_after=close_after) if is_ssl: if not ssl: self.skipTest("No ssl module") srv_ctx = test_utils.simple_server_sslcontext() cli_ctx = test_utils.simple_client_sslcontext() else: srv_ctx = None cli_ctx = None srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv_sock.bind((support.HOST, port)) server = self.run_loop( self.loop.create_server(lambda: srv_proto, sock=srv_sock, ssl=srv_ctx)) self.reduce_receive_buffer_size(srv_sock) if is_ssl: server_hostname = support.HOST else: server_hostname = None cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) cli_sock.connect((support.HOST, port)) cli_proto = MySendfileProto(loop=self.loop) tr, pr = self.run_loop( self.loop.create_connection(lambda: cli_proto, sock=cli_sock, ssl=cli_ctx, server_hostname=server_hostname)) self.reduce_send_buffer_size(cli_sock, transport=tr) def cleanup(): srv_proto.transport.close() cli_proto.transport.close() self.run_loop(srv_proto.done) self.run_loop(cli_proto.done) server.close() self.run_loop(server.wait_closed()) self.addCleanup(cleanup) return srv_proto, cli_proto
def prepare_sendfile(self, *, is_ssl=False, close_after=0): port = support.find_unused_port() srv_proto = MySendfileProto(loop=self.loop, close_after=close_after) if is_ssl: if not ssl: self.skipTest("No ssl module") srv_ctx = test_utils.simple_server_sslcontext() cli_ctx = test_utils.simple_client_sslcontext() else: srv_ctx = None cli_ctx = None srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv_sock.bind((support.HOST, port)) server = self.run_loop(self.loop.create_server( lambda: srv_proto, sock=srv_sock, ssl=srv_ctx)) self.reduce_receive_buffer_size(srv_sock) if is_ssl: server_hostname = support.HOST else: server_hostname = None cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) cli_sock.connect((support.HOST, port)) cli_proto = MySendfileProto(loop=self.loop) tr, pr = self.run_loop(self.loop.create_connection( lambda: cli_proto, sock=cli_sock, ssl=cli_ctx, server_hostname=server_hostname)) self.reduce_send_buffer_size(cli_sock, transport=tr) def cleanup(): srv_proto.transport.close() cli_proto.transport.close() self.run_loop(srv_proto.done) self.run_loop(cli_proto.done) server.close() self.run_loop(server.wait_closed()) self.addCleanup(cleanup) return srv_proto, cli_proto
def test_start_serving_dual_stack(self): f_proto = futures.Future(loop=self.loop) class TestMyProto(MyProto): def connection_made(self, transport): super().connection_made(transport) f_proto.set_result(self) try_count = 0 while True: try: port = find_unused_port() f = self.loop.start_serving(TestMyProto, host=None, port=port) socks = self.loop.run_until_complete(f) except OSError as ex: if ex.errno == errno.EADDRINUSE: try_count += 1 self.assertGreaterEqual(5, try_count) continue else: raise else: break client = socket.socket() client.connect(('127.0.0.1', port)) client.send(b'xxx') proto = self.loop.run_until_complete(f_proto) proto.transport.close() client.close() f_proto = futures.Future(loop=self.loop) client = socket.socket(socket.AF_INET6) client.connect(('::1', port)) client.send(b'xxx') proto = self.loop.run_until_complete(f_proto) proto.transport.close() client.close() for s in socks: self.loop.stop_serving(s)
def test_mlistener(self): port = find_unused_port() # v4 sock = MultipleSocketsListener( [('127.0.0.1', port), ('::1', port)]) with contextlib.closing(sock): self.echo_server(sock) port = sock.getsockname()[1] cl = socket.create_connection(("127.0.0.1", port), timeout=2) with contextlib.closing(cl): cl.sendall(b'foo') self.assertEqual(cl.recv(1024), b'foo') # v6 sock = MultipleSocketsListener( [('127.0.0.1', port), ('::1', port)]) with contextlib.closing(sock): self.echo_server(sock) port = sock.getsockname()[1] cl = socket.create_connection(("::1", port), timeout=2) with contextlib.closing(cl): cl.sendall(b'foo') self.assertEqual(cl.recv(1024), b'foo')
def test_mlistener(self): port = find_unused_port() # v4 sock = MultipleSocketsListener([('127.0.0.1', port), ('::1', port)]) with contextlib.closing(sock): self.echo_server(sock) port = sock.getsockname()[1] cl = socket.create_connection(("127.0.0.1", port), timeout=2) with contextlib.closing(cl): cl.sendall(b'foo') self.assertEqual(cl.recv(1024), b'foo') # v6 sock = MultipleSocketsListener([('127.0.0.1', port), ('::1', port)]) with contextlib.closing(sock): self.echo_server(sock) port = sock.getsockname()[1] cl = socket.create_connection(("::1", port), timeout=2) with contextlib.closing(cl): cl.sendall(b'foo') self.assertEqual(cl.recv(1024), b'foo')
def prepare(self): sock = self.make_socket() proto = self.MyProto(self.loop) port = support.find_unused_port() srv_sock = self.make_socket(cleanup=False) srv_sock.bind(('127.0.0.1', port)) server = self.run_loop( self.loop.create_server(lambda: proto, sock=srv_sock)) self.run_loop(self.loop.sock_connect(sock, srv_sock.getsockname())) def cleanup(): if proto.transport is not None: # can be None if the task was cancelled before # connection_made callback proto.transport.close() self.run_loop(proto.wait_closed()) server.close() self.run_loop(server.wait_closed()) self.addCleanup(cleanup) return sock, proto
def prepare(self): sock = self.make_socket() proto = self.MyProto(self.loop) port = support.find_unused_port() srv_sock = self.make_socket(cleanup=False) srv_sock.bind(('127.0.0.1', port)) server = self.run_loop(self.loop.create_server( lambda: proto, sock=srv_sock)) self.run_loop(self.loop.sock_connect(sock, srv_sock.getsockname())) def cleanup(): if proto.transport is not None: # can be None if the task was cancelled before # connection_made callback proto.transport.close() self.run_loop(proto.wait_closed()) server.close() self.run_loop(server.wait_closed()) self.addCleanup(cleanup) return sock, proto
def testRudeShutdown(self): listener_ready = threading.Event() listener_gone = threading.Event() port = support.find_unused_port() # `listener` runs in a thread. It opens a socket listening on # PORT, and sits in an accept() until the main thread connects. # Then it rudely closes the socket, and sets Event `listener_gone` # to let the main thread know the socket is gone. def listener(): s = socket.socket() s.bind((HOST, port)) s.listen(5) listener_ready.set() s.accept() s = None # reclaim the socket object, which also closes it listener_gone.set() def connector(): listener_ready.wait() s = socket.socket() s.connect((HOST, port)) listener_gone.wait() try: ssl_sock = ssl.wrap_socket(s) except IOError: pass else: raise support.TestFailed( 'connecting to closed SSL socket should have failed') t = threading.Thread(target=listener) t.start() connector() t.join()
def test_find_unused_port(self): port = support.find_unused_port() s = socket.socket() s.bind((support.HOST, port)) s.close()
def main(config_path_str: str=None, verbosity: int=20) -> None: """Runs the main fauxmo process. Spawns a UDP server to handle the Echo's UPnP / SSDP device discovery process as well as multiple TCP servers to respond to the Echo's device setup requests and handle its process for turning devices on and off. Args: config_path_str: Path to config file. If not given will search for `config.json` in cwd, `~/.fauxmo/`, and `/etc/fauxmo/`. verbosity: Logging verbosity, defaults to 20 """ logger.setLevel(verbosity) logger.info(f"Fauxmo version {__version__}") logger.debug(sys.version) if config_path_str: config_path = pathlib.Path(config_path_str) else: for config_dir in ('.', "~/.fauxmo", "/etc/fauxmo"): config_path = pathlib.Path(config_dir) / 'config.json' if config_path.is_file(): logger.info(f"Using config: {config_path}") break try: config = json.loads(config_path.read_text()) except FileNotFoundError: logger.error("Could not find config file in default search path. Try " "specifying your file with `-c`.\n") raise # Every config should include a FAUXMO section fauxmo_config = config.get("FAUXMO") fauxmo_ip = get_local_ip(fauxmo_config.get("ip_address")) ssdp_server = SSDPServer() servers = [] loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) if verbosity < 20: loop.set_debug(True) logging.getLogger('asyncio').setLevel(logging.DEBUG) try: plugins = config['PLUGINS'] except KeyError: # Give a meaningful message without a nasty traceback if it looks like # user is running a pre-v0.4.0 config. errmsg = ("`PLUGINS` key not found in your config.\n" "You may be trying to use an outdated config.\n" "If so, please review <https://github.com/n8henrie/fauxmo> " "and update your config for Fauxmo >= v0.4.0.") print(errmsg) sys.exit(1) for plugin in plugins: modname = f"{__package__}.plugins.{plugin.lower()}" try: module = importlib.import_module(modname) # Will fail until https://github.com/python/typeshed/pull/1083 merged # and included in the next mypy release except ModuleNotFoundError: # type: ignore path_str = config['PLUGINS'][plugin]['path'] module = module_from_file(modname, path_str) Plugin = getattr(module, plugin) if not issubclass(Plugin, FauxmoPlugin): raise TypeError(f"Plugins must inherit from {repr(FauxmoPlugin)}") # Pass along variables defined at the plugin level that don't change # per device plugin_vars = {k: v for k, v in config['PLUGINS'][plugin].items() if k not in {"DEVICES", "path"}} logger.debug(f"plugin_vars: {repr(plugin_vars)}") for device in config['PLUGINS'][plugin]['DEVICES']: logger.debug(f"device config: {repr(device)}") # Ensure port is `int`, set it if not given (`None`) or 0 device["port"] = int(device.get('port', 0)) or find_unused_port() try: plugin = Plugin(**plugin_vars, **device) except TypeError: logger.error(f"Error in plugin {repr(Plugin)}") raise fauxmo = partial(Fauxmo, name=plugin.name, plugin=plugin) coro = loop.create_server(fauxmo, host=fauxmo_ip, port=plugin.port) server = loop.run_until_complete(coro) servers.append(server) ssdp_server.add_device(plugin.name, fauxmo_ip, plugin.port) logger.debug(f"Started fauxmo device: {repr(fauxmo.keywords)}") logger.info("Starting UDP server") # mypy will fail until https://github.com/python/typeshed/pull/1084 merged, # pulled into mypy, and new mypy released listen = loop.create_datagram_endpoint(lambda: ssdp_server, # type: ignore sock=make_udp_sock()) transport, protocol = loop.run_until_complete(listen) # type: ignore for signame in ('SIGINT', 'SIGTERM'): try: loop.add_signal_handler(getattr(signal, signame), loop.stop) # Workaround for Windows (https://github.com/n8henrie/fauxmo/issues/21) except NotImplementedError: if sys.platform == 'win32': pass else: raise loop.run_forever() # Will not reach this part unless SIGINT or SIGTERM triggers `loop.stop()` logger.debug("Shutdown starting...") transport.close() for idx, server in enumerate(servers): logger.debug(f"Shutting down server {idx}...") server.close() loop.run_until_complete(server.wait_closed()) loop.close()
def testWithoutServer(self): port = support.find_unused_port() self.failUnlessRaises( socket.error, lambda: socket.create_connection((HOST, port)) )
def test_find_unused_port(self): port = support.find_unused_port() s = socket.create_server((support.HOST, port)) s.close()
def testWithoutServer(self): port = support.find_unused_port() self.assertRaises( socket.error, lambda: socket.create_connection((HOST, port)) )
def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.port = support.bind_port(self.serv) self.source_port = support.find_unused_port() self.serv.listen(5) self.conn = None
def test_source_address_passive_connection(self): port = support.find_unused_port() self.client.source_address = (HOST, port) with self.client.transfercmd('list') as sock: self.assertEqual(sock.getsockname()[1], port)