Skip to content

Commit 9078626

Browse files
committed
Prevent HostsFileProvider from barfing on non-UTF8 characters
This should fix #153.
1 parent 4e26adb commit 9078626

File tree

3 files changed

+11
-11
lines changed

3 files changed

+11
-11
lines changed

vpn_slice/__main__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ def do_disconnect(env, args):
130130
print(f"Killed pid {pid} from {pidfile}", file=stderr)
131131

132132
if 'hosts' in providers:
133-
removed = providers.hosts.write_hosts({}, args.name)
133+
removed = providers.hosts.write_hosts((), args.name)
134134
if args.verbose:
135135
print(f"Removed {removed} hosts from /etc/hosts", file=stderr)
136136

vpn_slice/posix.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -99,14 +99,13 @@ def __init__(self, path):
9999

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

vpn_slice/provider.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -128,14 +128,15 @@ def lookup_srv(self, query):
128128

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

141142
class TunnelPrepProvider:

0 commit comments

Comments
 (0)