(hostmap, port)
| 23 | |
| 24 | |
| 25 | def rewrite_etc_hosts(hostmap, port): |
| 26 | BAKFILE = '%s.sbak' % HOSTSFILE |
| 27 | APPEND = '# sshuttle-firewall-%d AUTOCREATED' % port |
| 28 | old_content = '' |
| 29 | st = None |
| 30 | try: |
| 31 | old_content = open(HOSTSFILE).read() |
| 32 | st = os.stat(HOSTSFILE) |
| 33 | except IOError as e: |
| 34 | if e.errno == errno.ENOENT: |
| 35 | pass |
| 36 | else: |
| 37 | raise |
| 38 | if old_content.strip() and not os.path.exists(BAKFILE): |
| 39 | try: |
| 40 | os.link(HOSTSFILE, BAKFILE) |
| 41 | except OSError: |
| 42 | # file is locked - performing non-atomic copy |
| 43 | shutil.copyfile(HOSTSFILE, BAKFILE) |
| 44 | tmpname = "%s.%d.tmp" % (HOSTSFILE, port) |
| 45 | f = open(tmpname, 'w') |
| 46 | for line in old_content.rstrip().split('\n'): |
| 47 | if line.find(APPEND) >= 0: |
| 48 | continue |
| 49 | f.write('%s\n' % line) |
| 50 | for (name, ip) in sorted(hostmap.items()): |
| 51 | f.write('%-30s %s\n' % ('%s %s' % (ip, name), APPEND)) |
| 52 | f.close() |
| 53 | |
| 54 | if sys.platform != 'win32': |
| 55 | if st is not None: |
| 56 | os.chown(tmpname, st.st_uid, st.st_gid) |
| 57 | os.chmod(tmpname, st.st_mode) |
| 58 | else: |
| 59 | os.chown(tmpname, 0, 0) |
| 60 | os.chmod(tmpname, 0o644) |
| 61 | try: |
| 62 | os.rename(tmpname, HOSTSFILE) |
| 63 | except OSError: |
| 64 | # file is locked - performing non-atomic copy |
| 65 | log('Warning: Using a non-atomic way to overwrite %s that can corrupt the file if ' |
| 66 | 'multiple processes write to it simultaneously.' % HOSTSFILE) |
| 67 | shutil.move(tmpname, HOSTSFILE) |
| 68 | |
| 69 | |
| 70 | def restore_etc_hosts(hostmap, port): |
no test coverage detected