edouard@2492: from __future__ import absolute_import
andrej@2542: from __future__ import print_function
Edouard@2321: import os
Edouard@2328: from binascii import b2a_hqx
Edouard@2339: try:
Edouard@2339:     from runtime.spawn_subprocess import call
Edouard@2339: except ImportError:
Edouard@2339:     from subprocess import call
Edouard@2321: 
edouard@2492: restart_stunnel_cmdline = ["/etc/init.d/S50stunnel", "restart"]
Edouard@2321: 
Edouard@2324: _PSKpath = None
Edouard@2324: 
edouard@2492: 
andrej@2542: def restartStunnel():
andrej@2542:     """
andrej@2542:     Restart stunnel service using SysV init stript
andrej@2542:     to apply new generated credentials
andrej@2542:     """
andrej@2542:     try:
andrej@2542:         call(restart_stunnel_cmdline)
andrej@2542:     except OSError:
andrej@2542:         print(_("Couldn't restart stunnel service"))
andrej@2542: 
andrej@2542: 
Edouard@2324: def PSKgen(ID, PSKpath):
Edouard@2323: 
Edouard@2328:     # b2a_hqx output len is 4/3 input len
edouard@2492:     secret = os.urandom(192)  # int(256/1.3333)
Edouard@2328:     secretstring = b2a_hqx(secret)
Edouard@2323: 
Edouard@2324:     PSKstring = ID+":"+secretstring
Edouard@2324:     with open(PSKpath, 'w') as f:
Edouard@2324:         f.write(PSKstring)
andrej@2542:     restartStunnel()
Edouard@2321: 
edouard@2492: 
Edouard@2324: def ensurePSK(ID, PSKpath):
Edouard@2324:     global _PSKpath
Edouard@2324:     _PSKpath = PSKpath
Edouard@2321:     # check if already there
Edouard@2324:     if not os.path.exists(PSKpath):
Edouard@2321:         # create if needed
Edouard@2324:         PSKgen(ID, PSKpath)
Edouard@2321: 
edouard@2492: 
edouard@2492: def getPSKID(errorlog):
edouard@2492:     if _PSKpath is not None:
Edouard@2324:         if not os.path.exists(_PSKpath):
edouard@2492:             errorlog(
Edouard@2324:                 'Error: Pre-Shared-Key Secret in %s is missing!\n' % _PSKpath)
Edouard@2324:             return None
edouard@2492:         ID, _sep, PSK = open(_PSKpath).read().partition(':')
Edouard@2324:         PSK = PSK.rstrip('\n\r')
edouard@2492:         return (ID, PSK)
Edouard@2324:     return None