Andrew Boyson / crypto

Dependents:   oldheating gps motorhome heating

Revision:
5:ee5489ee1117
Child:
6:819c17738dc2
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tls/tls-connection.c	Wed Aug 28 07:10:59 2019 +0000
@@ -0,0 +1,74 @@
+#include <stdlib.h>
+
+#include "tls-connection.h"
+#include "mstimer.h"
+
+#define MAX_CONNECTIONS 4
+
+static struct TlsConnection connections[MAX_CONNECTIONS];
+
+static void zeroConnection(struct TlsConnection* p)
+{
+    p->id       = 0;
+    p->lastUsed = 0;
+    p->toDo     = 0;
+    p->session  = 0;
+    Sha256Start(&p->handshakeHash); //This just clears any information previously calculated
+}
+
+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);
+    }
+}