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 4128bc5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
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, name 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: "Dict[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 map from IP addresses to lists of hostnames.
"""

class TunnelPrepProvider:
Expand Down

0 comments on commit 4128bc5

Please sign in to comment.