Andrew Boyson / crypto

Dependents:   oldheating gps motorhome heating

tls/tls-connection.c

Committer:
andrewboyson
Date:
2019-09-07
Revision:
8:5e66a6b4b38c
Parent:
6:819c17738dc2
Child:
10:e269fd7b9500

File content as of revision 8:5e66a6b4b38c:

#include <stdlib.h>

#include "tls-connection.h"
#include "mstimer.h"

#define MAX_CONNECTIONS 4

static struct TlsConnection connections[MAX_CONNECTIONS];

struct TlsConnection* TlsConnectionGetNext()
{
    static struct TlsConnection* p = connections + MAX_CONNECTIONS - 1; //Initialise to last element
    p++;
    if (p >= connections + MAX_CONNECTIONS) p = connections;
    return p;
}

static void zeroConnection(struct TlsConnection* p)
{
    p->id       = 0;
    p->lastUsed = 0;
    p->toDo     = 0;
    p->session  = 0;
    Sha256Start(&p->handshakeSha); //This just clears any information previously calculated
    p->clientEncrypted = false;
    p->serverEncrypted = false;
    for (int i = 0; i < TLS_RANDOM_SIZE; i++) p->clientRandom[i] = 0;
    for (int i = 0; i < TLS_RANDOM_SIZE; i++) p->serverRandom[i] = 0;
    for (int i = 0; i < TLS_DEFERRED_CONTENT_SIZE; i++) p->deferredContent[i] = 0;
}

struct TlsConnection* TlsConnectionNew(int connectionId) //Never fails so never returns NULL
{
    struct TlsConnection* p;
    
    //Look for an existing connection
    for (p = connections; p < connections + MAX_CONNECTIONS; p++)
    {
        if (p->id == connectionId) goto end;
    }
    
    //look for an empty connection
    {
        struct TlsConnection* pOldest = 0;
        uint32_t ageOldest = 0;
        for (p = connections; p < connections + MAX_CONNECTIONS; p++)
        {
            if (!p->id) goto end;
            
            //Otherwise record the oldest and keep going
            uint32_t age = MsTimerCount - p->lastUsed;
            if (age >= ageOldest)
            {
                ageOldest = age;
                  pOldest = p;
            }
        }
    
        //No empty ones found so use the oldest
        p = pOldest;
    }
    
end:
    zeroConnection(p);
    p->id           = connectionId;
    p->lastUsed     = MsTimerCount;
    return p;
}
struct TlsConnection* TlsConnectionOrNull(int connectionId)
{
    for (struct TlsConnection* p = connections; p < connections + MAX_CONNECTIONS; p++)
    {
        if (p->id == connectionId)
        {
            p->lastUsed = MsTimerCount;
            return p;
        }
    }
    return NULL;
}
void TlsConnectionReset(int connectionId)
{
    for (struct TlsConnection* p = connections; p < connections + MAX_CONNECTIONS; p++)
    {
        if (p->id == connectionId) zeroConnection(p);
    }
}