Files
OpenVPNAdapter/win/utils.py
Sergey Abramchuk 84ad2a289f Squashed 'OpenVPN Adapter/Vendors/openvpn/' changes from 098fd412a..e6d68831a
e6d68831a deps: update mbedTLS to 2.7.0
59de63fa6 cli.cpp: added OPENVPN_REMOTE_OVERRIDE
caf9cf6c1 RedirectPipe: added additional flags for flexibility
68595de4d ClientAPI::RemoteOverride: added error status
37d848ca2 Log lines from C++ exceptions should contain the text "exception"
f05802cf9 Increase server validation of password size to 16KB to support bundling SAML messages.
52e4d4a5f Increase client validation of password/response size to 16KB to support bundling SAML messages.
a0416ed92 [OVPN3-209] win: add dependencies checksum verification
f6eadbc4d [OVPN3-206] Refactor Windows build system
7b30c2f12 [OVPN3-220] proto.hpp: send initial options set on rekeying
33dd2f29e mbedtls: backport fixes for CVE-2018-0487
0912a9b62 [OVPN3-213] build system: mbedtls timing tests
98fa55576 deps: update asio to 1.12.0
620531101 [OVPN3-215] asio: apply external patches
f4a73bde5 [OVPN3-215] asio: rebase external patches on top of our current commit ID
a61cac928 mbedtls: Patches from 2.7 to fix timing test failures
c892f41fb win: tune dependencies build
8a394a37d [OVPN3-213] build system: mbedtls timing tests
0a3dd67da [OVPN3-190] tun linux: add to/from_json methods
44c6cdfdc [OVPN3-206] readme: update Windows build instructions
0edec4a09 [OVPN3-206] win: update directories in VS projects
3d6fd62cb mac build: improve unittest stability
758ae98c6 [OVPN3-209] win: add dependencies checksum verification
a7642ee82 [OVPN3-205] win: apply mbedTLS patches
ac94b6eb7 [OVPN3-206] Refactor Windows build system
c5bc3859e mbedTLS: don't set endpoint twice in conf object
3d5dd9ee3 [OVPN3-199] mac build: do not overwrite DEP_DIR
b713762ba mbedtls: Patches from 2.7 to fix timing test failures
37ab79fa6 tun linux: apply changes from 362acf0
6a7aee2c9 [OVPN3-190] tun: implement persistence
1d2ebb07f [OVPN3-190] tun: move tun creation to separate class
53e33d634 [OVPN3-190] tun: move content of tun to tuncli
85d3377c2 [OVPN3-190] tun: move tun setup methods to separate file
735b985eb i/o layer:  wrap raw pointers embedded in closures
322ae24b5 OptionList: support variadic template parameter pack in constructors
8a012b454 lz4: added namespace and improved error handling
34998e94a zlib: removed verbose parameter
846ed217d OpenSSL: set SSL_MODE_RELEASE_BUFFERS to conserve memory by releasing unneeded buffers
32e3ea117 OptionList: added show_unused_options() method
fe38233a8 Buffer: added typedefs for thread-safe refcounts
b34b6271e compression: added compress_lz4() and decompress_lz4()
755e1a181 linux/core.hpp: added exclude_from_core() function
a7f6fe64f ManClientInstance::Send: added userprop_local_update() virtual method
94526ac19 BufferAllocated: fixed regression in buffer copy
33c16812e [OVPN3-144] mbedTLS: fix support for 4096bit encrypted keys
f249ab4bd [OVPN3-144] build-mbedtls: run make check before compiling
5040aef4c [OVPN3-144] build-mbedtls: apply patches using git-apply instead of patch
8a5e838ab [OVPN3-144] mbedTLS: fix incompatibility with PKI created by OpenSSL 1.1
e7badefd7 proto.hpp/tls-crypt: fix access to ACK IDs during packet validation
73fa974db proto.hpp: print buffer exception in case of packet access error
79ad5eded Estblishing a stable branch
1c5f20ab0 Hide the @ sign in logs if username is empty
01ee1f5a4 Added ClientAPI::Config::retryOnAuthFailed parameter
05880b136 Added ProfileParseLimits::MAX_SERVER_LIST_SIZE and raise limit to 4096
eedee4fa6 cli.cpp: allow -s server override to reference a friendly name
6e350e9f9 Linux tun setup: use LinuxGW46 to obtain gateway info
3e044c6c7 top-level .gitignore was missing a trailing newline
a27355ac7 Use C++11 push_back(std::move(...))) for pushing objects onto vectors
8c3af2704 HostPort::split_host_port: support unix socket filename as an alternative kind of host
14b588c86 asio: added asio_resolver_results_to_string()
fd6e8e9bf AsioPolySock: minor changes to remote_endpoint_str()
06f5e4d71 AsioBoundSocket::Socket: added to_string() method
8fd968532 RemoteList: minor cleanup in set_endpoint_range()
f9fc2f54e BufferAllocated: improve movability
8cb8d52cd string: added first_line() method
a26b1646b AsioPolySock: extend AltRouting support
ef3a40c27 Listen::Item: added AltRouting mode
02e786bc9 write_binary_atomic: support ConstBuffer
6745799c9 fileunix: added read_binary_unix_fast()
5689c2d9c write_binary_unix(): added ConstBuffer variant
2b0e76453 enum_dir: refactor to allow enumeration via lambda
116a5bd5e bufstr: added const_buf_from_string() method
f8ec81413 Buffer: added const_buffer_ref() variant accepting a const argument
ae98aa8b6 AsioPolySock: support AltRouting
8f81479f1 AsioBoundSocket::Socket: support inheritance
9598918e9 ServerProto: added schedule_disconnect() method.
4516cf67b ServerProto: reset CoarseTime object when AsioTimer is canceled
0ffc76a0b Route: implement operator< so Route objects can be used as map/set keys.
c4af9f68b event_loop_wait_barrier: raise default timeout to 30 seconds
d7fe87540 appversion.hpp: rename VERSION -> BUILD_VERSION

git-subtree-dir: OpenVPN Adapter/Vendors/openvpn
git-subtree-split: e6d68831a71131b7d92fbea93d3b9cbe10ba2068
2018-04-04 12:34:20 +03:00

314 lines
8.7 KiB
Python

import os, sys, re, stat, shutil, tarfile, zipfile, subprocess
import requests
import rfc6266
import hashlib
j = os.path.join
class Cd(object):
"""
Cd is a context manager that allows
you to temporary change the working directory.
with Cd(dir) as cd:
...
"""
def __init__(self, directory):
self._dir = directory
def orig(self):
return self._orig
def __enter__(self):
self._orig = os.getcwd()
os.chdir(self._dir)
return self
def __exit__(self, *args):
os.chdir(self._orig)
class ModEnv(object):
"""
Context manager for temporarily
modifying an env var. Normally used to make
changes to PATH.
"""
def __init__(self, key, value):
self.key = key;
self.value = value;
def __enter__(self):
self.orig_value = os.environ.get(self.key)
os.environ[self.key] = self.value
return self
def __exit__(self, *args):
if self.orig_value is not None:
os.environ[self.key] = self.orig_value
def rmtree(dir):
print "RMTREE", dir
shutil.rmtree(dir, ignore_errors=True)
def rm(fn, silent=False):
if os.path.exists(fn):
if not silent:
print "RM", fn
os.remove(fn)
def makedirs(dir):
print "MAKEDIRS", dir
os.makedirs(dir)
def cp(src, dest):
print "COPY %s %s" % (src, dest)
shutil.copy2(src, dest)
def wipetree(dir, wipe=True):
def onerror(func, path, exc_info):
"""
Error handler for ``shutil.rmtree``.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it ignores.
Usage : ``shutil.rmtree(path, onerror=onerror)``
"""
if not os.access(path, os.W_OK):
# Is the error an access error ?
try:
os.chmod(path, stat.S_IWUSR)
func(path)
except:
pass
if wipe:
print "WIPETREE", dir
shutil.rmtree(dir, ignore_errors=False, onerror=onerror)
if not os.path.isdir(dir):
makedirs(dir)
def extract_dict(d, k, default=None):
if k in d:
v = d[k]
del d[k]
else:
v = default
return v
def scan_prefixes(prefix, dir, filt=None):
fns = []
for dirpath, dirnames, filenames in os.walk(dir):
for f in filenames:
if f.startswith(prefix) and (filt is None or filt(f)):
fns.append(f)
break
return fns
def one_prefix(prefix, dir, filt=None):
f = scan_prefixes(prefix, dir, filt)
if len(f) == 0:
raise ValueError("prefix %r not found in dir %r" % (prefix, dir))
elif len(f) >= 2:
raise ValueError("prefix %r is ambiguous in dir %r: %r" % (prefix, dir, f))
return f[0]
def tarsplit(fn):
if fn.endswith(".tar.gz"):
t = 'gz'
b = fn[:-7]
elif fn.endswith(".tgz"):
t = 'gz'
b = fn[:-4]
elif fn.endswith(".tar.bz2"):
t = 'bz2'
b = fn[:-8]
elif fn.endswith(".tbz"):
t = 'bz2'
b = fn[:-4]
elif fn.endswith(".tar.xz"):
t = 'xz'
b = fn[:-7]
else:
raise ValueError("unrecognized tar file type: %r" % (fn,))
return b, t
def zipsplit(fn):
if fn.endswith(".zip"):
t = "zip"
b = fn[:-4]
else:
raise ValueError("unrecognized zip file type: %r" % (fn,))
return b, t
def archsplit(fn):
try:
b, t = tarsplit(fn)
except:
b, t = zipsplit(fn)
return b, t
def archsplit_filt(fn):
try:
tarsplit(fn)
except:
try:
zipsplit(fn)
except:
return False
else:
return True
else:
return True
def extract(fn, t):
print "%s EXTRACT %s [%s]" % ("ZIP" if t == "zip" else "TAR", fn, t)
if t == "zip":
with zipfile.ZipFile(fn) as z:
z.extractall()
else:
tar = tarfile.open(fn, mode='r:'+t)
try:
tar.extractall()
finally:
tar.close()
def expand(pkg_prefix, srcdir, lib_versions=None, noop=False):
if lib_versions and pkg_prefix in lib_versions:
f = one_prefix(lib_versions[pkg_prefix], srcdir, archsplit_filt)
else:
f = one_prefix(pkg_prefix, srcdir, archsplit_filt)
b, t = archsplit(f)
if not noop:
# remove previous directory
rmtree(os.path.realpath(b))
# expand it
extract(os.path.join(srcdir, f), t)
return b
def call(cmd, **kw):
print "***", cmd
ignore_errors = extract_dict(kw, 'ignore_errors', False)
extra_env = extract_dict(kw, 'extra_env', None)
if extra_env:
env = kw.get('env', os.environ).copy()
env.update(extra_env)
kw['env'] = env
succeed = extract_dict(kw, 'succeed', 0)
# show environment
se = kw.get('env')
if se:
show_env(se)
print "***"
ret = subprocess.call(cmd, **kw)
if not ignore_errors and ret != succeed:
raise ValueError("command failed with status %r (expected %r)" % (ret, succeed))
def vc_cmd(parms, cmd, arch=None, succeed=0):
# arch should be one of amd64 (alias x64), x86, x86_xp, or None
# (if None, use parms.py value)
if arch is None:
arch = parms['ARCH']
if arch == "x64":
arch = "amd64"
with ModEnv('PATH', "%s;%s\\VC" % (os.environ['PATH'], parms['MSVC_DIR'])):
status = call('vcvarsall.bat %s && %s' % (arch, cmd), shell=True, succeed=succeed)
def vc_parms(parms, cmd_dict):
cmd_dict["dbg_rel_flags"] = "/Zi" if parms['DEBUG'] else "/O2"
flags = "/MT" if parms['STATIC'] else "/MD"
if parms['DEBUG']:
flags += "d"
cmd_dict["link_static_dynamic_flags"] = flags
def patchfile(pkg_prefix, patchdir):
return os.path.join(patchdir, one_prefix(pkg_prefix, patchdir))
def patch(pkg_prefix, patchdir):
patch_fn = patchfile(pkg_prefix, patchdir)
print "PATCH", patch_fn
call(['patch', '-p1', '-i', patch_fn])
def build_dir(parms):
return os.path.join(parms['BUILD'], parms['ARCH'])
# remove .obj files
def rm_obj(dir):
fns = []
for dirpath, dirnames, filenames in os.walk(dir):
for f in filenames:
path = os.path.join(dirpath, f)
if f.endswith(".obj"):
rm(path)
# zip a directory
# sample usage:
# zipf = zipfile.ZipFile('Python.zip', 'w')
# zipdir('tmp/', zipf)
# zipf.close()
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file))
def download(url):
print "Downloading %s" % url
response = requests.get(url)
fname = rfc6266.parse_headers(response.headers['content-disposition']).filename_unsafe
with open(fname, "wb") as f:
f.write(response.content)
return fname
def sha256_checksum(filename, block_size=65536):
sha256 = hashlib.sha256()
with open(filename, 'rb') as f:
for block in iter(lambda: f.read(block_size), b''):
sha256.update(block)
return sha256.hexdigest()
def read_params():
if not os.environ.get('O3'):
sys.exit("Missing required O3 env variable")
params={}
params['OVPN3'] = os.environ.get('O3').rstrip()
if not os.environ.get('DEP_DIR'):
params["BUILD"] = os.path.join(params['OVPN3'], "deps")
else:
params['BUILD'] = os.environ.get('DEP_DIR').rstrip()
params['ARCH'] = os.environ.get('ARCH', 'amd64').rstrip()
params['DEBUG'] = os.environ.get('DEBUG')
params['STATIC'] = os.environ.get('STATIC')
params['MSVC_DIR'] = os.environ.get('MSVC_DIR', 'c:\\Program Files (x86)\\Microsoft Visual Studio 14.0').rstrip()
# Community: tap0901, Access Server: tapoas
params['TAP_WIN_COMPONENT_ID'] = os.environ.get('TAP_WIN_COMPONENT_ID', 'tap0901')
params['CPP_EXTRA'] = os.environ.get('CPP_EXTRA', '').rstrip()
if os.environ.get('USE_JSONSPP'):
params['USE_JSONCPP'] = True
if os.environ.get('USE_JSONSPP'):
params['CONNECT'] = True
params['GTEST_ROOT'] = os.environ.get('GTEST_ROOT')
# read versions
with open(os.path.join(params['OVPN3'], "core", "deps", "lib-versions")) as f:
for l in [line.strip() for line in f if line.strip()]:
name, val = l.split("=")
if name.startswith("export"):
name = name[6:].strip()
params[name] = val
return params