2016-06-04 20:06:27 +00:00
|
|
|
# No unicode_literals
|
2018-04-21 07:30:08 +00:00
|
|
|
import json
|
|
|
|
import os
|
|
|
|
import unicodedata
|
2016-05-29 01:04:08 +00:00
|
|
|
from binascii import hexlify, unhexlify
|
2018-12-22 22:27:54 +00:00
|
|
|
from hkdf import Hkdf
|
2016-05-29 01:04:08 +00:00
|
|
|
|
2018-04-21 07:30:08 +00:00
|
|
|
|
2018-12-22 22:27:54 +00:00
|
|
|
def HKDF(skm, outlen, salt=None, CTXinfo=b""):
|
|
|
|
return Hkdf(salt, skm).expand(CTXinfo, outlen)
|
|
|
|
|
2016-05-29 01:04:08 +00:00
|
|
|
def to_bytes(u):
|
|
|
|
return unicodedata.normalize("NFC", u).encode("utf-8")
|
2018-04-21 07:30:08 +00:00
|
|
|
|
2018-12-24 05:07:06 +00:00
|
|
|
def to_unicode(any):
|
|
|
|
if isinstance(any, type(u"")):
|
|
|
|
return any
|
|
|
|
return any.decode("ascii")
|
2018-04-21 07:30:08 +00:00
|
|
|
|
2016-05-29 01:04:08 +00:00
|
|
|
def bytes_to_hexstr(b):
|
|
|
|
assert isinstance(b, type(b""))
|
|
|
|
hexstr = hexlify(b).decode("ascii")
|
|
|
|
assert isinstance(hexstr, type(u""))
|
|
|
|
return hexstr
|
2018-04-21 07:30:08 +00:00
|
|
|
|
|
|
|
|
2016-05-29 01:04:08 +00:00
|
|
|
def hexstr_to_bytes(hexstr):
|
|
|
|
assert isinstance(hexstr, type(u""))
|
|
|
|
b = unhexlify(hexstr.encode("ascii"))
|
|
|
|
assert isinstance(b, type(b""))
|
|
|
|
return b
|
2018-04-21 07:30:08 +00:00
|
|
|
|
|
|
|
|
2016-05-29 01:04:08 +00:00
|
|
|
def dict_to_bytes(d):
|
|
|
|
assert isinstance(d, dict)
|
|
|
|
b = json.dumps(d).encode("utf-8")
|
|
|
|
assert isinstance(b, type(b""))
|
|
|
|
return b
|
2018-04-21 07:30:08 +00:00
|
|
|
|
|
|
|
|
2016-05-29 01:04:08 +00:00
|
|
|
def bytes_to_dict(b):
|
|
|
|
assert isinstance(b, type(b""))
|
|
|
|
d = json.loads(b.decode("utf-8"))
|
|
|
|
assert isinstance(d, dict)
|
|
|
|
return d
|
2016-12-10 23:30:25 +00:00
|
|
|
|
2018-04-21 07:30:08 +00:00
|
|
|
|
2016-12-10 23:30:25 +00:00
|
|
|
def estimate_free_space(target):
|
|
|
|
# f_bfree is the blocks available to a root user. It might be more
|
|
|
|
# accurate to use f_bavail (blocks available to non-root user), but we
|
|
|
|
# don't know which user is running us, and a lot of installations don't
|
|
|
|
# bother with reserving extra space for root, so let's just stick to the
|
|
|
|
# basic (larger) estimate.
|
|
|
|
try:
|
|
|
|
s = os.statvfs(os.path.dirname(os.path.abspath(target)))
|
|
|
|
return s.f_frsize * s.f_bfree
|
|
|
|
except AttributeError:
|
|
|
|
return None
|