runtime/Stunnel.py
author Edouard Tisserant <edouard@beremiz.fr>
Tue, 23 Jul 2024 17:05:59 +0200
changeset 3999 1479acf750e2
parent 3884 34da877021d5
permissions -rw-r--r--
MQTT: WIP fix modified status not being set when adding and modifying topics or attributes.

Fix loading of CSV that was not applying model types, and that not checking conformance either.


import os
from binascii import b2a_base64
try:
    from runtime.spawn_subprocess import call
except ImportError:
    from subprocess import call

restart_stunnel_cmdline = ["/etc/init.d/S50stunnel", "restart"]

_PSKpath = None


def restartStunnel():
    """
    Restart stunnel service using SysV init stript
    to apply new generated credentials
    """
    try:
        call(restart_stunnel_cmdline)
    except OSError:
        print(_("Couldn't restart stunnel service"))


def PSKgen(ID, PSKpath):

    # secret string length is 256
    # b2a_base64 output len is 4/3 input len
    secret = os.urandom(192)  # int(256/1.3333)
    secretstring = b2a_base64(secret)

    PSKstring = ID+":"+secretstring
    with open(PSKpath, 'w') as f:
        f.write(PSKstring)
    restartStunnel()


def ensurePSK(ID, PSKpath):
    global _PSKpath
    _PSKpath = PSKpath
    # check if already there
    if not os.path.exists(PSKpath):
        # create if needed
        PSKgen(ID, PSKpath)


def getPSKID(errorlog):
    if _PSKpath is not None:
        if not os.path.exists(_PSKpath):
            errorlog(
                'Error: Pre-Shared-Key Secret in %s is missing!\n' % _PSKpath)
            return ("","")
        ID, _sep, PSK = open(_PSKpath).read().partition(':')
        PSK = PSK.rstrip('\n\r')
        return (ID, PSK)
    return ("","")