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 c527986
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 9 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
14 changes: 10 additions & 4 deletions vpn_slice/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,19 @@ def lookup_srv(self, query):
class HostsProvider(metaclass=ABCMeta):
@abstractmethod
def write_hosts(self, host_map, name):
"""Write information to the hosts file.
"""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.
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 maps IP addresses to host names, like the hosts file expects.
'host_map' should be a list of (IP address, lists of hostnames) tuples, e.g.
from typing import List, Tuple, Union
from ipaddress import ip_address
def write_hosts(self, host_map: List[Tuple[Union[ip_address, str], List[str]]], name: str):
...
"""

class TunnelPrepProvider:
Expand Down

0 comments on commit c527986

Please sign in to comment.