diff --git a/copyparty/tcpsrv.py b/copyparty/tcpsrv.py index c44f96c4..6c61fe61 100644 --- a/copyparty/tcpsrv.py +++ b/copyparty/tcpsrv.py @@ -25,8 +25,8 @@ from .util import ( termsize, ) -if True: - from typing import Generator, Union +if True: # pylint: disable=using-constant-test + from typing import Generator, Optional, Union if TYPE_CHECKING: from .svchub import SvcHub @@ -245,7 +245,7 @@ class TcpSrv(object): def _listen(self, ip: str, port: int) -> None: uds_perm = uds_gid = -1 - bound = False + bound: Optional[socket.socket] = None tcp = False if "unix:" in ip: @@ -274,10 +274,7 @@ class TcpSrv(object): tcp = True ipv = socket.AF_INET - if not bound: - srv = socket.socket(ipv, socket.SOCK_STREAM) - else: - srv = bound + srv = bound or socket.socket(ipv, socket.SOCK_STREAM) if not ANYWIN or self.args.reuseaddr: srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) @@ -295,31 +292,34 @@ class TcpSrv(object): if getattr(self.args, "freebind", False): srv.setsockopt(socket.SOL_IP, socket.IP_FREEBIND, 1) - try: - if not bound: - if tcp: - srv.bind((ip, port)) - else: - if ANYWIN or self.args.rm_sck: - if os.path.exists(ip): - os.unlink(ip) - srv.bind(ip) - else: - tf = "%s.%d" % (ip, os.getpid()) - if os.path.exists(tf): - os.unlink(tf) - srv.bind(tf) - if uds_gid != -1: - os.chown(tf, -1, uds_gid) - if uds_perm != -1: - os.chmod(tf, uds_perm) - atomic_move(self.nlog, tf, ip, VF_CAREFUL) + if bound: + self.srv.append(srv) + return - sport = srv.getsockname()[1] if tcp else port - if port != sport: - # linux 6.0.16 lets you bind a port which is in use - # except it just gives you a random port instead - raise OSError(E_ADDR_IN_USE[0], "") + try: + if tcp: + srv.bind((ip, port)) + else: + if ANYWIN or self.args.rm_sck: + if os.path.exists(ip): + os.unlink(ip) + srv.bind(ip) + else: + tf = "%s.%d" % (ip, os.getpid()) + if os.path.exists(tf): + os.unlink(tf) + srv.bind(tf) + if uds_gid != -1: + os.chown(tf, -1, uds_gid) + if uds_perm != -1: + os.chmod(tf, uds_perm) + atomic_move(self.nlog, tf, ip, VF_CAREFUL) + + sport = srv.getsockname()[1] if tcp else port + if port != sport: + # linux 6.0.16 lets you bind a port which is in use + # except it just gives you a random port instead + raise OSError(E_ADDR_IN_USE[0], "") self.srv.append(srv) except (OSError, socket.error) as ex: try: