move to new cspot

This commit is contained in:
philippe44
2023-03-25 16:48:41 -07:00
parent c712b78931
commit 008c36facf
2983 changed files with 465270 additions and 13569 deletions

View File

@@ -0,0 +1,120 @@
#ifndef BELL_LOGGER_H
#define BELL_LOGGER_H
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <string>
#include <memory>
namespace bell
{
class AbstractLogger
{
public:
bool enableSubmodule = false;
virtual void debug(std::string filename, int line, std::string submodule, const char *format, ...) = 0;
virtual void error(std::string filename, int line, std::string submodule, const char *format, ...) = 0;
virtual void info(std::string filename, int line, std::string submodule, const char *format, ...) = 0;
};
extern bell::AbstractLogger* bellGlobalLogger;
class BellLogger : public bell::AbstractLogger
{
public:
// static bool enableColors = true;
void debug(std::string filename, int line, std::string submodule, const char *format, ...)
{
printf(colorRed);
printf("D ");
if (enableSubmodule) {
printf(colorReset);
printf("[%s] ", submodule.c_str());
}
printFilename(filename);
printf(":%d: ", line);
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
};
void error(std::string filename, int line, std::string submodule, const char *format, ...)
{
printf(colorRed);
printf("E ");
if (enableSubmodule) {
printf(colorReset);
printf("[%s] ", submodule.c_str());
}
printFilename(filename);
printf(":%d: ", line);
printf(colorRed);
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
};
void info(std::string filename, int line, std::string submodule, const char *format, ...)
{
printf(colorBlue);
printf("I ");
if (enableSubmodule) {
printf(colorReset);
printf("[%s] ", submodule.c_str());
}
printFilename(filename);
printf(":%d: ", line);
printf(colorReset);
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
};
void printFilename(std::string filename)
{
#ifdef _WIN32
std::string basenameStr(filename.substr(filename.rfind("\\") + 1));
#else
std::string basenameStr(filename.substr(filename.rfind("/") + 1));
#endif
unsigned long hash = 5381;
for (char const &c : basenameStr)
{
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
printf("\033[0;%dm", allColors[hash % NColors]);
printf("%s", basenameStr.c_str());
printf(colorReset);
}
private:
static constexpr const char *colorReset = "\033[0m";
static constexpr const char *colorRed = "\033[0;31m";
static constexpr const char *colorBlue = "\033[0;34m";
static constexpr const int NColors = 15;
static constexpr int allColors[NColors] = {31, 32, 33, 34, 35, 36, 37, 90, 91, 92, 93, 94, 95, 96, 97};
};
void setDefaultLogger();
void enableSubmoduleLogging();
}
#define BELL_LOG(type, ...) \
do \
{ \
bell::bellGlobalLogger->type(__FILE__, __LINE__, __VA_ARGS__); \
} while (0)
#endif

View File

@@ -0,0 +1,123 @@
#ifndef BELL_TASK_H
#define BELL_TASK_H
#include <string>
#ifdef ESP_PLATFORM
#include <esp_pthread.h>
#include <esp_task.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/timers.h>
#elif _WIN32
#include <winsock2.h>
#else
#include <pthread.h>
#endif
#include <string>
#include <iostream>
namespace bell {
class Task {
public:
std::string TASK;
int stackSize, core;
bool runOnPSRAM;
Task(std::string taskName, int stackSize, int priority, int core,
bool runOnPSRAM = true) {
this->TASK = taskName;
this->stackSize = stackSize;
this->core = core;
this->runOnPSRAM = runOnPSRAM;
#ifdef ESP_PLATFORM
this->xStack = NULL;
this->priority = CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT + priority;
if (this->priority <= ESP_TASK_PRIO_MIN)
this->priority = ESP_TASK_PRIO_MIN + 1;
if (runOnPSRAM) {
this->xStack = (StackType_t*)heap_caps_malloc(
this->stackSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
}
#endif
}
virtual ~Task() {
#ifdef ESP_PLATFORM
if (xStack)
heap_caps_free(xStack);
#endif
}
bool startTask() {
#ifdef ESP_PLATFORM
if (runOnPSRAM) {
xTaskBuffer = (StaticTask_t*)heap_caps_malloc(
sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
return (xTaskCreateStaticPinnedToCore(
taskEntryFuncPSRAM, this->TASK.c_str(), this->stackSize, this,
this->priority, xStack, xTaskBuffer, this->core) != NULL);
} else {
printf("task on internal %s", this->TASK.c_str());
esp_pthread_cfg_t cfg = esp_pthread_get_default_config();
cfg.stack_size = stackSize;
cfg.inherit_cfg = true;
cfg.thread_name = this->TASK.c_str();
cfg.pin_to_core = core;
cfg.prio = this->priority;
esp_pthread_set_cfg(&cfg);
}
#endif
#if _WIN32
thread = CreateThread(NULL, stackSize,
(LPTHREAD_START_ROUTINE)taskEntryFunc, this, 0, NULL);
return thread != NULL;
#else
return (pthread_create(&thread, NULL, taskEntryFunc, this) == 0);
#endif
}
protected:
virtual void runTask() = 0;
private:
#if _WIN32
HANDLE thread;
#else
pthread_t thread;
#endif
#ifdef ESP_PLATFORM
int priority;
StaticTask_t* xTaskBuffer;
StackType_t* xStack;
static void taskEntryFuncPSRAM(void* This) {
Task* self = (Task*)This;
self->runTask();
// TCB are cleanup in IDLE task, so give it some time
TimerHandle_t timer =
xTimerCreate("cleanup", pdMS_TO_TICKS(5000), pdFALSE, self->xTaskBuffer,
[](TimerHandle_t xTimer) {
heap_caps_free(pvTimerGetTimerID(xTimer));
xTimerDelete(xTimer, portMAX_DELAY);
});
xTimerStart(timer, portMAX_DELAY);
vTaskDelete(NULL);
}
#endif
static void* taskEntryFunc(void* This) {
Task* self = (Task*)This;
self->runTask();
#if _WIN32
WaitForSingleObject(self->thread, INFINITE);
#else
pthread_join(self->thread, NULL);
#endif
return NULL;
}
};
} // namespace bell
#endif

View File

@@ -0,0 +1,105 @@
#ifndef EUPHONIUM_BELL_UTILS
#define EUPHONIUM_BELL_UTILS
#include <string.h>
#ifdef _WIN32
#include <WinSock2.h>
#else
#include <sys/time.h>
#endif
#include <random>
#include <vector>
#ifdef ESP_PLATFORM
//#include "esp_mac.h"
#include "esp_system.h"
#endif
namespace bell {
std::string generateRandomUUID();
void freeAndNull(void*& ptr);
std::string getMacAddress();
struct tv {
tv() {}
tv(timeval tv) : sec(tv.tv_sec), usec(tv.tv_usec){};
tv(int32_t _sec, int32_t _usec) : sec(_sec), usec(_usec){};
static tv now() {
tv timestampNow;
#if _WIN32
static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
time = ((uint64_t)file_time.dwLowDateTime);
time += ((uint64_t)file_time.dwHighDateTime) << 32;
timestampNow.sec = (long)((time - EPOCH) / 10000000L);
timestampNow.usec = (long)(system_time.wMilliseconds * 1000);
#else
timeval t;
gettimeofday(&t, NULL);
timestampNow.sec = t.tv_sec;
timestampNow.usec = t.tv_usec;
#endif
return timestampNow;
}
int32_t sec;
int32_t usec;
int64_t ms() { return (sec * (int64_t)1000) + (usec / 1000); }
tv operator+(const tv& other) const {
tv result(*this);
result.sec += other.sec;
result.usec += other.usec;
if (result.usec > 1000000) {
result.sec += result.usec / 1000000;
result.usec %= 1000000;
}
return result;
}
tv operator/(const int& other) const {
tv result(*this);
int64_t millis = result.ms();
millis = millis / other;
result.sec = std::floor(millis / 1000.0);
result.usec = (int32_t)((int64_t)(millis * 1000) % 1000000);
return result;
}
tv operator-(const tv& other) const {
tv result(*this);
result.sec -= other.sec;
result.usec -= other.usec;
while (result.usec < 0) {
result.sec -= 1;
result.usec += 1000000;
}
return result;
}
};
} // namespace bell
#ifdef ESP_PLATFORM
#include <freertos/FreeRTOS.h>
#define BELL_SLEEP_MS(ms) vTaskDelay(ms / portTICK_PERIOD_MS)
#define BELL_YIELD() taskYIELD()
#elif defined(_WIN32)
#define BELL_SLEEP_MS(ms) Sleep(ms)
#define BELL_YIELD() ;
#else
#include <unistd.h>
#define BELL_SLEEP_MS(ms) usleep(ms * 1000)
#define BELL_YIELD() ;
#endif
#endif

View File

@@ -0,0 +1,83 @@
#ifndef BELL_CRYPTO_H
#define BELL_CRYPTO_H
#define Crypto CryptoMbedTLS
#include <vector>
#include <string>
#include <memory>
#include <stdexcept>
extern "C" {
#include "aes.h"
}
#include <mbedtls/base64.h>
#include <mbedtls/bignum.h>
#include <mbedtls/md.h>
#include <mbedtls/aes.h>
#include <mbedtls/pkcs5.h>
#include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h>
#define DH_KEY_SIZE 96
static unsigned char DHPrime[] = {
/* Well-known Group 1, 768-bit prime */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9,
0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6,
0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e,
0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6,
0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e,
0x34, 0x04, 0xdd, 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a,
0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14,
0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45,
0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4,
0x4c, 0x42, 0xe9, 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
static unsigned char DHGenerator[1] = {2};
class CryptoMbedTLS {
private:
mbedtls_md_context_t sha1Context;
mbedtls_aes_context aesCtx;
bool aesCtxInitialized = false;
public:
CryptoMbedTLS();
~CryptoMbedTLS();
// Base64
std::vector<uint8_t> base64Decode(const std::string& data);
std::string base64Encode(const std::vector<uint8_t>& data);
// Sha1
void sha1Init();
void sha1Update(const std::string& s);
void sha1Update(const std::vector<uint8_t>& vec);
std::string sha1Final();
std::vector<uint8_t> sha1FinalBytes();
// HMAC SHA1
std::vector<uint8_t> sha1HMAC(const std::vector<uint8_t>& inputKey, const std::vector<uint8_t>& message);
// AES CTR
void aesCTRXcrypt(const std::vector<uint8_t>& key, std::vector<uint8_t>& iv, uint8_t* data, size_t nbytes);
// AES ECB
void aesECBdecrypt(const std::vector<uint8_t>& key, std::vector<uint8_t>& data);
// Diffie Hellman
std::vector<uint8_t> publicKey;
std::vector<uint8_t> privateKey;
void dhInit();
std::vector<uint8_t> dhCalculateShared(const std::vector<uint8_t>& remoteKey);
// PBKDF2
std::vector<uint8_t> pbkdf2HmacSha1(const std::vector<uint8_t>& password, const std::vector<uint8_t>& salt, int iterations, int digestSize);
// Random stuff
std::vector<uint8_t> generateVectorWithRandomData(size_t length);
};
#endif

View File

@@ -0,0 +1,47 @@
#pragma once
#include <vector>
#include "pb_encode.h"
#include "pb_decode.h"
#include <string>
std::vector<uint8_t> pbEncode(const pb_msgdesc_t *fields, const void *src_struct);
pb_bytes_array_t* vectorToPbArray(const std::vector<uint8_t>& vectorToPack);
void packString(char* &dst, std::string stringToPack);
std::vector<uint8_t> pbArrayToVector(pb_bytes_array_t* pbArray);
template <typename T>
T pbDecode(const pb_msgdesc_t *fields, std::vector<uint8_t> &data)
{
T result = {};
// Create stream
pb_istream_t stream = pb_istream_from_buffer(&data[0], data.size());
// Decode the message
if (pb_decode(&stream, fields, &result) == false) {
printf("Decode failed: %s\n", PB_GET_ERROR(&stream));
}
return result;
}
template <typename T>
void pbDecode(T &result, const pb_msgdesc_t *fields, std::vector<uint8_t> &data)
{
// Create stream
pb_istream_t stream = pb_istream_from_buffer(&data[0], data.size());
// Decode the message
if (pb_decode(&stream, fields, &result) == false) {
printf("Decode failed: %s\n", PB_GET_ERROR(&stream));
}
}
void pbPutString(const std::string &stringToPack, char* dst);
void pbPutCharArray(const char * stringToPack, char* dst);
void pbPutBytes(const std::vector<uint8_t> &data, pb_bytes_array_t &dst);
const char* pb_encode_to_string(const pb_msgdesc_t *fields, const void *data);

View File

@@ -0,0 +1,117 @@
#ifndef BELL_QUEUE_H
#define BELL_QUEUE_H
#include <queue>
#include <atomic>
#include <condition_variable>
#include <atomic>
namespace bell
{
template <typename dataType>
class Queue
{
private:
/// Queue
std::queue<dataType> m_queue;
/// Mutex to controll multiple access
mutable std::mutex m_mutex;
/// Conditional variable used to fire event
std::condition_variable m_cv;
/// Atomic variable used to terminate immediately wpop and wtpop functions
std::atomic<bool> m_forceExit = false;
public:
/// <summary> Add a new element in the queue. </summary>
/// <param name="data"> New element. </param>
void push(dataType const &data)
{
m_forceExit.store(false);
std::unique_lock<std::mutex> lk(m_mutex);
m_queue.push(data);
lk.unlock();
m_cv.notify_one();
}
/// <summary> Check queue empty. </summary>
/// <returns> True if the queue is empty. </returns>
bool isEmpty() const
{
std::unique_lock<std::mutex> lk(m_mutex);
return m_queue.empty();
}
/// <summary> Pop element from queue. </summary>
/// <param name="popped_value"> [in,out] Element. </param>
/// <returns> false if the queue is empty. </returns>
bool pop(dataType &popped_value)
{
std::unique_lock<std::mutex> lk(m_mutex);
if (m_queue.empty())
{
return false;
}
else
{
popped_value = m_queue.front();
m_queue.pop();
return true;
}
}
/// <summary> Wait and pop an element in the queue. </summary>
/// <param name="popped_value"> [in,out] Element. </param>
/// <returns> False for forced exit. </returns>
bool wpop(dataType &popped_value)
{
std::unique_lock<std::mutex> lk(m_mutex);
m_cv.wait(lk, [&]() -> bool
{ return !m_queue.empty() || m_forceExit.load(); });
if (m_forceExit.load())
return false;
popped_value = m_queue.front();
m_queue.pop();
return true;
}
/// <summary> Timed wait and pop an element in the queue. </summary>
/// <param name="popped_value"> [in,out] Element. </param>
/// <param name="milliseconds"> [in] Wait time. </param>
/// <returns> False for timeout or forced exit. </returns>
bool wtpop(dataType &popped_value, long milliseconds = 1000)
{
std::unique_lock<std::mutex> lk(m_mutex);
m_cv.wait_for(lk, std::chrono::milliseconds(milliseconds), [&]() -> bool
{ return !m_queue.empty() || m_forceExit.load(); });
if (m_forceExit.load())
return false;
if (m_queue.empty())
return false;
popped_value = m_queue.front();
m_queue.pop();
return true;
}
/// <summary> Queue size. </summary>
int size()
{
std::unique_lock<std::mutex> lk(m_mutex);
return static_cast<int>(m_queue.size());
}
/// <summary> Free the queue and force stop. </summary>
void clear()
{
m_forceExit.store(true);
std::unique_lock<std::mutex> lk(m_mutex);
while (!m_queue.empty())
{
//delete m_queue.front();
m_queue.pop();
}
lk.unlock();
m_cv.notify_one();
}
/// <summary> Check queue in forced exit state. </summary>
bool isExit() const
{
return m_forceExit.load();
}
};
}
#endif

View File

@@ -0,0 +1,8 @@
//
// Created by Filip Grzywok on 28/02/2022.
//
#ifndef EUPHONIUMCLI_TIMEDEFS_H
#define EUPHONIUMCLI_TIMEDEFS_H
#endif // EUPHONIUMCLI_TIMEDEFS_H

View File

@@ -0,0 +1,91 @@
#ifndef _AES_H_
#define _AES_H_
#include <stdint.h>
#include <stddef.h>
// #define the macros below to 1/0 to enable/disable the mode of operation.
//
// CBC enables AES encryption in CBC-mode of operation.
// CTR enables encryption in counter-mode.
// ECB enables the basic ECB 16-byte block algorithm. All can be enabled simultaneously.
// The #ifndef-guard allows it to be configured before #include'ing or at compile time.
#ifndef CBC
#define CBC 1
#endif
#ifndef ECB
#define ECB 1
#endif
#ifndef CTR
#define CTR 1
#endif
// #define AES128 1
#define AES192 1
//#define AES256 1
#define AES_BLOCKLEN 16 // Block length in bytes - AES is 128b block only
#if defined(AES256) && (AES256 == 1)
#define AES_KEYLEN 32
#define AES_keyExpSize 240
#elif defined(AES192) && (AES192 == 1)
#define AES_KEYLEN 24
#define AES_keyExpSize 208
#else
#define AES_KEYLEN 16 // Key length in bytes
#define AES_keyExpSize 176
#endif
struct AES_ctx
{
uint8_t RoundKey[AES_keyExpSize];
#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
uint8_t Iv[AES_BLOCKLEN];
#endif
};
void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key);
#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv);
void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv);
#endif
#if defined(ECB) && (ECB == 1)
// buffer size is exactly AES_BLOCKLEN bytes;
// you need only AES_init_ctx as IV is not used in ECB
// NB: ECB is considered insecure for most uses
void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf);
void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf);
#endif // #if defined(ECB) && (ECB == !)
#if defined(CBC) && (CBC == 1)
// buffer size MUST be mutile of AES_BLOCKLEN;
// Suggest https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
// NOTES: you need to set IV in ctx via AES_init_ctx_iv() or AES_ctx_set_iv()
// no IV should ever be reused with the same key
void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
#endif // #if defined(CBC) && (CBC == 1)
#if defined(CTR) && (CTR == 1)
// Same function for encrypting as for decrypting.
// IV is incremented for every block, and used after encryption as XOR-compliment for output
// Suggesting https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
// NOTES: you need to set IV in ctx with AES_init_ctx_iv() or AES_ctx_set_iv()
// no IV should ever be reused with the same key
void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
#endif // #if defined(CTR) && (CTR == 1)
#endif // _AES_H_

View File

@@ -0,0 +1,4 @@
#ifdef __XTENSA__
#include <xtensa/config/core-isa.h>
#include <xtensa/config/core-matmap.h>
#endif