Skip to content

Commit

Permalink
Prevent HostsFileProvider from barfing on non-UTF8 characters
Browse files Browse the repository at this point in the history
This should fix #153.
  • Loading branch information
dlenski committed Sep 5, 2024
1 parent 4e26adb commit 9078626
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 11 deletions.
2 changes: 1 addition & 1 deletion vpn_slice/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def do_disconnect(env, args):
print(f"Killed pid {pid} from {pidfile}", file=stderr)

if 'hosts' in providers:
removed = providers.hosts.write_hosts({}, args.name)
removed = providers.hosts.write_hosts((), args.name)
if args.verbose:
print(f"Removed {removed} hosts from /etc/hosts", file=stderr)

Expand Down
7 changes: 3 additions & 4 deletions vpn_slice/posix.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,13 @@ def __init__(self, path):

def write_hosts(self, host_map, name):
tag = f'vpn-slice-{name} AUTOCREATED'
with open(self.path, 'r+') as hostf:
with open(self.path, 'r+b') as hostf:
fcntl.flock(hostf, fcntl.LOCK_EX) # POSIX only, obviously
lines = hostf.readlines()
keeplines = [l for l in lines if not l.endswith(f'# {tag}\n')]
keeplines = [l for l in lines if not l.endswith(f'# {tag}\n'.encode())]
hostf.seek(0, 0)
hostf.writelines(keeplines)
for ip, names in host_map:
print(f"{ip} {' '.join(names)}\t\t# {tag}", file=hostf)
hostf.writelines(f"{ip} {' '.join(names)}\t\t# {tag}\n".encode() for ip, names in host_map)
hostf.truncate()
return len(host_map) or len(lines) - len(keeplines)

Expand Down
13 changes: 7 additions & 6 deletions vpn_slice/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,15 @@ def lookup_srv(self, query):

class HostsProvider(metaclass=ABCMeta):
@abstractmethod
def write_hosts(self, host_map, name):
"""Write information to the hosts file.
def write_hosts(self, host_map: "List[Tuple[Union[ip_address, str], List[str]]]", name):
"""Update local overrides for hostname-to-IP address mapping.
Lines include a tag so we can identify which lines to remove.
The tag is derived from the name.
host_map maps IP addresses to host names, like the hosts file expects.
Each local override added by this instance of vpn-slice should include a tag
a tag derived from the 'name' parameter, so that we can later identify those
owned by this instance in order to remove/replace them, while leaving others
untouched.
'host_map' should be a list of (IP address, lists of hostnames) tuples.
"""

class TunnelPrepProvider:
Expand Down

0 comments on commit 9078626

Please sign in to comment.